Home > Back-end >  Simulate computer network with docker containers & socket programming
Simulate computer network with docker containers & socket programming

Time:08-21

I am trying to build simulation of real computers on the network for some project I am doing, my goal is to build python script that listening on some random port and accepting new clients. like some service on the internet. I heard that I can achive that with containers, but I have no experiance with docker at all. can someone help me with the commands I need to run in the terminal in order to achive that?. after I will be able to run one container I want to run several containers that using the same code but listening on different ports.

this is my Dockerfile:

FROM python:latest

ADD relay.py /Users/<username>/Desktop/containers/

WORKDIR /containers/

EXPOSE 9898

CMD [ "python3", "/containers/relay.py" ]

this is an example of relay.py that I want to run on several different containers to simulate servers on the network:

import socket
import threading

host = "0.0.0.0"
port = 9898


def handle_client(sock):
    sock.sendall(b'Hello from relay')


def main():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.bind((host, port))
        sock.listen(1)
        print("start listing on port %s" % (port))
        while True:
            c_sock, addr = sock.accept()
            new_client = threading.Thread(target=handle_client, args=(c_sock,))
            new_client.start()


if __name__ == "__main__":
    main()

CodePudding user response:

In your Python code, take the port as a command-line parameter.

import argparse

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('--bind', default='0.0.0.0')
  parser.add_argument('--port', type=int, default=9898)
  args = parser.parse_args()
  with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
    sock.bind((args.bind, args.port))
    ...

Now if you want to set up multiple listeners on different ports, you can just run multiple copies of this process; you don't need Docker at all.

./relay.py --port 9898 &
./relay.py --port 9899 &
./relay.py --port 9900 &

nc localhost:9898 </dev/null
  • Related