views:

306

answers:

2

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? Thanks to anyone who replies.

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;
+6  A: 

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.

James McNellis
That is exactly what I needed to do, thank you.
Silmaril89
+2  A: 

what your are getting is the raw 32 bit integer representation of the IP address. to get the familiar dot separated string, use the function:

 char * inet_ntoa(struct in_addr addr);

that will convert the integer to a static string.

Alon