How do I get my server to find out the clients address / host- name?

Answer Posted / chaitanya

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.

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);

}

Is This Answer Correct ?    0 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

How many sockets can a port have?

483


What is a socket set used for?

506


What is a socket connection?

508


What are the pros/cons of select(), non-blocking I/O and SIGIO?

978


What is the difference between a socket and a port?

467






Why sockets are used?

525


Is there any advantage to handling the signal, rather than just ignoring it and checking for the EPIPE error? Are there any useful parameters passed to the signal catching function?

1041


Can multiple clients connect to same socket?

518


How do unix sockets work?

493


What is socket address with example?

495


What is a socket api?

533


How can I tell when a socket is closed on the other end?

975


What does af mean in sockets?

524


What is the purpose of socket?

505


How do I use TCP_NODELAY?

1111