Chapter Contents

Previous

Next
getservbyname

getservbyname



Gets Service Information by Name

Portability: UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTION
PORTABILITY
IMPLEMENTATION
EXAMPLE
RELATED FUNCTIONS


SYNOPSIS

#include <netdb.h>

struct servent *getservbyname(const char *name, const char *proto);


DESCRIPTION

Given the name of a well-known service, pointed to by name , and a protocol string for accessing that service, pointed to by proto , getservbyname returns a pointer to the servent structure, which is defined in <netdb.h> . This structure is typically used to obtain the port for the service from the serv_port field. The source of the data in this structure is the services file, that is, a file with the same format as the /etc/services file on a UNIX operating system. Refer to <netdb.h> for details on the servent structure.

Refer to Search Logic for information on the logic used to determine the location of the services file.


RETURN VALUE

If getservbyname succeeds, it returns a pointer to the servent structure. A null pointer indicates an error or an end-of-file.


CAUTION

The value that getservbyname returns points to a static structure within the library. You must copy the information from this structure before you make further getservbyname , getservbyport , or getservent calls.


PORTABILITY

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


IMPLEMENTATION

getservbyname is ported directly from the BSD UNIX Socket Library.


EXAMPLE

This program uses the socket call, getservbyname to obtain the structure,

servent

. In most cases the returned structure is used to obtain the port for the service. getservbyname reads the prefix.ETC.SERVICES file. The prefix .ETC.SERVICES file must be properly configures on the local host; where prefix is described in Network Administration. The input parameters are case sensitive.

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
main(int argc, char *argv[])
{
   struct servent *serv;

   if (argc < 3) {
      puts("Incorrect parameters. Use:");
      puts("   gsbnm service-name protocol-name");
      return EXIT_FAILURE;
   }

   /* getservbyname() - opens the etc.services file and returns the */
   /* values for the requested service and protocol.                */

   serv = getservbyname(argv[1], argv[2]);
   if (serv == NULL) {
      printf("Service "%s" not found for protocol "%s"\n",
         argv[1], argv[2]);
      return EXIT_FAILURE;
   }

   /* Print it. */
   printf("Name: %-15s  Port: %5d    Protocol: %-6s\n",
             serv->s_name,ntohs(serv->s_port),serv->s_proto);
   return EXIT_SUCCESS;
}


RELATED FUNCTIONS

endservent , setservent , getservent , getservbyport


Chapter Contents

Previous

Next

Top of Page

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