Skip to content

Instantly share code, notes, and snippets.

@Michal-Szczepaniak
Created October 20, 2021 17:20
Show Gist options
  • Save Michal-Szczepaniak/6f7319c686aaaab1a6a0d273153e7936 to your computer and use it in GitHub Desktop.
Save Michal-Szczepaniak/6f7319c686aaaab1a6a0d273153e7936 to your computer and use it in GitHub Desktop.
Nim UDP server discovery
import net
let socket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
socket.setSockOpt(OptReuseAddr, true)
socket.setSockOpt(OptReusePort, true)
socket.setSockOpt(OptBroadcast, true)
socket.sendTo("255.255.255.255", Port(12346), $0b10)
var
receivedFrom = ""
receivedPort = Port(0)
line = ""
len = socket.recvFrom(line, 16, receivedFrom, receivedPort)
echo "Discovered server at: " & receivedFrom
import net
var discoverServer = newSocket(protocol = IPPROTO_UDP, sockType = SOCK_DGRAM)
discoverServer.setSockOpt(OptReuseAddr, true)
discoverServer.setSockOpt(OptReusePort, true)
discoverServer.setSockOpt(OptBroadcast, true)
discoverServer.bindAddr(Port(12346))
while true:
var
receivedFrom = ""
receivedPort = Port(0)
line = ""
len = discoverServer.recvFrom(line, 1, receivedFrom, receivedPort)
if line == $0b10:
discoverServer.sendTo(receivedFrom, receivedPort, $getPrimaryIPAddr(parseIpAddress(receivedFrom)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment