trainworld_computercraft/computer/5/rednetcopy
2025-05-26 02:36:15 +02:00

61 lines
1.9 KiB
Text

require("rom/apis/rednet")
function lookup(protocol, hostname)
-- expect(1, protocol, "string")
-- expect(2, hostname, "string", "nil")
-- Build list of host IDs
local results = nil
if hostname == nil then
results = {}
end
-- Check localhost first
if hostnames and hostnames[protocol] then
if hostname == nil then
table.insert(results, {os.getComputerID(),os.getComputerLabel()})
elseif hostname == "localhost" or hostname == hostnames[protocol] then
return {os.getComputerID(),os.getComputerLabel()}
end
end
if not isOpen() then
if results then
return results
end
return {}
end
-- Broadcast a lookup packet
broadcast({
sType = "lookup",
sProtocol = protocol,
sHostname = hostname,
}, "dns")
-- Start a timer
local timer = os.startTimer(0.05)
-- Wait for events
while true do
local event, p1, p2, p3 = os.pullEvent()
if event == "rednet_message" then
-- Got a rednet message, check if it's the response to our request
local sender_id, message, message_protocol = p1, p2, p3
if message_protocol == "dns" and type(message) == "table" and message.sType == "lookup response" then
if message.sProtocol == protocol then
if hostname == nil then
table.insert(results, {sender_id,message.sHostname})
elseif message.sHostname == hostname then
return {sender_id,message.sHostname}
end
end
end
elseif event == "timer" and p1 == timer then
-- Got a timer event, check it's the end of our timeout
break
end
end
if results then
return results
end
return {}
end
return {lookup = lookup}