Ticket #1684: netstat.cpp.2.diff

File netstat.cpp.2.diff, 2.1 KB (added by mjw, 16 years ago)

I hope this one is more acceptable

  • netstat.cpp

     
    2222#include <stdlib.h>
    2323#include <string.h>
    2424#include <unistd.h>
     25#include <getopt.h>
    2526
    2627
    2728extern const char* __progname;
    2829const char* kProgramName = __progname;
    2930
     31static int sResolveNames = 1;
    3032
    3133struct address_family {
    3234    int         family;
     
    5961        return;
    6062    }
    6163
    62     hostent* host = gethostbyaddr((const char*)&address.sin_addr,
    63         sizeof(sockaddr_in), AF_INET);
    64     servent* service = getservbyport(ntohs(address.sin_port), NULL);
     64    hostent* host = NULL;
     65    servent* service = NULL;
     66    if (sResolveNames) {
     67        host = gethostbyaddr((const char*)&(address.sin_addr), sizeof(in_addr), AF_INET);
     68        service = getservbyport(ntohs(address.sin_port), NULL);
     69    }
    6570
    6671    const char *hostName;
    6772    if (host != NULL)
     
    9499void
    95100usage(int status)
    96101{
    97     printf("usage: %s\n", kProgramName);
     102    printf("usage: %s [options]\n", kProgramName);
     103    printf("options:\n");
     104    printf("    -n  don't resolve names\n");
     105    printf("    -h  this help\n");
    98106
    99107    exit(status);
    100108}
     
    141149int
    142150main(int argc, char** argv)
    143151{
    144     if (argc > 1 && (!strcmp(argv[1], "--help") || !strcmp(argv[1], "-h")))
    145         usage(0);
     152    int optionIndex = 0;
     153    int opt;
     154    static struct option longOptions[] = {
     155        {"help", no_argument, 0, 'h'},
     156        {"numeric", no_argument, 0, 'n'},
     157        {0, 0, 0, 0}
     158    };
    146159
     160    do {
     161        opt = getopt_long(argc, argv, "hn", longOptions, &optionIndex);
     162        switch (opt) {
     163            case -1:
     164                // end of arguments, do nothing
     165                break;
     166
     167            case 'n':
     168                sResolveNames = 0;
     169                break;
     170
     171            case 'h':
     172            default:
     173                usage(0);
     174                break;
     175        }
     176    } while (opt != -1);
     177
    147178    int stack = open(NET_STACK_DRIVER_PATH, O_RDWR);
    148179    if (stack < 0) {
    149180        fprintf(stderr, "%s: The networking stack doesn't seem to be available.\n",
     
    152183    }
    153184
    154185    bool printProgram = true;
    155         // TODO: add some program options... :-)
     186        // TODO: add some more program options... :-)
    156187
    157188    printf("Proto  Recv-Q Send-Q Local Address         Foreign Address       State        Program\n");
    158189