generic/131: dynamically allocate tcp listen port to avoid port clashes
authorTahsin Erdogan <tahsin@google.com>
Wed, 8 Jun 2016 18:52:41 +0000 (11:52 -0700)
committerEryu Guan <eguan@redhat.com>
Wed, 15 Jun 2016 07:37:41 +0000 (15:37 +0800)
Current port selection algorithm is bound to have port clashes. To
eliminate clashes, let server pick an unused port and report it on
stdout.

Signed-off-by: Tahsin Erdogan <tahsin@google.com>
Reviewed-by: Eryu Guan <eguan@redhat.com>
Signed-off-by: Eryu Guan <eguan@redhat.com>
src/locktest.c
tests/generic/131

index adf8ce05ccc5e7f28746e1cd5a75b60596a19a4a..eab48e2a012f71dd66ababe39f3b3bf51ff6e242 100644 (file)
@@ -95,7 +95,7 @@ static char   *filename = 0;
 static int     debug = 0;
 static int     server = 1;
 static int     maxio = 8192;
-static int     port = 7890;
+static int     port = 0;
 static int     testnumber = -1;
 static int     saved_errno = 0;
 
@@ -899,6 +899,20 @@ main(int argc, char *argv[])
            /*NOTREACHED*/
        }
 
+       if (port == 0) {
+               socklen_t addr_len = sizeof(myAddr);
+
+               if (getsockname(s_fd, &myAddr, &addr_len)) {
+                   perror("getsockname");
+                   exit(1);
+               }
+
+               port = ntohs(myAddr.sin_port);
+       }
+
+       printf("server port: %d\n", port);
+       fflush(stdout);
+
        c_fd = accept(s_fd, NULL, NULL);
        if (c_fd == INVALID_SOCKET) {
            perror("accept");
index 3bcb0d16a34b2306156939d5941225bddd6918d5..d64ba550e258b3c0cddcef5e666a3ea0a8e79677 100755 (executable)
@@ -49,21 +49,18 @@ _require_test_fcntl_advisory_locks
 
 TESTFILE=$TEST_DIR/lock_file
 
-# Grab a port which is hopefully unused
-if [ $$ -gt 1024 -a $$ -lt 32000 ]; then
-    PORT=$$
-elif [ $$ -lt 1024 ]; then
-    PORT=$(($$+1024))
-elif [ $$ -gt 32000 ]; then
-    PORT=$(($$%30000+1024))
-fi
-
 # Start the server
-src/locktest -p $PORT $TESTFILE 2>&1 > $TEST_DIR/server.out &
+src/locktest $TESTFILE 2>&1 > $TEST_DIR/server.out &
 locktest_pid1=$!
 
 sleep 1
 
+PORT=$(cat $TEST_DIR/server.out | grep "^server port: " | awk '{print $3}')
+if [ -z $PORT ]; then
+       echo "Could not get server port"
+       exit 1
+fi
+
 # Start the client
 src/locktest -p $PORT -h localhost $TESTFILE 2>&1 > $TEST_DIR/client.out
 locktest_pid2=$!