Sockets and IP addresses

Started by
2 comments, last by Krun 19 years, 7 months ago
I hate asking questions like this because I know the solution is something simple, and I even have the nagging feeling I've done this before, but for the life of me I can't seem to find a way to identify the IP address of a user connected to my winsock server. Now, considering the bit of code used to connect a user is pretty simple: user->socket = accept(sock,&user->addr,&size); It seems to me that the information must be available either from the socket itself, or in the sockaddr structure that's also used. The problem of course is, that I can't seem to find a way to use these to get an IP address of the user. I don't suppose there's any function like GetIP(SOCKET sock); anywhere, is there? Any help would be greatly appreciated, as I'd very much like to be able to give my MUD server more meaningful logs, as well as a possible means of banning delinquent users.
-Arek the Absolute"The full quartet is pirates, ninjas, zombies, and robots. Create a game which involves all four, and you risk being blinded by the sheer level of coolness involved." - Superpig
Advertisement

yes, the ip address is in the sockaddr_in structure: addr.sin_addr is a 32bit number with the ip address. if you want to convert it to a string (i.e. "127.0.0.1") then use inet_ntoa(addr.sin_addr).

hth
Chris
First, check that the sa_family field of the socket address is AF_INET. It will always be this if you've bound to an AF_INET network interface, so you could skip the check if you wanted.

Second, just cast your sockaddr structure to (sockaddr_in &) and read out the sin_addr.addr and sin_port fields. Remember to use ntohl() and ntohs() appropriately.

If you need to get the IP of the remote side after accept(), you can use getpeername(). You can also get your own LOCAL IP address using getsockname(). Note that the local address may NOT be what the remote end actually sees, because of NAT gateways/firewalls. (Corollary: what you get from accept() or getpeername() may not be what the remote side would get from a getsockname()).
enum Bool { True, False, FileNotFound };
Why not use the "getnameinfo" function? It will give you the name of the host and the port, or if you specify the NI_NUMERICHOST flag, a number address (e.g. 124.34.133.121)

This topic is closed to new replies.

Advertisement