Chapter Contents

Previous

Next
getsockname

getsockname



Gets a Socket by Name

Portability: UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
PORTABILITY
EXAMPLE
RELATED FUNCTIONS


SYNOPSIS

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

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


DESCRIPTION

getsockname stores the address that is bound to a specified socket s in the buffer pointed to by addr . The addr and addrlen functions describe the buffer into which getsockname places the address of the socket. addr , as specified in the previous bind call, should point to a sockaddr structure or one of its derivatives, such as sockaddr_in .

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 socket, 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. If the socket has not been bound to an address, only the sa_family field is meaningful; all other fields are set to 0 .


RETURN VALUE

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


PORTABILITY

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


EXAMPLE

In this example getsockname returns the name of bound socket s .

#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 sa;
   int sa_len;
   .
   .
   .
      /* We must put the length in a variable.              */
   sa_len = sizeof(sa);
      /* Ask getsockname to fill in this socket's local     */
      /* address.                                           */
   if (getsockname(s, &sa, &sa_len) == -1) {
      perror("getsockname() failed");
      return -1;
   }

      /* Print it. The IP address is often zero beacuase    */
      /* sockets are seldom bound to a specific local       */
      /* interface.                                         */
   printf("Local IP address is: %s\n", inet_ntoa(sa.sin_add r));
   printf("Local port is: %d\n", (int) ntohs(sa.sin_port));
   .
   .
   .
}


RELATED FUNCTIONS

bind , getpeername


Chapter Contents

Previous

Next

Top of Page

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