The getpeername function can be used to retrieve the peer IP address and port number on a given socket. For this to work, the socket should have a valid TCP connection established. Typically this is used by server to find the IP address and port number of client.

In the following code snippet, a TCP server binds to port number 5555 and waits for clients. It retrieves client’s IP address and port number using getpeername if a client is connected.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/un.h>

int main()
{
	struct sockaddr_in sin;
	struct in_addr in;
	int sd, client_sd, len;

	/* create a socket */
	sd = socket(AF_INET,SOCK_STREAM,0);

	/* let the OS use any unused port */
	sin.sin_family = AF_INET;
	sin.sin_addr.s_addr = htonl(INADDR_ANY);
	sin.sin_port = htons(5555);

	/* bind */
	if(bind(sd,(struct sockaddr *)&sin, sizeof(sin)) < 0) {
		perror("bind");
		exit(1);
	}

	/* listen */
	listen(sd,10);

	while(1) {

		client_sd = accept(sd,NULL,NULL);
		if(client_sd < 0) {
			perror("accept");
			break;
		}

		memset(&sin,0,sizeof(&sin));
		len = sizeof(sin);
		getpeername(client_sd,(struct sockaddr*)&sin, &len);

		memset(&in,0,sizeof(in));
		in.s_addr = sin.sin_addr.s_addr;

		printf("Remote Peer IP Address: %s\n", inet_ntoa(in));
		printf("Remote Peer Port Number: %d\n", ntohs(sin.sin_port));
		printf("----------------\n");

		close(client_sd);
	}
	printf("client_sd = %d\n", client_sd);
	close(sd);
	return 0;
}

Compile the above program using gcc and run the server as shown below (assuming file name to be tcpser.c). Note that the server listens on port 5555.

[neo@techpulp test]# gcc tcpser.c -o tcpser
[neo@techpulp test]# ./tcpser

Now use telnet program to connect to the server as shown below.

[neo@techpulp test]# telnet 127.0.0.1 5555
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
[neo@techpulp test]#

You should see similar to the following on the console where server is run.

[neo@techpulp test]# ./tcpser
Remote Peer IP Address: 127.0.0.1
Remote Peer Port Number: 38300
----------------
<-- CTRL+C
[neo@techpulp test]# ./tcpser