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.
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)
No, you can't have a TCP server communicating with UDP clients.
A UDP server is always listening. A UDP client is only listening after sending a message, for a response.
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.
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.
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.
just let the TCP socket listen on port X, and do the UDP connections through port Y
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With