Datagram is a type of wireless communication between two endpoints and it requires the ip address and port number to establish connection. Datagram uses UDP(User Datagram Protocol), it converts user data into small packets or chunks of data so that it can be sent over a network in a continuous manner. In UDP type of connection data packets have no records at the sender’s end, it just sends by the user then it’s upon receiver that it wants to accept data packets or not. UDP type of connection we use in video conferencing or in video calls.
Let’s learn how to send some data on localhost network and receive the same data as a receiver on the same machine to demonstrate the use of datagram.
To know the IP configurations of your computer, use this command on terminal:
ipconfig
Code #1: For sender’s end.
import socket
UDP_IP = "localhost"
UDP_PORT = 8080
MESSAGE = "GeeksforGeeks"
print ( "message:" , MESSAGE)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.sendto(bytes(MESSAGE, "utf-8" ), (UDP_IP, UDP_PORT))
|
Output:
message: Geeksforgeeks
Explanation:
- Specify your IPv4 address in the place of UDP_IP and remember port number 8080 is your localhost port number so you need to specify the same.
socket.socket()
uses AF_INET in order to use the IPv4 address of your system and SOCK_DGRAM is a type of protocol that we are using for communication.
- Use sock object to call function
sendto()
, then pass argument of tuple containing IP address and port number.
Step #2: At the receiver’s end.
import socket
UDP_IP = "localhost"
UDP_PORT = 8080
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((UDP_IP, UDP_PORT))
while True :
data, addr = sock.recvfrom( 1024 )
print ( "Received message:" , data)
|
Output:
Received Message: b'Geeksforgeeks'
Explanation:
- We need to specify the localhost IPaddress in
UDP_IP
and use the socket.socket() function same as above.
- bind the parameter to the socket object so that anything receive at these port address will we catch at this end. In the loop, define the buffer size as 1024, As message is not big, it is sufficient buffer size.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!