From 1c40b7a0861247d4ba37313e1d6cfeda4ff7cb60 Mon Sep 17 00:00:00 2001 From: Federico Ceratto Date: Tue, 19 Feb 2019 22:55:35 +0000 Subject: [PATCH] Handle IPv6 in bindAddr #7633 Add test --- lib/pure/net.nim | 25 ++++++++++++------------- tests/stdlib/tnetbind.nim | 17 +++++++++++++++++ 2 files changed, 29 insertions(+), 13 deletions(-) create mode 100644 tests/stdlib/tnetbind.nim diff --git a/lib/pure/net.nim b/lib/pure/net.nim index 43284f8724f49..f468e1c5d37fa 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -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}) {. diff --git a/tests/stdlib/tnetbind.nim b/tests/stdlib/tnetbind.nim new file mode 100644 index 0000000000000..149f2ba2c9f27 --- /dev/null +++ b/tests/stdlib/tnetbind.nim @@ -0,0 +1,17 @@ +discard """ +""" + +import net + +## Test for net.bindAddr + +proc test() = + newSocket(AF_INET, SOCK_DGRAM, IPPROTO_IP).bindAddr(Port(1900), "0.0.0.0") + + newSocket(AF_INET, SOCK_DGRAM, IPPROTO_IP).bindAddr(Port(1901)) + + newSocket(AF_INET6, SOCK_DGRAM, IPPROTO_IP).bindAddr(Port(1902), "::") + + newSocket(AF_INET6, SOCK_DGRAM, IPPROTO_IP).bindAddr(Port(1903)) + +test()