简体   繁体   中英

how to differentiate tcp/udp when programming sockets

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.

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.

The main difference is that TCP sockets are connection-based. You can't send or receive anything until you are connected to another TCP socket on the remote machine. Once connected, a TCP socket can only send and receive to/from the remote machine. This means that you'll need one TCP socket for each client in your application. UDP is not connection-based, you can send and receive to/from anyone at any time with the same socket.

~ Muralidhar gundala

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM