Linux 4.19.133
[linux/fpc-iii.git] / tools / testing / selftests / bpf / tcp_server.py
blobb39903fca4c898c014811d5a302b7872aabb40fe
1 #!/usr/bin/env python3
3 # SPDX-License-Identifier: GPL-2.0
6 import sys, os, os.path, getopt
7 import socket, time
8 import subprocess
9 import select
11 def read(sock, n):
12 buf = b''
13 while len(buf) < n:
14 rem = n - len(buf)
15 try: s = sock.recv(rem)
16 except (socket.error) as e: return b''
17 buf += s
18 return buf
20 def send(sock, s):
21 total = len(s)
22 count = 0
23 while count < total:
24 try: n = sock.send(s)
25 except (socket.error) as e: n = 0
26 if n == 0:
27 return count;
28 count += n
29 return count
32 SERVER_PORT = 12877
33 MAX_PORTS = 2
35 serverPort = SERVER_PORT
36 serverSocket = None
38 HostName = socket.gethostname()
40 # create passive socket
41 serverSocket = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
42 host = socket.gethostname()
44 try: serverSocket.bind((host, 0))
45 except socket.error as msg:
46 print('bind fails: ' + str(msg))
48 sn = serverSocket.getsockname()
49 serverPort = sn[1]
51 cmdStr = ("./tcp_client.py %d &") % (serverPort)
52 os.system(cmdStr)
54 buf = b''
55 n = 0
56 while n < 500:
57 buf += b'.'
58 n += 1
60 serverSocket.listen(MAX_PORTS)
61 readList = [serverSocket]
63 while True:
64 readyRead, readyWrite, inError = \
65 select.select(readList, [], [], 2)
67 if len(readyRead) > 0:
68 waitCount = 0
69 for sock in readyRead:
70 if sock == serverSocket:
71 (clientSocket, address) = serverSocket.accept()
72 address = str(address[0])
73 readList.append(clientSocket)
74 else:
75 sock.settimeout(1);
76 s = read(sock, 1000)
77 n = send(sock, buf)
78 sock.close()
79 serverSocket.close()
80 sys.exit(0)
81 else:
82 print('Select timeout!')
83 sys.exit(1)