[mw-devel] MW3 r1266 - trunk/src/server
welshbyte at sucs.org
welshbyte at sucs.org
Sun Nov 4 00:53:27 GMT 2012
Author: welshbyte
Date: 2012-11-04 00:53:27 +0000 (Sun, 04 Nov 2012)
New Revision: 1266
Modified:
trunk/src/server/mwserv.c
Log:
server: Add some getopt boilerplate to accept options from the commandline and print usage. Currently only accepts --port and --help options.
Modified: trunk/src/server/mwserv.c
===================================================================
--- trunk/src/server/mwserv.c 2012-11-03 21:16:43 UTC (rev 1265)
+++ trunk/src/server/mwserv.c 2012-11-04 00:53:27 UTC (rev 1266)
@@ -1,14 +1,82 @@
#include <stdio.h>
#include <fcntl.h>
+#include <stdlib.h>
+#include <getopt.h>
+#include <errno.h>
+#include <inttypes.h>
#include "../socket.h"
#include "servsock.h"
+struct servopts {
+ uint16_t port;
+ int help;
+};
+
+void usage(char *name)
+{
+ printf("Usage:\n %s [--help|-h][--port|-p <port>]\n", name);
+}
+
+static int getopts(int argc, char **argv, struct servopts *opts)
+{
+ int c;
+ int optidx = 0;
+ long num;
+ static struct option loptspec[] = {
+ {"port", required_argument, 0, 'p'},
+ {"help", no_argument, 0, 'h'},
+ {0, 0, 0, 0}
+ };
+
+ while (1) {
+ c = getopt_long(argc, argv, "p:h", loptspec, &optidx);
+ if (c == -1)
+ break;
+
+ switch (c) {
+ case 'p':
+ errno = 0;
+ num = strtol(optarg, NULL, 0);
+ if (errno != 0 || num < 1 || num > UINT16_MAX) {
+ fprintf(stderr, "Bad port number\n");
+ return 1;
+ }
+ opts->port = (uint16_t)num;
+ break;
+ case 'h':
+ opts->help = 1;
+ return 0;
+ case '?':
+ default:
+ return 1;
+ }
+ }
+
+ if (optind < argc) {
+ fprintf(stderr, "Unrecognised arguments: ");
+ while (optind < argc)
+ fprintf(stderr, "%s ", argv[optind++]);
+ fprintf(stderr, "\n");
+ return 1;
+ }
+ return 0;
+}
+
int main(int argc, char **argv)
{
+ struct servopts opts = {.port = IPCPORT_DEFAULT};
int mainsock = -1;
+ int err = getopts(argc, argv, &opts);
+
+ if (err || opts.help)
+ usage(argv[0]);
+
+ if (err)
+ return 1;
+
init_server();
- mainsock = open_mainsock(IPCPORT_DEFAULT);
+ mainsock = open_mainsock(opts.port);
if (mainsock < 0) {
fprintf(stderr, "Failed.\n");
More information about the mw-devel
mailing list