function::inet_get_local_port - Linux


The inet_get_local_port function retrieves the local port number associated with a socket. This is useful for determining the port that an incoming connection has been received on, or for identifying the port that a client socket is using to communicate with a server.


int inet_get_local_port(const int sockfd);

| Parameter | Description |
| sockfd | The socket file descriptor for which to retrieve the local port number. |




#include <sys/socket.h>
#include <netinet/in.h>

int main() {
  int sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if (sockfd == -1) {
    return -1;

  struct sockaddr_in addr;
  socklen_t addrlen = sizeof(addr);
  if (getsockname(sockfd, (struct sockaddr *) &addr, &addrlen) == -1) {
    return -1;

  printf("Local port: %d\n", ntohs(addr.sin_port));

  return 0;

This example creates a TCP socket, retrieves the local port number associated with the socket using the inet_get_local_port function, and prints the port number to the console.

Common Issues

One common issue that can occur when using the inet_get_local_port function is that it may return -1 if the socket is not valid. This can happen if the socket has been closed or if it is not associated with a valid network interface. Always check the return value of inet_get_local_port to ensure that it is not -1 before using the returned port number.


The inet_get_local_port function can be used with other Linux commands and tools to perform various tasks related to network programming. For example, it can be used with the netstat command to display the local port numbers of all open sockets on the system. It can also be used with the nc command to connect to a remote host on a specific port.

Related Commands

  • inet_get_peer_port – Retrieves the remote port number associated with a socket.
  • getsockname – Retrieves the local address and port number associated with a socket.
  • netstat – Displays information about network connections, including local and remote port numbers.
  • nc – A command-line tool for establishing network connections.