Created
October 20, 2021 17:20
-
-
Save Michal-Szczepaniak/6f7319c686aaaab1a6a0d273153e7936 to your computer and use it in GitHub Desktop.
Nim UDP server discovery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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