getpeername - Linux


The getpeername command provides information about the remote end of a connected socket. It retrieves the address and port of the peer connected to the socket specified by the sock argument. getpeername is commonly used with network programming and socket communication to determine the identity of the other party connected to the socket.


getpeername sock


This command does not have any options or flags.


  • Getting the address and port of the peer connected to a socket:
$ sockname=$(nc -l 8080 )
$ getpeername $sockname
  • Using getpeername in a script to determine the remote IP address:
$ sockname=$(nc -l 8080)
$ addr=$(getpeername $sockname | awk -F ':' '{print $1}')
$ echo $addr

Common Issues

  • Error "Bad file descriptor": Ensure the provided socket descriptor is valid and refers to a connected socket.
  • Incorrect address or port information: Check if the socket is connected to the expected peer. Firewall or network configurations may also affect the results.


getpeername can be integrated with other networking commands:

  • nc to establish connections and retrieve socket descriptors.
  • netstat to view active connections and identify socket descriptors.
  • awk to parse and extract specific information from the output.

Related Commands

  • getsockname: Retrieves the address and port of the local end of a socket.
  • netstat: Displays network connections and socket-related information.
  • nc: A versatile tool for creating and connecting to network sockets.