tcpscript.c
changeset 3 01ec0b3b1135
parent 2 f08014d5d89f
child 5 470463cba5cf
child 9 3be85141e3eb
--- a/tcpscript.c	Sat Jun 09 18:07:06 2007 +0200
+++ b/tcpscript.c	Mon Jun 11 20:58:53 2007 +0200
@@ -39,7 +39,7 @@
  */
 
 /*
- * script
+ * tcpscript - Modified from script - 2007 Lluis Batlle i Rossell
  */
 #include <stdio.h>
 #include <stdlib.h>
@@ -91,6 +91,7 @@
 char	*cflg = NULL;
 int	qflg = 0;
 int	tcp_port = 4000;
+int	limit_conns = 1;
 
 enum {
     MAXCONNS = 10
@@ -141,7 +142,7 @@
 		}
 	}
 
-	while ((ch = getopt(argc, argv, "c:qp:")) != -1)
+	while ((ch = getopt(argc, argv, "c:qp:l:")) != -1)
 		switch((char)ch) {
 		case 'c':
 			cflg = optarg;
@@ -149,13 +150,16 @@
 		case 'p':
 			tcp_port = atoi(optarg);
 			break;
+		case 'l':
+			limit_conns = atoi(optarg);
+			break;
 		case 'q':
 			qflg++;
 			break;
 		case '?':
 		default:
 			fprintf(stderr,
-				"usage: script [-p port] [-q] [-t] \n");
+				"usage: script [-l nconns] [-p port] [-q] [-t] \n");
 			exit(1);
 		}
 	argc -= optind;
@@ -231,6 +235,16 @@
     exit(-1);
 }
 
+int set_reusable(int s)
+{
+    int boolean = 1;
+    int res;
+
+    res = setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &boolean, sizeof(boolean));
+    if (res != 0)
+        perror("Setsockopt REUSE failed"), fatal();
+}
+
 int listen_tcp()
 {
     int s;
@@ -241,6 +255,8 @@
     if (s == -1)
         perror("Failed socket()"), fatal();
 
+    set_reusable(s);
+
     addr.sin_family = AF_INET;
     addr.sin_port = htons(tcp_port);
     addr.sin_addr.s_addr = INADDR_ANY;
@@ -336,7 +352,7 @@
                 perror("accept() failed");
                 break;
             }
-            if (nconns < (MAXCONNS - 1))
+            if (nconns < (MAXCONNS - 1) && nconns < limit_conns)
             {
                 FD_SET(s, &should_read_set);
                 conns[nconns] = s;