简体   繁体   中英

How to receive UDP packets from a specific remote client per UdpClient? (.Net 4.6)

I'm trying to figure out how a server will distinguish between multiple clients that connect to it via TCP listener, and begin sending UDP messages to a UdpClient.

The TcpListner makes it easy for TCP, because a TcpClient is returned that I can attach to a specific client instance on the server. But how will I handle the UdpClient now since UDP is a connectionless protocol? I am also curious how the TcpClient knows which machine to send data back to in the first place, especially if its sitting behind a router.

I can't trust something like a unique id in udp packet headers, because those can always be forged or stolen.

From the documentation for UdpClient.Receive Method (IPEndPoint):

remoteEP
Type: System.Net.IPEndPoint
An IPEndPoint that represents the remote host from which the data was sent.

In other words, just use the IPEndPoint value that the Receive() method passes back to you. This will be a unique IP address and port for each client, which you can use as a key to match the datagram with your client state.

I am also curious how the TcpClient knows which machine to send data back to in the first place, especially if its sitting behind a router

A connected socket maintains information about the remote endpoint. If the client is behind a NAT router, the remote endpoint IP address and port are of the router, and the router has a table that maps externally-visible addresses and ports to the clients which sit behind that router. See Network Address Translation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM