Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the source address of an incoming socket connection

Tags:

I have a server with a incoming socket from a client. I need the get the IP address of the remote client. Tried searching google for in_addr but it's a bit troublesome. Any suggestions?

like image 945
David Avatar asked Jan 14 '10 14:01

David


People also ask

How do I find my socket address?

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening: struct sockaddr_in sin; socklen_t len = sizeof(sin); if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1) perror("getsockname"); else printf("port number %d\n", ntohs(sin.

Do sockets have IP addresses?

A socket consists of the IP address of a system and the port number of a program within the system. The IP address corresponds to the system and the port number corresponds to the program where the data needs to be sent: Sockets can be classified into three categories: stream, datagram, and raw socket.

How do I find the IP address of a client connected to a server?

After the client establishes a successful connection to the server, the IP address of the client will be printed on the server console.

What is socket socket address?

A socket address is defined by the IP address of the socket and the port number allocated to the socket.


1 Answers

You need the getpeername function:

// 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); 
like image 80
Eli Bendersky Avatar answered Nov 02 '22 23:11

Eli Bendersky