Search code examples
cloopssegmentation-faulthostent

Loop to get multiple entries in host, network, protocol, and service database


I am having a hard time understanding a previous assignment. I was to use functions given in the Addison-Wesley Advanced Programming in the UNIX Environment Third edition text (chapter 16.3.3) to print the host, network, protocol, and services database to the standard output. The feedback my professor gave is below.

Needs serious work (-40); each section of the output needs to contain (possibly) many entries, and must be read in a loop Service port numbers incorrect (-5); the port is a short (NOT an int and in network byte order!); it must be converted using ntohs(3).

My issue is in looping the program to get multiple entries, as I'm not sure how this can be done, especially with the addresses in h_addr_list, since I get Segfaults trying to access anything past [0]. Does the loop have anything to do with the value of h_length?

Here is the code as submitted for the feedback above:

   /*
    * Dawson Binder
    * Assignment 10 - assign10.c
    * displays the host, network, protocol, and services databases. 
    */
    #include <stdio.h>
    #include <stdlib.h>
    #include <netdb.h>
    #include <arpa/inet.h>
    int main(int argc, char *argv[])
    {
        char address[36];
        struct hostent *hPtr = gethostent();    // print host name, address type, address length, and the addresses
        struct netent *nPtr = getnetent();
        struct protoent *pPtr = getprotoent();
        struct servent *sPtr = getservent();

        // Host
        printf("\nHost Name: %s\nAddress Type: %d\nAddress Length: %d\n", hPtr->h_name, hPtr->h_addrtype, hPtr->h_length);
        inet_ntop(AF_INET, hPtr->h_addr_list[0], address, 36);
        printf("Address: %s\n", address);
        // end Host

        // Network
        printf("Network Name: %s\nNetwork Number: %u\n", nPtr->n_name, nPtr->n_net);
        // end Network

        //Protocol
        printf("Protocol Name: %s\nProtocol Number: %d\n", pPtr->p_name, pPtr->p_proto);
        //end Protocol

        //Service Database
                printf("Service Database Name: %s\nService Database Port: %d\nServiceDatabase Protocol: %s\n\n", sPtr->s_name, sPtr->s_port, sPtr->s_proto);    
        //end Service Database
        return 0;
    }

Solution

  • Each time you call those four get*ent() functions, they will return one entry of their database, until they return NULL. Read their manpage to know more, e.g. getservent(3). You may also want to close the database connection with their end*net() counterparts.

    See also related questions like How to loop getprotent() function.