pythonqtudppyqt

how could a server send data to a client behind nat by udp in qt?


The server has a public IP, the client is behind a nat.

How could the client communicate with server by udp in qt?

The client will send some data to server first, then how could server reply to client?

The current code is this:

server:

self.udpSocketGet = QtNetwork.QUdpSocket()
self.udpSocketGet.bind(QtNetwork.QHostAddress.LocalHost, serverPort)
self.udpSocketGet.readyRead.connect(self.receive)

def receive(self):
    while self.udpSocketGet.hasPendingDatagrams():
        size = self.udpSocketGet.pendingDatagramSize()
        if size > 0:
            data, senderAddr, senderPort = self.udpSocketGet.readDatagram(size)

client:

def sentToServer(self,data):
    udpSocketSend = QtNetwork.QUdpSocket()
    udpSocketSend.writeDatagram(data.encode('utf-8'), serverAddress, serverPort)

Solution

  • The answer to your question goes beyond qt. Check out http://en.m.wikipedia.org/wiki/UDP_hole_punching and http://en.m.wikipedia.org/wiki/NAT_traversal

    I am editing this answer after I looked back and found out that the server has a public IP address. In that case, the server will just have to respond to whatever IP address the request comes from. In case the client is communicating via NAT, the server will see the public address of the router and will be totally unaware that the actual client is behind that router.

    Read Receiving a response through UDP The bottom line is that you either have to use port mapping or UPNP.

    See also https://superuser.com/questions/456812/nat-and-udp-replies Again, the server code should not be concerned with NAT traversal. Either the client uses UPNP and the router has UPNP enabled. Or the router is configured to port forward or remember the source and destination IP addresses and ports of the packet originating from the client and properly farwards back the packets sent by the server.