0

I am trying to implement socket programming and want to configure the communication port number for both the server and client to a specific port. I specify the same port number on both the the client and server side but still when the program run's it takes a random port number. How do I fix the port number/make it static?

Server Side Code

import socket
s=socket.socket()
port=12345
s.bind(("192.168.0.111",port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("got connection from ",addr)
    sendingMessage = "Thank you for connecting"
    c.send(bytes(sendingMessage, 'UTF-8'))
    data = c.recv(16)
    receivedData=data.decode("utf-8","ignore")
    print (receivedData)
    c.close()
    if receivedData=="stop":
        break

Client Side Code

import socket
port=12345
s=socket.socket()
s.connect(("192.168.43.111",port))

sendingMessage = input("Enter your message : ")
s.send(bytes(sendingMessage, 'UTF-8'))

data = s.recv(32)
receivedData=data.decode("utf-8","ignore")
print (receivedData)

s.close
3
  • Cannot reproduce it, tcp 0 0 127.0.0.1:12345 0.0.0.0:* LISTEN 25027/python Commented Apr 12, 2016 at 14:25
  • 1
    That's how connection oriented sockets work. The port you specify is for the initial connection only. The second socket returned from accept() is used for the conversation, and that uses a "random" port. Commented Apr 12, 2016 at 14:30
  • @cdarke This is not correct. You get a different socket with accept not a different port (on the server side). In order to accept more than one connection from the client, the client would need to use a different port to connect since every 5-tuple (TCP, IP1, Port1, IP2, Port2) must be unique. Commented Apr 12, 2016 at 15:28

1 Answer 1

1

If you want the client side to also use port 12345, you must also bind the client side port number. The port number given in the s.connect is the remote port to which you're connecting. IOW, your code should look something like this in the client:

s = socket.socket()
s.bind(('', port))
s.connect(("192.168.43.111", port))

You can also specify an IP address in the bind but typically you don't need to as the local IP address will be established by the route to the remote host.

Sign up to request clarification or add additional context in comments.

2 Comments

When i bind the client with the same port number as the server it throws an error saying s.bind(("192.168.0.112",port)) OSError: [Errno 98] Address already in use
You can't run both of them on the same machine if they're both binding the same port. If this is on a different machine, then something else is using that port. Try netstat -apn to find out what's using it.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.