Search code examples
ctcpudpipport

receiving udp packets from a specific client


I am trying to implement UDP Server with "accept" function like the one in TCP. That because I need to keep one channel for each client. My question is how to let the UDP socket receiving Daata from a specific client (specific client's ip and port)?

TCP uses a main Socket (within a thread) that receives the request from a client. Once a request from a client commes, the main socket opens another socket for communicating with that client (within another thread). To implement this Mechanisem, the ability to bind socket to receive packets from a specific client must be available. This ability what I am asking for. How can i reimplement the "Accept" function for UDP Sockets ? where (as I know) it is not possible to bind Socket for receiving from a specific client. My Question is how to make it possible ?


Solution

  • To implement this mechanism, the ability to bind socket to receive packets from a specific client must be available.

    bind does not specify a remote client which can connect, but specifies the local address where data should be sent to. This is in UDP the same as in TCP. It is not possible in TCP to accept only a specific client, but one can accept a connection and then simply close it if it is the wrong client.

    With UDP one can bind a socket to receive data on a local IP and port. One can additionally connect the UDP socket to get only data from a specific client IP and port. Note that this is different from connect in TCP: in TCP it actively establishes a connection (i.e. packets get exchanged during TCP handshake) whereas in UDP it only sets the peers address on the socket.

    It is not possible though to connect to a specific client IP only. connect needs both IP and port. If the client source port is not known upfront, one can create an unconnected but bound UDP socket, call recvfrom on it and then connect the socket to the clients IP,port as returned by recvfrom (or create a new bound and connected socket) if it is the expected client.