Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to differentiate if client is using TCP or UDP from server side

I am writing simple client-server program.

Client send some messages to server using UDP or TCP. Server must be able to support both UDP and TCP.

If client, sends message using UDP, sequence of method calls in client is socket(),bind(),sendto(),recvfrom(),close() and that in server is socket(),bind(),sendto(),recvfrom(),close().

If it uses TCP, sequence of call in server is socket(),bind(),listen(),accept(),send(),recv(),close(). and that in client is socket(),bind(),connect(),send(),recv(),close()

In my program, user/client is given choice in the start to select what he want to use UDP or TCP. So, my main problem is how can I know or differentiate in the server side, if the client is sending message using TCP or UDP. If it uses TCP, I must call listen(),accept(),send(),recv() and if it uses UDP, I don't call listen(),accept() but call sendto() and recvfrom().

So, how can I differentiate/know this in the beginning so that I can make appropriate function calls.

Thanks.

like image 551
seg.server.fault Avatar asked Sep 18 '09 14:09

seg.server.fault


People also ask

How do you identify whether an application uses TCP or UDP?

Run netstat -an from a Windows command prompt. Download and run TCPView (which also lists UDP) for a GUI view. Run Wireshark. Run nmap against the server with port in question (by default only scans TCP ports)

Can UDP client communicate with TCP server?

No, you can't have a TCP server communicating with UDP clients.

What is the difference between UDP client and server?

A UDP server is always listening. A UDP client is only listening after sending a message, for a response.


4 Answers

Before the packet reaches you, you don't know whether it's UDP or TCP.

So you want to bind to both UDP and TCP sockets if you expect requests both ways.

Once you did, you just know which way it came by the socket you received the packet through.

like image 188
Michael Krelin - hacker Avatar answered Oct 06 '22 02:10

Michael Krelin - hacker


When you create the socket, you pass a type - SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)

So the two kinds of traffic will be on two different sockets.

like image 23
Henry Troup Avatar answered Oct 06 '22 03:10

Henry Troup


Just as Henry Troup pointed out, an IP socket is defined as

(transport, interface, port).

(UDP, 127.0.0.1, 80) is not the same IP socket as (TCP, 127.0.0.1, 80) , thus you can safely bind to both of them and listen for incoming traffic.

like image 31
Michael Beer Avatar answered Oct 06 '22 01:10

Michael Beer


just let the TCP socket listen on port X, and do the UDP connections through port Y

like image 27
Toad Avatar answered Oct 06 '22 01:10

Toad