getpeername: Return the name of the peer

The getpeername socket function returns the address of the peer connected to socket s.

Last updated

  • Changed for PUT13.
  • Added for PUT00.

Format

#include  <sys/socket.h>
int       getpeername(int s,
                      struct sockaddr *name,
                      int *namelen);
s
The socket descriptor.
name
Pointer to the sockaddr buffer. On return, the buffer contains the name of the remote peer of the socket.
namelen
Size of the address structure that the name parameter points to in bytes. The namelen parameter must be initialized to indicate the size of the space pointed to by the name parameter and is set to the number of bytes copied into the space before the call returns. If the buffer of the local host is too small, the peer name is truncated.

Normal return

Return code 0 indicates that the function was successful.

Error return

A return code equal to -1 indicates an error. You can get the specific error code by calling the sock_errno function. See z/TPF Transmission Control Protocol/Internet Protocol for more information about socket errors.
SOCNOTSOCK
The s parameter is not a valid socket descriptor.
SOCNOTCONN
The socket is not in the connected state.
E1052STATE
The socket was closed because the system was in or cycling down to 1052 state.
SOCINVAL
The namelen parameter is not a valid length.

Programming considerations

  • This function applies to all connected sockets for both TCP and UDP protocols.
  • The length passed must be a minimum of 32 bytes.
  • A UNIX domain stream socket that is not bound to a path name by using the bind function is unnamed. Similarly, the two UNIX domain sockets that are created by using the socketpair function are unnamed. When the address of an unnamed socket is returned, a NULL value is returned for the sun_path field.

Examples

  • The following example obtains the peer socket address.
    #include <sys/socket.h>
    ⋮
    int addrlen;
    int rc,
    int newclient_sock;
    int server_sock;
    struct sockaddr_in client_addr;
    ⋮
    newclient_sock = accept(server_sock, (struct sockaddr *) 0, (int) 0);
    ⋮
    addrlen = sizeof(client_addr);
    rc = getpeername(newclient_sock, (struct sockaddr *)&client_addr,
                    &addrlen);
  • The following example obtains the peer socket address for a UNIX domain socket.
    #include <sys/socket.h>
    ⋮
    int addrlen;
    int rc,
    int newclient_sock;
    int server_sock;
    struct sockaddr_un client_addr;
    ⋮
    newclient_sock = accept(server_sock, (struct sockaddr *) 0, (int) 0);
    ⋮
    addrlen = sizeof(client_addr);
    rc = getpeername(newclient_sock, (struct sockaddr *)&client_addr,               
            &addrlen);
    if (rc == -1){     
            printf("GETPEERNAME ERROR = %d\n", sock_errno());
    }