Generally, sock.bind(('',port))
is all you need to receive messages on a port. It means "listen for incoming packets that port on all interfaces" You don't give an idea what 'XX.XXX.XX.XX' refers but you don't have to be specific unless you only want to listen to a specific interface. You don't bind when sending to a port, you just sock.sendto(msg,(serverip,port))
. The host receiving the packet also gets the address it was sent from and can .sendto()
that address for a reply.
Here's an example client/server interaction:
server.py
import socket
HOST = '' # receive on all interfaces
PORT = 5000
server = socket.socket(type=socket.SOCK_DGRAM)
server.bind((HOST,PORT))
while True:
data,(ip,port) = server.recvfrom(4096)
msg = data.decode()
print(f'from {ip}:{port}> {msg}')
if msg == 'quit': break # terminate server
server.sendto(f'Response: <{msg}>'.encode(), (ip,port))
print('SERVER EXIT')
client.py
import socket
SERVER = 'localhost' # or specific IP of host accessible by client
PORT = 5000
client = socket.socket(type=socket.SOCK_DGRAM)
while True:
msg = input('Client> ')
client.sendto(msg.encode(), (SERVER,PORT))
if not msg or msg == 'quit': break # empty message to quit client only
response,addr = client.recvfrom(4096)
print(response.decode())
print('CLIENT EXIT')
Demo (client):
C:\> client
Client> test1
Response: <test1>
Client> test2
Response: <test2>
Client> # empty message only quits client
CLIENT EXIT
C:\> client # 2nd client
Client> test3
Response: <test3>
Client> 你好!
Response: <你好!>
Client> quit # quit client and server
CLIENT EXIT
Demo (server):
C:\> server
from 127.0.0.1:49164> test1
from 127.0.0.1:49164> test2
from 127.0.0.1:49164>
from 127.0.0.1:49165> test3 # note client port change for 2nd client
from 127.0.0.1:49165> 你好!
from 127.0.0.1:49165> quit
SERVER EXIT