I've been trying to do this for a while. I tried following this http://lua.2524044.n2.nabble.com/UDP-Broadcast-td3995269.html, but to no avail. I've successfully sent unicast messages between the client and server. I've confirmed my broadcast address is correct. The only other thing I can think of is sniffing my interface to make sure there's no network problems. I'm gonna get around to that tomorrow, but wanted to post this here to see if anyone might notice a stupid mistake.
Note: I'm running the client and the server on the same laptop.
client
local socket = require("socket")
local s_address, s_port = "192.168.1.135", 33333
local d_address, d_port = "192.168.1.255", 22222
udp = socket.udp()
assert(udp)
assert(udp:settimeout(1))
assert(udp:setoption('broadcast', true))
assert(udp:setoption('dontroute',true))
assert(udp:setsockname(s_address, s_port))
while true do
tosend = string.format("client %s:%s", s_address, s_port)
print(string.format('sending to %s:%s...', d_address, d_port))
udp:sendto(tosend, d_address, d_port)
data, msg = udp:receive()
toprint = string.format("data = \"%s\"", data)
print(toprint)
socket.sleep(.5)
end
server
local socket = require("socket")
local s_address, s_port = "192.168.1.135", 11111
local p_address, p_port = "192.168.1.255", 22222
udp = socket.udp()
assert(udp)
assert(udp:setoption('broadcast', true))
assert(udp:setoption('dontroute',true))
assert(udp:settimeout(1))
assert(udp:setsockname(s_address, s_port))
assert(udp:setpeername(p_address, p_port))
while true do
data = udp:receive()
print(string.format('listening on %s:%s...', p_address, p_port))
toprint = string.format("data = \"%s\"", data)
print(toprint)
if data then
msg_back = "server received your message"
udp:send(msg_back)
end
socket.sleep(.5)
end
output
Both sides continually print data = "nil"
.
I had been looking to implement luasocket broadcast myself, and this was one of the few pages on the internet that even brought the topic up. In the end, between the luasocket API and some python code I was able to adapt, I found a solution that works for me: