Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local component = require("component")
- local computer = require("computer")
- local event = require("event")
- local serialization = require("serialization")
- local m = component.modem
- local isRunning = false
- local name = ""
- local isServer = false
- local dnsList = {}
- function start()
- if(isRunning) then
- print("Already running")
- return
- end
- if m == nil then
- print("No modem")
- return
- end
- if not m.isOpen(1) then
- m.open(1)
- end
- dnsList = {}
- event.listen("modem_message", onMessage)
- local c = loadConfig()
- local conf = c or {}
- isServer = conf.isServer or false
- name = conf.name or ""
- saveConfig(setDefault(setDefault(conf, "isServer", isServer),"name", name))
- if isServer then
- m.broadcast(1, "dns")
- else
- m.broadcast(1, "dns", 1, name)
- end
- isRunning = true
- end
- function stop()
- if not isRunning then
- print("Not running")
- return
- end
- if m == nil then
- print("No modem")
- return
- end
- if m.isOpen(1) then
- m.close()
- end
- event.ignore("modem_message", onMessage)
- isRunning = false
- end
- function send(address, port, ...)
- if isServer then
- onMessage(nil, m.address, m.address, 1, 0, address, port, ...)
- return
- end
- m.broadcast(1, address, port, ...)
- end
- function onMessage(_, localAddress, from, port, distance, to, toPort, ...)
- if not isRunning then
- return
- end
- if port ~= 1 then
- return
- end
- if isServer then
- if to == "dns" and toPort == 1 then
- addClient(from, ...)
- return
- end
- if to == name then
- computer.pushSignal("modem_message", localAddress, from, toPort, distance, ...)
- return
- end
- local na = dnsList[to]
- if na == nil then return end
- m.send(na, toPort, ...)
- return
- else
- if to == "dns" and toPort == nil then
- m.broadcast(1, "dns", 1, name)
- end
- end
- end
- function addClient(client, na)
- dnsList[na] = client
- end
- function loadConfig()
- local env = {}
- local result, reason = loadfile('/etc/dns.cfg', 't', env)
- if result then
- result, reason = xpcall(result, debug.traceback)
- if result then
- return env
- end
- end
- return nil, reason
- end
- function saveConfig(conf)
- local file, reason = io.open('/etc/dns.cfg', 'w')
- if not file then
- return nil, reason
- end
- for key, value in pairs(conf) do
- file:write(tostring(key) .. " = " .. serialization.serialize(value) .. "\n")
- end
- file:close()
- return true
- end
- function setDefault(conf, name, data)
- conf[name] = data
- return conf
- end
- function getName(n)
- n.name = name
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement