How to get IP address from sockaddr

adhanlon picture adhanlon · Dec 1, 2009 · Viewed 62.9k times · Source

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;

Answer

ofavre picture ofavre · Feb 9, 2012

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.