4

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?

NoBugs
  • 9,310
  • 13
  • 80
  • 146

1 Answers1

5

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.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • but it is sending broadcast, or else it would not be picked up by the device ip correct? – NoBugs Jan 26 '14 at 06:52
  • @NoBugs, To make it clear whether broadcast is problem or not, try to send message to specific IP (of A/V device). – falsetru Jan 26 '14 at 06:59
  • Right! Setting the ip's 0.255 to 0.realaddress works! So I have to find what the device ip is before doing this, broadcast doesn't work in Python? – NoBugs Jan 26 '14 at 07:22
  • @NoBugs, Broadcast works in Python. Maybe router does not allow broadcast.. or A/V device does not accept broadcast? – falsetru Jan 26 '14 at 07:24
  • I see the broadcast UDP sent and the UDP response in Wireshark – NoBugs Jan 26 '14 at 07:27
  • @NoBugs, What happen if you replace `s.connect(('192.168.0.255',63630)); s.send('0:0')` with `s.sendto('0:0', ('192.168.0.255',63630))` – falsetru Jan 26 '14 at 07:29
  • @NoBugs, I added explanation (quote) in the answer. Check it out. – falsetru Jan 26 '14 at 07:32