Chapter Contents

Previous

Next
getpeername

getpeername



Gets the Address of a Peer

Portability: UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
PORTABILITY
EXAMPLE
RELATED FUNCTIONS


SYNOPSIS

#include <sys/types.h>
#include <sys/socket.h>

int getpeername(int s, void *addr, int *addrlen);


DESCRIPTION

getpeername stores the address of the peer that is connected to socket s . The addr and addrlen functions describe the buffer into which getpeername places the address of the new peer. addr points to a sockaddr structure or one of its derivatives, such as sockaddr_in , and addrlen points to an integer containing the size of the buffer in bytes. If the buffer size is not large enough to contain the address of the peer, the value of the address is not completely copied. No error is indicated in this situation. On return, the integer pointed to by addrlen is set to the length that was actually copied. For connected sockets, the address that is returned is the same as that returned by the recvfrom function.


RETURN VALUE

If getpeername succeeds, it returns a 0 . Otherwise, it returns a -1 , and sets errno to indicate the type of error.


PORTABILITY

getpeername is portable to other environments, including most UNIX systems, that implement BSD sockets.


EXAMPLE

In this example, getpeername returns the port and address of the peer program.

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>

f()
{
   int s;
   struct sockaddr_in peer;
   int peer_len;
   .
   .
   .
      /* We must put the length in a variable.              */
   peer_len = sizeof(peer);
      /* Ask getpeername to fill in peer's socket address.  */
   if (getpeername(s, &peer, &peer_len) == -1) {
      perror("getpeername() failed");
      return -1;
   }

      /* Print it. The IP address is often zero because     */
      /* sockets are seldom bound to a specific local       */
      /* interface.                                         */
   printf("Peer's IP address is: %s\n", inet_ntoa(peer.sin_addr));
   printf("Peer's port is: %d\n", (int) ntohs(peer.sin_port));
   .
   .
   .
}


RELATED FUNCTIONS

accept , bind , connect , getsockname , recvfrom


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.