+

Datagram in Python

Let`s learn how to send some data to the local network and receive the same data as the recipient on the same machine to demonstrate the use of a datagram.

To find out the IP configuration of your computer, use this command on the terminal:

 ipconfig 

Code # 1: For the end of the sender.

# socket module import

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))

Exit:

 message: Geeksforgeeks 

Explanation :

  • Please enter your IPv4 address instead of UDP_IP and remember that port number 8080 — this is the port number of your localhost, so you need to specify it.
  • socket.socket () uses your system`s IPv4 address, and SOCK_DGRAM — this is the type of protocol we use for communication.
  • Use the sock object to call the sendto () function, then pass the tuple argument containing the IP address and port number.

Step # 2: at the receiver end.

# import socket module

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 :

# buffer size 1024 bytes

  data, addr = sock.recvfrom ( 1024

print ( "Received message:" , data)

Exit :

 Received Message: b`Geeksforgeeks` 

Explanation:

  • We need to specify the localhost IP in UDP_IP and use the socket.socket () function, as described above.
  • bind the parameter to a socket object so that whatever is received with that port address we intercept at that end. In a loop, define the buffer size as 1024. Since the message is small, the buffer size is sufficient.
Get Solution for free from DataCamp guru