You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
1.8 KiB
63 lines
1.8 KiB
-- Network utilities module for auto-boot-ollama-host
|
|
-- Provides port checking and Wake-on-LAN functionality
|
|
|
|
local socket = require("socket")
|
|
local utils = require("utils")
|
|
|
|
local network = {}
|
|
|
|
-- Check if a TCP port is accepting connections within a timeout (seconds)
|
|
function network.port_is_up(host, port, timeout_sec)
|
|
host = tostring(host or "127.0.0.1")
|
|
port = tonumber(port or 0) or 0
|
|
local timeout = tonumber(timeout_sec or 1) or 1
|
|
if port <= 0 then return false end
|
|
|
|
local deadline = socket.gettime() + timeout
|
|
while socket.gettime() < deadline do
|
|
local tcp = socket.tcp()
|
|
if not tcp then return false end
|
|
tcp:settimeout(1)
|
|
local ok = tcp:connect(host, port)
|
|
tcp:close()
|
|
if ok then return true end
|
|
socket.sleep(0.5)
|
|
end
|
|
return false
|
|
end
|
|
|
|
-- Convert MAC address string to bytes
|
|
-- "AA:BB:CC:DD:EE:FF" -> 6 bytes
|
|
local function mac_to_bytes(mac)
|
|
local bytes = {}
|
|
for byte in mac:gmatch("(%x%x)") do
|
|
table.insert(bytes, tonumber(byte, 16))
|
|
end
|
|
if #bytes ~= 6 then return nil end
|
|
return string.char(table.unpack(bytes))
|
|
end
|
|
|
|
-- Send Wake-on-LAN magic packet
|
|
function network.send_wol(mac_str, bcast_ip, port)
|
|
-- Build magic packet
|
|
local bytes = {}
|
|
for byte in mac_str:gmatch("(%x%x)") do
|
|
table.insert(bytes, tonumber(byte, 16))
|
|
end
|
|
if #bytes ~= 6 then return false, "invalid MAC" end
|
|
|
|
local mac = string.char(table.unpack(bytes))
|
|
local packet = string.rep(string.char(0xFF), 6) .. mac:rep(16)
|
|
|
|
-- Create IPv4 UDP socket (udp4 if available), bind to IPv4 wildcard to lock AF_INET
|
|
local udp = assert((socket.udp4 or socket.udp)())
|
|
udp:settimeout(2)
|
|
assert(udp:setsockname("0.0.0.0", 0)) -- force IPv4 family
|
|
assert(udp:setoption("broadcast", true)) -- allow broadcast
|
|
|
|
local ok, err = udp:sendto(packet, bcast_ip, port)
|
|
udp:close()
|
|
return ok ~= nil, err
|
|
end
|
|
|
|
return network
|
|
|