Skip to content

Instantly share code, notes, and snippets.

@masakk1
Created February 25, 2025 22:53
Show Gist options
  • Save masakk1/cdee28f95f5e51fccd6a871512a19717 to your computer and use it in GitHub Desktop.
Save masakk1/cdee28f95f5e51fccd6a871512a19717 to your computer and use it in GitHub Desktop.
`:setpeername()` doesn't care whether its connected or not. Contrary to `luasocket`'s documenation.
local socket = require("socket")
-- Proof that `:setpeername()` doesn't care whether it's connected or not
-- On the other hand, `:getpeername()` errors if the UDP object isn't connected
local udp, err = socket.udp()
assert(udp, err)
local function print_peer(message)
print(message)
local success, result = pcall(udp.getpeername, udp)
print("-> Result: ", success and result or "Can't get peer")
end
print_peer("unconnected clean")
print(udp:setpeername("127.0.0.1", 12345)) --1
print_peer("unconnected setting peer")
-- we can set a peer even when already connected
print(udp:setpeername("127.0.0.2", 12345)) --1
print_peer("connected setting another peer again")
print(udp:setpeername("*")) --1
print_peer("connected removing peer")
-- we can remove the specified peer even when already unconnected
print(udp:setpeername("*")) --1
print_peer("unconnected removing peer again")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment