8
votes

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.

4
So, should I create two sockets in the server side, one for UDP and another for TCP ?seg.server.fault
@seg.server.fault: I would recommend not calling bind() in your client code. While it's technically possible (and required in very specific situations), the default behavior without a client-side bind() is usually what you want at the application layer. Also, keep in mind that you can call connect() on a UDP socket. It doesn't do any handshaking, but it does mean you can use send/recv instead of sendto/recvfrom, which may end up making the client logic simpler.Tom

4 Answers

17
votes

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.

6
votes

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.

2
votes

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.

1
votes

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