Skip to content

Commit

Permalink
Handle IPv6 in bindAddr nim-lang#7633
Browse files Browse the repository at this point in the history
Add test
  • Loading branch information
Federico Ceratto authored and dom96 committed Feb 23, 2019
1 parent f39aa1b commit 28a83a8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 13 deletions.
25 changes: 12 additions & 13 deletions lib/pure/net.nim
Original file line number Diff line number Diff line change
Expand Up @@ -755,21 +755,20 @@ proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
## Binds ``address``:``port`` to the socket.
##
## If ``address`` is "" then ADDR_ANY will be bound.
var realaddr = address
if realaddr == "":
case socket.domain
of AF_INET6: realaddr = "::"
of AF_INET: realaddr = "0.0.0.0"
else:
raise newException(ValueError,
"Unknown socket address family and no address specified to bindAddr")

if address == "":
var name: Sockaddr_in
name.sin_family = toInt(AF_INET).uint16
name.sin_port = htons(port.uint16)
name.sin_addr.s_addr = htonl(INADDR_ANY)
if bindAddr(socket.fd, cast[ptr SockAddr](addr(name)),
sizeof(name).SockLen) < 0'i32:
raiseOSError(osLastError())
else:
var aiList = getAddrInfo(address, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
raiseOSError(osLastError())
var aiList = getAddrInfo(realaddr, port, socket.domain)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
freeAddrInfo(aiList)
raiseOSError(osLastError())
freeAddrInfo(aiList)

proc acceptAddr*(server: Socket, client: var Socket, address: var string,
flags = {SocketFlag.SafeDisconn}) {.
Expand Down
14 changes: 14 additions & 0 deletions tests/stdlib/tnetbind.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import net

## Test for net.bindAddr

proc test() =
# IPv4 TCP
newSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP).bindAddr(Port(1900), "0.0.0.0")
newSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP).bindAddr(Port(1901))

# IPv6 TCP
newSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP).bindAddr(Port(1902), "::")
newSocket(AF_INET6, SOCK_STREAM, IPPROTO_TCP).bindAddr(Port(1903))

test()

0 comments on commit 28a83a8

Please sign in to comment.