b80fbb2816334a91acd828b1f7787cdf33a11c7f
[vpp.git] / src / scripts / vnet / uri / dummy_app.py
1 #!/usr/bin/env python
2
3 import socket
4 import sys
5 import bitstring
6
7 # action can be reflect or drop 
8 action = "drop"
9
10 def handle_connection (connection, client_address):
11     print("Received connection from {}".format(repr(client_address)))
12     try:
13         while True:
14             data = connection.recv(4096)
15             if not data:
16                 break;
17             if (action != "drop"):
18                 connection.sendall(data)
19     finally:
20         connection.close()
21         
22 def run_server(ip, port):
23     print("Starting server {}:{}".format(repr(ip), repr(port)))
24     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
25     server_address = (ip, int(port))
26     sock.bind(server_address)
27     sock.listen(1)
28     
29     while True:
30         connection, client_address = sock.accept()
31         handle_connection (connection, client_address)
32
33 def prepare_data():
34     buf = []
35     for i in range (0, pow(2, 16)):
36         buf.append(i & 0xff)
37     return bytearray(buf)
38
39 def run_client(ip, port):
40     print("Starting client {}:{}".format(repr(ip), repr(port)))
41     sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
42     server_address = ("6.0.1.1", 1234)
43     sock.connect(server_address)
44     
45     data = prepare_data()
46     try:
47         sock.sendall(data)
48     finally:
49         sock.close()
50     
51 def run(mode, ip, port):
52     if (mode == "server"):
53         run_server (ip, port)
54     elif (mode == "client"):
55         run_client (ip, port)
56     else:
57         raise Exception("Unknown mode. Only client and server supported")
58
59 if __name__ == "__main__":
60     if (len(sys.argv)) < 4:
61         raise Exception("Usage: ./dummy_app <mode> <ip> <port> [<action>]")
62     if (len(sys.argv) == 5):
63         action = sys.argv[4]
64
65     run (sys.argv[1], sys.argv[2], sys.argv[3])