Frage

I'm trying to contact an A/V device through UDP. I send a packet to local broadcast 192.168.0.255, and it responds with information about the device. I can verify it works with Wireshark. However, I never get the response in Python, it just sits there:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) #Internet, UDP
s.bind(('', 64000))
#s.sendto('0:0',('192.168.0.255',63630))
s.connect(('192.168.0.255',63630));
s.send('0:0')
#s.listen(1)
data,addr = s.recvfrom(1024)
print data
print 'from', addr

I'm sending it from 64000 (random port) to the 63630 port, so binding and receiving at the 64000 port it was sent from, and gets sent back to, should work, correct? Am I missing a step?

War es hilfreich?

Lösung

Turn on SO_BROADCAST option to send broadcast message:

s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

Also replace following

s.connect(('192.168.0.255',63630))
s.send('0:0')

with:

s.sendto('0:0', ('192.168.0.255',63630))

According to Linux connect(2) manpage:

If the socket sockfd is of type SOCK_DGRAM then addr is the address to which datagrams are sent by default, and the only address from which datagrams are received.

According to MSDN - connect (Windows Sockets):

For a connectionless socket (for example, type SOCK_DGRAM), the operation performed by connect is merely to establish a default destination address that can be used on subsequent send/WSASend and recv/WSARecv calls. Any datagrams received from an address other than the destination address specified will be discarded.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top