lookupX, The Rednet Lookup API eXtension

Started by cynagen, Sep 25, 2018, 08:20 PM

Previous topic - Next topic

cynagen

After working on the DNS server in a previous thread, I had to start digging into the RedNet API to discover how they handled the name hosting they had built in. After reading the code, I realized I didn't need a big server setup at all, and got working on this instead. An extension of the RedNet lookup command, adding functionality that I felt was otherwise missing. I figured I had a use-case scenario for this kind of reverse searching, maybe somebody else would too.

-- lookupX, The Rednet Lookup API eXtension
-- Author: Cynagen
-- ComputerCraft 1.6+
 
-- lookupScan( sProtocol ) - Takes single string argument for protocol to scan
-- Returns; On success: { sHostname1 = nID1, sHostname2 = nID2 }, On no hosts found: {}, On failure: nil
function rednet.lookupScan( sProtocol )
    if type( sProtocol ) ~= "string" then
        error( "expected string", 2 )
    end
    local sHostname = nil
 
    -- Build list of host IDs
    local tResults = {}
 
    -- Broadcast a lookup packet
    rednet.broadcast( {
        sType = "lookup",
        sProtocol = sProtocol,
        sHostname = sHostname,
    }, "dns" )
 
    -- Inject a lookup packet into the queue for the local machine (workaround for local RedNet lookup)
    os.queueEvent("rednet_message",os.computerID(),{sType="lookup",sProtocol=sProtocol,sHostname=sHostname},"dns")
 
    -- Start a timer
    local timer = os.startTimer( 2 )
 
    -- 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 nSenderID, tMessage, sMessageProtocol = p1, p2, p3
            if sMessageProtocol == "dns" and tMessage.sType == "lookup response" then
                if tMessage.sProtocol == sProtocol then
                    if sHostname == nil then
                        tResults[tMessage.sHostname]=nSenderID
                    end
                end
            end
        else
            -- Got a timer event, check it's the end of our timeout
            if p1 == timer then
                break
            end
        end
    end
    if tResults then
        return tResults
    end
    return nil
end
 
-- lookupName( sProtocol, nID ) - Takes string argument for protocol, numeric for computer ID to search for and return its hosted name
-- Returns; On success: sHostname1, On failure: nil
function rednet.lookupName( sProtocol, nID )
    if type( nID ) ~= "number" then
        error( "expected number", 2 )
    end
    for name,id in pairs(rednet.lookupScan(sProtocol)) do
        if id==nID then return name end
    end
    return nil
end

Download:
pastebin get qscf3kCA lookupXLoad:
lua> os.loadAPI("lookupX")