diff --git a/chronos/transports/datagram.nim b/chronos/transports/datagram.nim index 93500f3..373fcd1 100644 --- a/chronos/transports/datagram.nim +++ b/chronos/transports/datagram.nim @@ -65,6 +65,28 @@ type const DgramTransportTrackerName = "datagram.transport" +proc remoteAddress*(transp: DatagramTransport): TransportAddress = + ## Returns ``transp`` remote socket address. + if transp.remote.family == AddressFamily.None: + var saddr: Sockaddr_storage + var slen = SockLen(sizeof(saddr)) + if getpeername(SocketHandle(transp.fd), cast[ptr SockAddr](addr saddr), + addr slen) != 0: + raiseTransportOsError(osLastError()) + fromSAddr(addr saddr, slen, transp.remote) + result = transp.remote + +proc localAddress*(transp: DatagramTransport): TransportAddress = + ## Returns ``transp`` local socket address. + if transp.local.family == AddressFamily.None: + var saddr: Sockaddr_storage + var slen = SockLen(sizeof(saddr)) + if getsockname(SocketHandle(transp.fd), cast[ptr SockAddr](addr saddr), + addr slen) != 0: + raiseTransportOsError(osLastError()) + fromSAddr(addr saddr, slen, transp.local) + result = transp.local + template setReadError(t, e: untyped) = (t).state.incl(ReadError) (t).error = getTransportOsError(e) @@ -318,13 +340,13 @@ when defined(windows): var saddr: Sockaddr_storage var slen: SockLen toSAddr(local, saddr, slen) + if bindAddr(SocketHandle(localSock), cast[ptr SockAddr](addr saddr), slen) != 0: let err = osLastError() if sock == asyncInvalidSocket: closeSocket(localSock) raiseTransportOsError(err) - result.local = local else: var saddr: Sockaddr_storage var slen: SockLen diff --git a/tests/testdatagram.nim b/tests/testdatagram.nim index 58e739b..01ca7b2 100644 --- a/tests/testdatagram.nim +++ b/tests/testdatagram.nim @@ -434,18 +434,19 @@ suite "Datagram Transport test suite": result += counters[i] proc testConnReset(): Future[bool] {.async.} = - var ta = initTAddress("127.0.0.1:65000") + var ta = initTAddress("127.0.0.1:0") var counter = 0 proc clientMark(transp: DatagramTransport, raddr: TransportAddress): Future[void] {.async.} = counter = 1 transp.close() var dgram1 = newDatagramTransport(client1, local = ta) + var localta = dgram1.localAddress() dgram1.close() await dgram1.join() var dgram2 = newDatagramTransport(clientMark) var data = "MESSAGE" - asyncCheck dgram2.sendTo(ta, data) + asyncCheck dgram2.sendTo(localta, data) await sleepAsync(2000.milliseconds) result = (counter == 0) dgram2.close()