tags:

views:

160

answers:

3

i have a server with a incoming socket from a client. i need the get the ip addr of the remote client. tried searing google for in_addr but its a bit troublesome. any suggestions? thanks

+3  A: 

man getpeername

Nikolai N Fetissov
+3  A: 

You need the getpeername function. The great Beej's guide to networking has a page about it. Here's a code sample from there:

// assume s is a connected socket

socklen_t len;
struct sockaddr_storage addr;
char ipstr[INET6_ADDRSTRLEN];
int port;

len = sizeof addr;
getpeername(s, (struct sockaddr*)&addr, &len);

// deal with both IPv4 and IPv6:
if (addr.ss_family == AF_INET) {
    struct sockaddr_in *s = (struct sockaddr_in *)&addr;
    port = ntohs(s->sin_port);
    inet_ntop(AF_INET, &s->sin_addr, ipstr, sizeof ipstr);
} else { // AF_INET6
    struct sockaddr_in6 *s = (struct sockaddr_in6 *)&addr;
    port = ntohs(s->sin6_port);
    inet_ntop(AF_INET6, &s->sin6_addr, ipstr, sizeof ipstr);
}

printf("Peer IP address: %s\n", ipstr);
Eli Bendersky
A: 

Since you say it is an incoming connection from a client, as an alternative to getpeername you can just save the address that was returned by the accept() call, in the second and third parameters.

caf