UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

#1 2002-07-26 11:11 PM

HectorLasso
Administrator
From: Colombia
Registered: 2002-06-12
Posts: 353

Re: 4.9 - How to find out the client's address/hostname

6
From Andrew Gierth (andrew@erlenstar.demon.co.uk):

After accept()ing a connection, use getpeername() to get the address of the client. The client's address is of course, also returned on the accept(), but it is essential to initialise the address-length parameter before the accept call for this will work.

Jari Kokko (jkokko@cc.hut.fi) has offered the following code to determine the client address:

int t;
int len;
struct sockaddr_in sin;
struct hostent *host;

len = sizeof sin;
if (getpeername(t, (struct sockaddr *) &sin, &len) < 0)
        perror("getpeername");
else {
        if ((host = gethostbyaddr((char *) &sin.sin_addr,
                                  sizeof sin.sin_addr,
                                  AF_INET)) == NULL)
            perror("gethostbyaddr");
        else printf("remote host is '%s'\n", host->h_name);
}

Offline

Board footer

Powered by FluxBB