Sign in to follow this  
Arek the Absolute

Sockets and IP addresses

Recommended Posts

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.

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
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()).

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this