简体   繁体   中英

Socket programming port help python

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM