Monday, August 15, 2011

socket getservent sample c code



/*
 * getservent.c:
 * Example getservent(3) program:
 */
  #include <stdio.h>
  #include <unistd.h>
  #include <stdlib.h>
  #include <errno.h>
  #include <string.h>
  #include <time.h>
  #include <sys/types.h>
  #include <sys/socket.h>
  #include <netinet/in.h>
  #include <arpa/inet.h>


  int main(int argc, char **argv) {
     int x;
     struct servent *sp;

     for (;;) {
        errno = 0;
        if ( !(sp = getservent()) ) {
           break;
        }

        printf("%s:\n"
               "\tPort: %d\n"
               "\tProtocol: %s\n"
               "\tAliases: ",
               sp->s_name,
               ntohs(sp->s_port),
               sp->s_proto);
        for ( x=0; sp->s_aliases[x] != NULL; ++x ) {
           printf("%s ",sp->s_aliases[x]);
        }
        putchar('\n');
     }

     if ( errno != && errno != ENOENT ) { /* For RH-6.0 */
        fprintf(stderr,
                "%s: getservent(3) %d\n",
                strerror(errno),errno);
     }
     return 0;
  }

/*
 * OUTPUT
 * 
[sgupta@rhel55x86 chap7]$ gcc -o getservent getservent.c
[sgupta@rhel55x86 chap7]$ ./getservent
tcpmux:
        Port: 1
        Protocol: tcp
        Aliases:
tcpmux:
        Port: 1
        Protocol: udp
        Aliases:
rje:
        Port: 5
        Protocol: tcp
        Aliases:
rje:
        Port: 5
        Protocol: udp
        Aliases:
echo:
        Port: 7
        Protocol: tcp
        Aliases:
echo:
        Port: 7
        Protocol: udp
        Aliases:
discard:
        Port: 9
        Protocol: tcp
        Aliases: sink null
 iqobject:
        Port: 48619
        Protocol: udp
        Aliases:
[sgupta@rhel55x86 chap7]$
 */

No comments:

Post a Comment