Reputation: 33
Instead on posting my mile long script here is a short example: I am creating a TCP/IP connection between two computers each running one of the following scripts:
server:
# server.py
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host, port))
s.listen(5)
while True:
c, addr = s.accept()
print 'Connection from', addr
c.close()
Client:
#client.py
import socket
s = socket.socket()
host = socket.socket()
port = 1234
s.connect((host, port))
print s.recv(1024)
which gives me a ready out like:
Connection from ('19*.1**.0.**', 54451)
Connection from ('19*.1**.0.**', 54452)
Connection from ('19*.1**.0.**', 54453)
Connection from ('19*.1**.0.**', 54454)
What is controlling the creation of the 54451-54454 numbers? I understand what it is; the port number assigned to the client side connection. I just cant seem to figure out how to control the number, or at least the range its issued in.
Is this even possible? Any suggestions would help immensely. Thank you in advance.
Upvotes: 3
Views: 4347
Reputation: 487725
Generally, your OS or runtime system assigns port IDs if you have not done so yourself.
TCP in particular has two ports per connection: a source port and a destination port, sometimes called local and remote. Using s.bind
sets the local port on the server, without setting any remote port (which makes sense: there's no actual connection yet). Using s.connect
sets the remote (destination) port on the client, without setting any local port.
When your client goes to send a connection request to the server, your client needs a local port. Since it does not have one yet, something—the OS or runtime system—picks one from a pool of available port IDs. It then binds that ID to the local side of the client's socket s
, and sends out a request with (I assume 192.168 RFC-1918 private-address space here):
<local-addr=192.168.xxx.xxx, local-port=54451, remote-addr=S, remote-port=1234>
(where S is the server's IP address).
The server sees the incoming request, creates a new socket with:
<local-addr=S, local-port=1234, remote-addr=192.168.xxx.xxx, remote-port=54451>
which as you can see is the same pair of IPaddr+port numbers, just swapped around.
That new socket is what s.accept
returns on the server, as c
.
If you want to assign your own local port on the client, you can call bind
there too, before calling connect
:
s.bind((0, port))
(Zero means "unassigned", so this leaves the local IP address unset. You can set a specific IP address, which is useful if your host is multi-homed.)
Upvotes: 3