network program

Started by aruljothi, Sep 28, 2008, 12:59 PM

Previous topic - Next topic

aruljothi

#include <iostream>
#include <stdlib.h>

// This is okay for small programs
using std::cout;
using std::endl;


// Help message for clueless users
void help() {
  cout << "typical: [(-p|--port) ####] ";
          "[(-n|--network network_id) ####]\n";
  cout << "  where:\n";
  cout << "  -p (--port) is the port number\n";
  cout << "     defaults to port 80 if not specified.\n";
  cout << "     Port 0 is an invalid port.\n";
  cout << "  -n (--network) is the network id\n";
  cout << "     defaults to 128.0.0.1 if not specified.\n";
}


int main(int argc, char* argv[]) {
  int  iPort = 80;
  char *network = "128.0.0.1";

  // A home-grown parsing algorithm starts here
  for(int i = 1; i < argc; ++i) {
    if (strcmp(argv, "-p") == 0 ||
        strcmp(argv, "--port") == 0) {
      if (i+1 == argc) {
        // error messages intermingled with parsing logic
        cout << "Invalid " << argv;
        cout << " parameter: no port number specified\n";
        help();
        exit(1); // multiple exit points in parsing algorithm
      }
      iPort = atoi(argv[++i]);  // parsing action goes here
    }
    else if (strcmp(argv, "-n") == 0 ||
             strcmp(argv, "--network") == 0) {
      if (i+1 == argc) {
        cout << "Invalid " << argv;
        cout << " parameter: no network ID specified\n";
        help();
        exit(1);
      }
      network = argv[++i];
    }
    else if (strcmp(argv, "--version") == 0) {
      cout << "Version 1.0\n";
      exit(0);
    }
  }

  // post-parsing parameter validation
  if (iPort == 0) {
    help();
    exit(1);
  }

  cout << "Port = " << iPort << endl;
  cout << "Network = " << network << endl;

  return 0;
}