2008年9月
C 语言参数读取代码
效果图
static struct option long_options[] = {
{"help", no_argument, NULL, 'h'},
{"tcp", required_argument, NULL, 't'},
{"udp", required_argument, NULL, 'u'},
{"ip", required_argument, NULL, 'i'},
{"ping", no_argument, NULL, 'p'},
{"size", required_argument, NULL, 's'},
{"count", required_argument, NULL, 'c'},
{"log", required_argument, NULL, 'l'},
{NULL, 0, NULL, 0}
};
void usage(int status)
{
if (status != 0)
printf("Try `%s --help' for more information.\n",
program_name);
else {
printf("IPGen : IP packets generator\n");
printf("Version %s\n", VERSION);
printf("Leo Liang <leo.liang@china.com>\n\n");
printf("Usage: program_name [option] ... src_ip dest_ip\n");
printf("\nIP packets type:\n");
printf(" -t, --tcp=PORT TCP\n");
printf(" -u, --udp=PORT UDP\n");
printf(" -i, --ip=PROTO IP\n");
printf(" -p, --ping Ping(ICMP)\n");
printf("\nPackets size:\n");
printf(" -s, --size=VALUE Packet size (default=%d)\n",
DEFAULT_PACKET_SIZE);
printf(" -c, --count=VALUE How many packets to send "
"(ignore when with -t, default=%d)\n",
DEFAULT_PACKET_COUNT);
printf("\nInfomation:\n");
printf(" -l, --log=LOGFILE Log to file\n");
printf(" --help Show this help\n");
}
exit(status);
}
int main(int argc, char* argv[])
{
/* parse options */
while ((c = getopt_long(argc, argv, "ht:u:i:ps:c:l:", long_options, NULL)) != -1) {
switch (c) {
case 'h':
usage(0);
break;
case 't':
packetType = IPPROTO_TCP;
packetTypeName = "TCP";
port = atoi(optarg);
printf("port = %d\n",port);
break;
case 'u':
packetType = IPPROTO_UDP;
packetTypeName = "UDP";
port = atoi(optarg);
break;
case 'i':
packetType = IPPROTO_RAW;
packetTypeName = "IP";
proto = atoi(optarg);
break;
case 'p':
packetType = IPPROTO_ICMP;
packetTypeName = "ping(ICMP)";
break;
case 's':
packetSize = atoi(optarg);
break;
case 'c':
packetCount = atoi(optarg);
break;
case 'l':
//OpenLog(optarg, LOG_INFO);
OpenLog(optarg, LOG_DEBUG);
break;
default:
usage(1);
}
}