how to differentiate tcp/udp when programming sockets

The general syntax for creating a socket is:

socket(socket_family, socket_type, protocol=0)

We can use either AF_INET (for IPv4) or AF_INET6 (IPv6) as the first argument i.,e for socket_family.

The socket_type is the argument that determines whether the socket to be created is TCP or UDP. For TCP sockets it will be SOCK_STREAM and for UDP it will be SOCK_DGRAM (DGRAM - datagram). Finally, we can leave out the protocol argument which sets it to the default value of 0.

For TCP sockets you should have used bind(), listen() and accept() methods for server sockets and connect() or connect_ex() for client sockets. Whereas for UDP sockets you won't need listen(), accept() and connect() methods (as TCP sockets are connection-oriented sockets while UDP sockets are connection less sockets).

There are specific methods available for UDP to send and receive packets recvfrom() and sendto() respectively while recv() and send() are for TCP. Refer to this documentation for socket for more information on respective methods for TCP and UDP. Also, Core Python Applications Programming by Wesley Chun is a better book for some pretty basics on socket programming.


The second argument determines the socket type; socket.SOCK_DGRAM is UDP, socket.SOCK_STREAM is a TCP socket. This all provided you are using a AF_INET or AF_INET6 socket family.

Before you continue, perhaps you wanted to go and read the Python socket programming HOWTO, as well as other socket programming tutorials. The difference between UDP and TCP sockets is rather big, but the differences translate across programming languages.

Some information on sockets on the Python Wiki:

  • UDP Communication
  • TCP Communication