How to get IP address from sockaddr


Question

I want to try and get the ip address of a client after calling accept. This is what I have so far, but I just end up getting some long number that is clearly not an ip address. What could be wrong?

int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);

sockaddr_in client;
client.sin_family = AF_INET;
socklen_t c_len = sizeof(client);

int acc_tcp_sock = accept(tcp_sock, (sockaddr*)&client, &c_len);
cout << "Connected to: " << client.sin_addr.s_addr << endl;
1
24
9/21/2015 11:19:34 AM

Accepted Answer

That long number is the IP address, in integer form (an IP address is just an integer, after all; it's just easier for people to use when we split the octets apart and put it into dot notation).

You can use inet_ntoa to convert the integer value to standard dot notation.

28
12/1/2009 6:16:37 AM

Seen from http://beej.us/guide/bgnet/examples/client.c:

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa)
{
    if (sa->sa_family == AF_INET)
        return &(((struct sockaddr_in*)sa)->sin_addr);
    return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

// [...]

struct addrinfo *p;
char s[INET6_ADDRSTRLEN];
inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr), s, sizeof s);

It uses inet_ntop, which is preferred over inet_ntoa (non thread-safe) as it handles IPv4 and IPv6 (AF_INET and AF_INET6) and should be thread-safe I think.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon