lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

UDP broadcast error

Thu Aug 07, 2014 4:49 pm

Code: Select all

import socket, time, os
from socket import gethostname

host = ''                               # Bind to all interfaces
port = 51423

#gw=[default, via, 10.0.0.1, dev, wlan0]

gw=os.popen("ip -4 route show default").read().split()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)                
s.connect((gw[2],0))
myip=s.getsockname()[0]
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)   #broadcasr

#gethostname=raspberrypi
#myip = socket.gethostbyaddr(socket.gethostname())
print 'My IP',myip

# XX: assumes /24 address
broadcastip = socket.inet_ntoa(socket.inet_aton(myip)[:3] + b'\xff' )
print 'LAN broadcast', broadcastip


addr=(broadcastip, port)

data='Pi IP@'+myip
print 'send string is', data

s.bind((' ', port))                  #socket binding to any host

while True:
	s.sendto(data, addr)
	time.sleep(3)				#sleep 3 seconds
s.bind((' ', port)) causes an error, it said No address associate with hostname. how do i fix it.

User avatar
Douglas6
Posts: 4861
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: UDP broadcast error

Thu Aug 07, 2014 5:34 pm

I'm guessing the "any server" should be a null string. You've got one space in there. I think it wants to be

Code: Select all

s.bind(('', port)) 

User avatar
DougieLawson
Posts: 39124
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: UDP broadcast error

Thu Aug 07, 2014 7:22 pm

Douglas6 wrote:I'm guessing the "any server" should be a null string. You've got one space in there. I think it wants to be

Code: Select all

s.bind(('', port)) 
INADDR_ANY for IPv4 is 0.0.0.0

So if a null string doesn't work try

Code: Select all

s.bind(('0.0.0.0', port))
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All non-medical doctors are on my foes list.

lilzz
Posts: 411
Joined: Sat Nov 30, 2013 5:27 pm

Re: UDP broadcast error

Fri Aug 08, 2014 4:04 pm

Hi, Both approaches still give me errors.

only way works is if I comment it out

#s.bind(('', port))

is bind function necessary for board casting ?

Return to “Python”