how to avoid two socket with same port number python
Question: Now here is sample for the server part of socket. I want to have serverSocket
and connectionSocket with different port number, but for now, they are using
same port number.

    
    
    from socket import *
    serverPort = 12000
    serverSocket = socket(AF_INET,SOCK_STREAM)
    serverSocket.bind((‘’,serverPort))
    serverSocket.listen(1)
    print (‘The server is ready to receive’)
    while 1:
     connectionSocket, addr = serverSocket.accept()
    
     sentence = connectionSocket.recv(1024)
     capitalizedSentence = sentence.upper()
     connectionSocket.send(capitalizedSentence)
     connectionSocket.close()
    

if they are using same port number, would there be some collision?


Answer: There is nothing to avoid, and there is really no easy way to avoid it - this
is how TCP is supposed to work.

In TCP there are 2 kinds of sockets:

  * listening server sockets
  * connected sockets

The server sockets start listening to incoming connections with `listen`; and
wait for client connections with `accept`. Clients create a socket that is
connected to the server address `(host, port)`. When the server `accept`s a
connection, a **new** connected socket is created between the
`(client_address, client_port)` and `(server_address, server_port)`. The TCP
stack on the server can see from **status bits** easily if the packet is a
connection request, or destined to an already connected socket. If it is a
communication between already connected sockets, then it finds out the file
descriptor that is bound on the local address and local port **and** is
connected with the source address, source port of the remote end.

The connected socket will have the same port as the listening server socket;
both Ende of the socket know 4 things: _local address_ , _local port_ ,
_remote address_ and _remote port_. You can have 1 server socket bound on
`10.20.30.40:12345` at the same time with thousands of sockets connected from
`10.20.30.40:12345` to thousands distinct addresses.

There is really congestion only in the connection attempt phase; the
`server_socket.listen(1)` means that the server will queue just 1 incoming
connection; subsequent connections will be rejected until the incoming
connection is accepted.

From Linux manual pages, `listen(2)` on the `backlog` argument of
`sock.listen`:

> The backlog argument defines the maximum length to which the queue of
> pending connections for sockfd may grow. If a connection request arrives
> when the queue is full, the client may receive an error with an indication
> of `ECONNREFUSED` or, if the underlying protocol supports retransmission,
> the request may be ignored so that a later reattempt at connection succeeds.

