Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to distinguish between two different UDP clients on the same IP address?

Tags:

java

udp

I'm writing a UDP server, which is a first for me; I've only done a bit of TCP communications. And I'm having trouble figuring out exactly how to distinguish which user is which, since UDP deals only with packets rather than connections and I therefore cannot tell exactly who I'm communicating with.

Here is pseudocode of my current server loop:

DatagramPacket p;
socket.receive(p); // now p contains the user's IP and port, and the data
int key = getKey(p);
if(key == 0) { // connection request
    key = makeKey(p);
    clients.add(key, p.ip);
    send(p.ip, p.port, key); // give the user his key
} else { // user has a key
    // verify key belongs to that IP address
    // lookup the user's session data based on the key
    // react to the packet in the context of the session
}

When designing this, I kept in mind these points:

  • Multiple users may exist on the same IP address, due to the presence of routers, therefore users must have a separate identification key.
  • Packets can be spoofed, so the key should be checked against its original IP address and ignored if a different IP tries to use the key.
  • The outbound port on the client side might change among packets.

Is that third assumption correct, or can I simply assume that one user = one IP+port combination? Is this commonly done, or should I continue to create a special key like I am currently doing?

I'm not completely clear on how TCP negotiates a connection so if you think I should model it off of TCP then please link me to a good tutorial or something on TCP's SYN/SYNACK/ACK mess.

Also note, I do have a provision to resend a key, if an IP sends a 0 and that IP already has a pending key; I omitted it to keep the snippet simple. I understand that UDP is not guaranteed to arrive, and I plan to add reliability to the main packet handling code later as well.

like image 831
Ricket Avatar asked Apr 11 '10 04:04

Ricket


2 Answers

UDP packet headers have a source port, which is generally used as the reply port. If not used, it should be zero, and then it is up to the higher level protocol to figure out how to coordinate request-response activity with multiple clients.

like image 119
Marcelo Cantos Avatar answered Nov 02 '22 08:11

Marcelo Cantos


* The outbound port on the client side might change among packets.

Is that third assumption correct

Not if the client keeps using the same outbound socket. Sending the first datagram will cause a local bind, so the socket will be on a fixed local port from then on.

like image 27
user207421 Avatar answered Nov 02 '22 10:11

user207421