Reputation: 120
I am trying to set up a UDP unicast between two linux-machines on my local network, using the python sockets library. I manage to send and receive the package using the following code:
Send
import socket
HOST = '192.168.1.194' # IP of remote machine
PORT = 47808
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.sendto('Hello UDP', (HOST, PORT))
s.close()
Receive
import socket
HOST = ''
PORT = 47808
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((HOST, PORT))
while True:
try:
data, addr = s.recvfrom(1024)
print 'Received: {0} @ {1}'.format(data, addr)
except KeyboardInterrupt:
break
s.close()
However, binding to ''
makes the receiving code accept packets from any local interface. If I try to bind to the IP address of the sending machine specifically (changing HOST = ''
to HOST = '192.168.1.130'
in the receiving code), I get a socket.error: [Errno 99] Cannot assign requested address
. No other services are using the port, and I have tried different ports with no change in behaviour. How can I configure my socket to only receive packets from a specific address?
Upvotes: 2
Views: 800
Reputation: 168596
First, let's deal with the error you are seeing. .bind()
names the local end of the socket, not the remote. So the host part must refer to the local machine (e.g., 'localhost'
, '127.0.0.1
, '192.168.1.194'
, or ''
(wildcard for all local interfaces).) So, when you specify an address that isn't local to the machine running .bind()
, you get an error.
Second, there is no way to "configure my socket to only receive packets from a specific address." As an alternative, you can use the returned address from .recvfrom()
to ignore data you don't care about.
data, addr = s.recvfrom(1024)
if addr != '192.168.1.130':
continue
Upvotes: 2