4

When I create a socket on a server and the accept an incoming connection:

conn, addr = s.accept()

Both print conn.getsockname() and print s.getsockname() print out the same port number.

I thought 'conn' was supposed to represent a NEW socket. How do I get the port number of this new socket?

Thanks!

2 Answers 2

6

The local port remains the same. What you want is the remote side's port. You can use getpeername for this (or the second element of accept's return value).

4
  • 1
    Thanks. If the local port stays the same, how does the server distinguish between data flows from different clients? Nov 12, 2010 at 19:21
  • 2
    By the combination of the source and target interfaces and ports.
    – Amnon
    Nov 12, 2010 at 19:24
  • Right, sockets are pairs of (host, port) tuples. Each pair is unique. (+1 for good question.) Nov 12, 2010 at 19:59
  • It should be a way to get this info directly, without having to save this data previously
    – NeDark
    Feb 12, 2015 at 21:24
0

It is a new socket, but it has the same local port as the original listening socket.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.