Following is a python socket snippet:
import socket
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
My question is: does the line state whethet socket connection will be transported via TCP/IP? So far I was programming TCP connections only, using above line, but probably I was unaware of the fact. Am I able to program UDP connections using python sockets? How can I differentiate the transport layer?
The question isn't strictly connected to python, explanations are welcome as well in c++ or anything else.
Use the lsof command, a variant of the netstat -af command to identify TCP sockets that are in the LISTEN state and idle UDP sockets that are waiting for data to arrive.
There are some fundamental differences between TCP and UDP sockets. UDP is a connection-less, unreliable, datagram protocol (TCP is instead connection-oriented, reliable and stream based). There are some instances when it makes to use UDP instead of TCP.
Yes, you can use the same port number for both TCP and UDP. Many protocols already do this, for example DNS works on udp/53 and tcp/53.
In the TCP protocol, the socket is uniquely identified by the source IP, source port, destination IP, and destination port.
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:
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.
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