pythonsocketsnetwork-programmingtcpport

Python socket-module: How to change the local port on the client side?


I want to get packages from a network using TCP/IP as a client.

With ...

connect((TCP_IP, TCP_PORT))

... I can change the port of the peer address. But can I change the port of my local computer?

EDIT: I want to use a network card with four ports. The network card is connected to a measurement device that sends a lot of data. How can I see where the data goes? How can I distinguish between these four ports?


Solution

  • Assume you have a socket named sock... use socket.bind()

    import socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    DESTINATION_ADDR = '1.1.1.1'
    SOURCE_PORT, DESTINATION_PORT = 31415, 80
    sock.bind(('0.0.0.0', SOURCE_PORT))
    sock.connect((DESTINATION_ADDR, DESTINATION_PORT))
    

    Now I run tshark (text wireshark) to see my traffic on that interface...

    [mpenning@Bucksnort ~]$ sudo tshark -i eth0 tcp and port 31415
    Capturing on eth0
      0.000000 24.19.161.6 -> 1.1.1.1      TCP 31415 > http [SYN] Seq=0 Win=5840 Len=0 MSS=1460 TSV=4228124209 TSER=0 WS=6
     12.000009 24.19.161.6 -> 1.1.1.1      TCP 31415 > http [SYN] Seq=0 Win=5840 Len=0 MSS=1460 TSV=4228127209 TSER=0 WS=6
     36.000010 24.19.161.6 -> 1.1.1.1      TCP 31415 > http [SYN] Seq=0 Win=5840 Len=0 MSS=1460 TSV=4228133209 TSER=0 WS=6