Find local IP address and local port number using getsockname
In Category C/C++ Networking
The getsockname function can be used to find the local port used by a given socket. It is valid to use this function only if the socket is already using a local port number. i.e A server socket which invoked bind system call with zero as port number. A client socket which has established connection to a server. In either case operating system selects an unused port number automatically. Similarly this function can also be used on UDP sockets.
The following code snippet explains how to use getsockname to retrieve the local port number assigned by operating system.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
int main()
{
struct sockaddr_in sin;
struct in_addr in;
int 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(0);
/* bind */
bind(sd,(struct sockaddr *)&sin, sizeof(sin));
/* retrieve local port number using getsockname */
len = sizeof(sin);
getsockname(sd,(struct sockaddr *)&sin,&len);
memset(&in,0,sizeof(in));
in.s_addr = sin.sin_addr.s_addr;
printf("My Local IP Address: %s\n", inet_ntoa(in));
printf("My Local Port Number: %d\n", ntohs(sin.sin_port));
close(sd);
return 0;
}
In the above example, you would see the local IP address to be 0.0.0.0 always as the socket is bound to INADDR_ANY. Any new socket that gets created after accepting a client will have proper local IP address which can retrieved using getsockname.
Recent Comments