You are on page 1of 11

Lecture 10: UDP protocol

What is an RFC
RFC stands for "Request for Comments," and it is a series of documents and memoranda encompassing new research, innovations, and
methodologies applicable to the functioning of the Internet and Internet-connected systems. The RFC system is a fundamental part of the
Internet's standardization process.

Here's a breakdown of key aspects of RFC:


1. Historical Context: The RFC series originated with the ARPANET (Advanced Research Projects Agency Network), the precursor to the
modern Internet. In the early days, researchers and engineers documented protocols and procedures through a system of notes called
"Requests for Comments."
2. Documenting Protocols and Standards: RFCs document various aspects of computer networking, including protocols, procedures,
programs, and concepts, as well as meeting notes, opinions, and sometimes humor. The documents cover a wide range of topics related
to the Internet and its technologies.

3. Open Process: The term "Request for Comments" doesn't imply a request for approval. Instead, it reflects the open and collaborative
nature of the process. Individuals or groups can submit a document to the RFC Editor for publication in the RFC series. The documents
are reviewed by the Internet Engineering Task Force (IETF) or the Internet Society, and they may evolve through discussions and
revisions.
4. Standardization and Evolution: Many RFCs describe standards for protocols and procedures that are widely used on the Internet,
such as the Hypertext Transfer Protocol (HTTP), Simple Mail Transfer Protocol (SMTP), and Internet Protocol (IP). As technologies
evolve, new RFCs may be issued to update or replace older ones.
5. RFC Editor: The RFC Editor is responsible for publishing the documents in the RFC series. The RFC Editor is supported by the Internet
Society (ISOC) and works closely with the IETF. The RFC Editor ensures that the documents follow the proper format and style
guidelines.
6. Numeric Designation: Each RFC is assigned a unique number for identification. The format is "RFC" followed by a number (e.g., RFC
768). The numbers are assigned sequentially.

RFCs play a crucial role in the development and maintenance of Internet standards. They provide a stable reference point for the
implementation and understanding of various Internet protocols and technologies.

UDP Definition
RFC 768 specifically refers to the User Datagram Protocol (UDP).

The User Datagram Protocol (UDP) is a connectionless transport protocol that operates on top of the Internet Protocol (IP). RFC 768,
published in August 1980, defines UDP and provides details about its header format, operation, and use. UDP is a simple, minimalistic
protocol that does not guarantee reliable, ordered delivery of data. It is often used in scenarios where low overhead and reduced latency are
more important than guaranteed data delivery, such as in real-time applications like streaming media, online gaming, and DNS (Domain
Name System). It is one of the core protocols of the Internet Protocol (IP) suite. It operates at the transport layer and provides a simple,
connectionless, and low-overhead method of exchanging data between devices on a network. Here are some key characteristics of the
UDP protocol:

1. Connectionless:
UDP is a connectionless protocol, meaning it does not establish a connection before sending data. Each UDP packet, also known as
a datagram, is independent and may take a different route to reach its destination.

2. Unreliable:
UDP does not guarantee the reliable delivery of data. There is no mechanism for acknowledging the receipt of packets or
retransmitting lost packets. If a packet is lost during transmission, it is not retransmitted.
3. Low Overhead:
UDP has a smaller header size compared to TCP (Transmission Control Protocol), resulting in lower overhead. This makes UDP
more efficient for certain real-time and low-latency applications.
4. No Flow Control:
UDP does not implement flow control mechanisms to manage the rate of data transmission between sender and receiver. This lack of
flow control allows UDP to send data at the maximum rate without waiting for acknowledgments.

5. No Ordered Delivery:
UDP does not ensure the ordered delivery of packets. Packets may arrive at the destination out of order, and it is up to the application
layer to manage the sequencing if required.
6. Header Format:
The UDP header includes source and destination port numbers, length information, and a checksum for error detection.
7. Stateless:
UDP is a stateless protocol. It does not maintain any connection state between sender and receiver after the transmission of a packet.
Each packet is processed independently.
8. Broadcast and Multicast Support:
UDP supports both broadcast and multicast communication. This makes it suitable for scenarios where a single message needs to be
delivered to multiple recipients simultaneously.

While UDP lacks some of the reliability features provided by TCP, its simplicity and low overhead make it well-suited for specific applications
where timely delivery and reduced latency are critical. However, the choice between UDP and TCP depends on the specific requirements of
the application.

User Datagram Protocol Wikipedia provides us with an awesome description of what AN UDP protocol is, and how it works.

RFC 768 for UDP: RFC 768: User Datagram Protocol

TCP header
The TCP (Transmission Control Protocol) header is a fundamental part of a TCP packet and contains information necessary for the reliable
and ordered delivery of data between devices. A standard TCP header is 20 bytes in size. The TCP header includes various fields, each
serving a specific purpose in the communication process.

Here is a breakdown of the common fields in a TCP header and their respective sizes:

1. Source Port (16 bits): Identifies the sender's port number.


2. Destination Port (16 bits): Identifies the recipient's port number.

3. Sequence Number (32 bits): Indicates the sequence number of the first data byte in the TCP segment.
4. Acknowledgment Number (32 bits): If the ACK flag is set, this field contains the value of the next sequence number that the sender of
the segment is expecting to receive.
5. Data Offset (4 bits): Specifies the length of the TCP header in 32-bit words. This field is used to locate the beginning of the data.
6. Reserved (6 bits): Reserved for future use. Must be set to zero.

7. Flags (6 bits): Control flags such as URG, ACK, PSH, RST, SYN, and FIN.
8. Window Size (16 bits): Specifies the size of the sender's receive window, used for flow control.

9. Checksum (16 bits): Used for error-checking the header and data.
10. Urgent Pointer (16 bits): If the URG flag is set, this field points to the sequence number of the last urgent data byte.

11. Options (Variable): This field is optional and can include various TCP options, such as Maximum Segment Size (MSS), Timestamps,
and Window Scale.

Keep in mind that the Options field length is variable, and its size depends on the specific options being used. The 20-byte size mentioned
here is for the basic TCP header without any additional options. If options are present, the header size can be larger.

For the most up-to-date and specific information, it's advisable to refer to the latest RFC (Request for Comments) documents related to
TCP, as standards may evolve over time.
UDP Header
The User Datagram Protocol (UDP) header is 8 bytes in size. The UDP header is relatively simple compared to other transport layer
protocols like TCP, as UDP is a connectionless and lightweight protocol.

Here is a breakdown of the common fields in a UDP header and their respective sizes:

1. Source Port (16 bits): Identifies the sender's port number.


2. Destination Port (16 bits): Identifies the recipient's port number.
3. Length (16 bits): Specifies the length of the UDP header and UDP data in bytes. The minimum value is 8 (header only), and the
maximum value is 65,535.
4. Checksum (16 bits): Used for error-checking the header and data. If the checksum is not used, this field is often set to zero.

The UDP header is fixed at 8 bytes, and there are no additional options or control flags as seen in the TCP header. UDP is a connectionless
protocol, meaning it does not establish a connection before sending data and does not provide features like reliability and flow control. As a
result, the UDP header is lightweight compared to the TCP header.

It's important to note that standards and specifications can change, so for the most up-to-date and specific information, you may want to
refer to the latest RFC (Request for Comments) documents related to UDP.

Comparison TCP vs UDP protocol


UDP (User Datagram Protocol) and TCP (Transmission Control Protocol) are both transport layer protocols in the Internet Protocol (IP)
suite, but they differ in their features and use cases. Here's a comparison between UDP and TCP:

1. Connection-Oriented vs. Connectionless:


TCP: Connection-oriented. Establishes a reliable, full-duplex connection before data exchange. Provides error checking and ensures
the ordered delivery of data.

UDP: Connectionless. Does not establish a connection before sending data. No guarantee of reliability, ordering, or error checking.
2. Reliability:
TCP: Reliable. Guarantees delivery of data. If data is lost or corrupted during transmission, TCP will retransmit it.

UDP: Unreliable. Does not guarantee delivery. No retransmission of lost or corrupted packets.
3. Ordering of Data:
TCP: Ensures ordered delivery. If packets are sent out of order, TCP reorders them before delivering them to the application.
UDP: Does not ensure ordered delivery. Packets may arrive out of order, and the application must handle sequencing if required.

4. Flow Control:
TCP: Implements flow control mechanisms to prevent overwhelming the receiver with too much data. Uses a sliding window
mechanism.

UDP: No inherent flow control. The sender can transmit data at its own rate without considering the receiver's ability to handle it.
5. Connection Setup and Termination:
TCP: Three-way handshake for connection setup and a four-way handshake for connection termination.
UDP: No connection setup or termination process. Communication is stateless.

6. Header Size:
TCP: Larger header size due to additional control information for connection management, flow control, and error recovery.
UDP: Smaller header size, resulting in less overhead.

7. Use Cases:
TCP: Suitable for applications where reliability and data integrity are crucial, such as file transfer, email, web browsing, and most
application-level protocols.
UDP: Suitable for real-time applications where low latency is more important than guaranteed delivery, such as streaming media,
online gaming, DNS, and VoIP.
8. Overhead:
TCP: Higher overhead due to additional control information and the need for acknowledgment messages.
UDP: Lower overhead, making it more efficient for certain types of communication.
9. Examples:
TCP: HTTP, HTTPS, FTP, SMTP, Telnet.
UDP: DNS, DHCP, SNMP, VoIP, online gaming, streaming media.
10. Error Handling:
TCP: Provides extensive error handling and correction mechanisms. Detects and retransmits lost or corrupted packets.

UDP: Limited error checking. Applications must handle errors if needed.

In summary, TCP provides a reliable, connection-oriented communication with features like flow control and error recovery, making it
suitable for applications where data integrity is crucial. UDP, on the other hand, is connectionless and lightweight, suitable for scenarios
where low latency is more important than guaranteed delivery. The choice between UDP and TCP depends on the specific requirements of
the application.

Examples of UDP usage


1. DNS (Domain Name System):
DNS uses UDP for its query/response mechanism. When a device needs to resolve a domain name to an IP address, it sends a DNS
query using UDP. The DNS server responds with the corresponding IP address.

2. Streaming Media:
UDP is commonly used for real-time applications such as live streaming, video conferencing, and online gaming. The low latency and
reduced overhead make it suitable for these applications where a small amount of lost data is acceptable, and timely delivery is
crucial.
3. VoIP (Voice over IP):
VoIP applications, like Skype or Zoom, often use UDP for the transmission of voice data. The real-time nature of voice communication
benefits from the lower latency provided by UDP.
4. Trivial File Transfer Protocol (TFTP):
TFTP, a simple file transfer protocol, uses UDP for its data transfer. While less reliable than TCP, TFTP is lightweight and suitable for
scenarios where speed is more critical than guaranteed delivery.

5. DHCP (Dynamic Host Configuration Protocol):


DHCP uses UDP for lease negotiation and configuration of network parameters, such as IP addresses, subnet masks, and gateways.
DHCP allows hosts to obtain necessary network configuration information dynamically.
6. NTP (Network Time Protocol):
NTP, used for synchronizing the clocks of computers on a network, often relies on UDP for time synchronization. NTP is designed to
provide accurate time information, and the simplicity of UDP is appropriate for this purpose.
7. SNMP (Simple Network Management Protocol):
SNMP uses UDP for communication between network devices and management systems. SNMP allows administrators to monitor
and manage network devices, and the connectionless nature of UDP suits the requirements of SNMP.
8. RIP (Routing Information Protocol):
RIP, a routing protocol, uses UDP to exchange routing information between routers. While more modern routing protocols like OSPF
use TCP, RIP's simplicity makes UDP a suitable choice for its operation.

9. Online Multiplayer Games:


Many online multiplayer games use UDP for in-game communication. UDP's low latency and reduced overhead are beneficial in fast-
paced gaming environments where real-time interaction is crucial.
10. IoT (Internet of Things) Applications:
UDP is used in certain IoT applications where lightweight communication is essential, and the overhead of TCP may be too much. For
example, sensor networks and small embedded devices may leverage UDP for data transmission.

These examples showcase the versatility of UDP in various applications where low latency and simplicity are prioritized over reliable,
ordered delivery. It's important to note that while UDP is suitable for certain scenarios, it lacks the reliability features provided by TCP.
Therefore, its usage should be carefully considered based on the specific requirements of the application.
Broadcast vs multicast
Broadcast:

Definition: Broadcast is a network communication method where data is sent from one sender to all possible recipients within a network
or a specific subnet. In a broadcast, a single sender addresses the data to all devices on the network, and all devices on that network
receive and process the broadcasted message.
Scope: Broadcast messages are typically limited to a specific local network or subnet. Routers, which typically separate different
subnets, may not forward broadcast messages by default.
Efficiency: While broadcast is straightforward and easy to implement, it can lead to network congestion, especially in larger networks,
as every device on the network processes the broadcasted message.
Example: In IPv4 networks, the broadcast address is often the highest address in a subnet (e.g., 192.168.1.255 in a network with the
range 192.168.1.0/24).

Multicast:

Definition: Multicast is a network communication method where data is sent from one sender to a specific group of recipients. Devices
that are interested in receiving the multicast data join a multicast group, and the sender sends the data only to that group. This allows for
more efficient use of network resources compared to broadcast.
Scope: Multicast can operate within a local network or extend across multiple networks. Routers can be configured to forward multicast
traffic between different subnets, making it scalable for larger networks.
Efficiency: Multicast is more bandwidth-efficient than broadcast because data is sent only to devices that have explicitly expressed
interest in the multicast group. This selective delivery reduces unnecessary network traffic.
Example: Multicast is commonly used in streaming applications, online gaming, and routing protocols. In IPv4, multicast addresses are
within the range 224.0.0.0 to 239.255.255.255.

In summary, broadcast sends data to all devices on a network, while multicast sends data to a specific group of devices that have
expressed interest in receiving that data. Multicast is often more efficient, scalable, and suitable for scenarios where selective delivery is
desired, as opposed to the broad delivery characteristic of broadcast.

Example of broadcast via UDP


Here's a simple Python example using the socket module to broadcast a message using UDP. This example assumes that you have two
scripts, one for sending the broadcast ( sender.py ) and one for receiving the broadcast ( receiver.py ).

Sender ( sender.py ):

1 import socket
2 import time
3
4 # Create a UDP socket
5 sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
6 sender_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
7
8 # Broadcast address and port
9 broadcast_address = ('<broadcast>', 12345)
10
11 # Message to be broadcasted
12 message = "Hello, broadcast world!"
13
14 try:
15 while True:
16 # Send the message
17 sender_socket.sendto(message.encode('utf-8'), broadcast_address)
18 print(f"Sent: '{message}' to {broadcast_address}")
19 time.sleep(2) # Broadcast every 2 seconds
20
21 except KeyboardInterrupt:
22 print("Broadcast stopped.")
23 sender_socket.close()

Let's go through the script line by line

1 # Import necessary modules


2 import socket
3 import time
4
5 # Create a UDP socket
6 sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

1. Import the socket and time modules.

2. Create a UDP socket using socket.socket() . AF_INET specifies the address family (IPv4), and SOCK_DGRAM specifies the socket
type (UDP).

1 sender_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

3. Set a socket option using setsockopt to enable broadcasting. socket.SO_BROADCAST is the option for enabling broadcast, and 1
is set as the value.

1 # Broadcast address and port


2 broadcast_address = ('<broadcast>', 12345)

4. Define the broadcast address as '<broadcast>' (a placeholder that gets replaced with the broadcast address by the operating
system) and the port as 12345 .

1 # Message to be broadcasted
2 message = "Hello, broadcast world!"

5. Set the message to be broadcasted.

1 try:
2 while True:
3 # Send the message
4 sender_socket.sendto(message.encode('utf-8'), broadcast_address)
5 print(f"Sent: '{message}' to {broadcast_address}")
6 time.sleep(2) # Broadcast every 2 seconds
7
8 except KeyboardInterrupt:
9 print("Broadcast stopped.")
10 sender_socket.close()

6. Start an infinite loop using while True .


7. Inside the loop, use sendto to send the encoded message to the specified broadcast address and port.

8. Print a message indicating that the broadcasted message has been sent.
9. Introduce a 2-second delay using time.sleep(2) to broadcast the message every 2 seconds.
10. Handle a KeyboardInterrupt exception (triggered by pressing Ctrl+C) to stop the broadcast gracefully.
11. Print a message indicating that the broadcast has stopped.
12. Close the sender socket to release system resources.

Receiver ( receiver.py ):

1 import socket
2
3 # Create a UDP socket
4 receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
5
6 # Bind the socket to a specific address and port
7 receiver_socket.bind(('0.0.0.0', 12345))
8
9 print("Waiting for broadcasts...")
10
11 try:
12 while True:
13 # Receive the message
14 data, address = receiver_socket.recvfrom(1024)
15 print(f"Received message from {address}: '{data.decode('utf-8')}'")
16
17 except KeyboardInterrupt:
18 print("Receiver stopped.")
19 receiver_socket.close()

Let's break down the script line by line

1 # Import necessary modules


2 import socket

1. Import the socket module.

1 # Create a UDP socket


2 receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

2. Create a UDP socket using socket.socket() . AF_INET specifies the address family (IPv4), and SOCK_DGRAM specifies the socket
type (UDP).

1 # Bind the socket to a specific address and port


2 receiver_socket.bind(('0.0.0.0', 12345))

3. Bind the UDP socket to a specific address and port ( 12345 ). '0.0.0.0' as the address means the socket is bound to all available
network interfaces, allowing it to receive messages from any sender on the specified port.

1 print("Waiting for broadcasts...")

4. Print a message indicating that the script is waiting for broadcasts.

1 try:
2 while True:
3 # Receive the message
4 data, address = receiver_socket.recvfrom(1024)
5 print(f"Received message from {address}: '{data.decode('utf-8')}'")

5. Start an infinite loop using while True .

6. Inside the loop, use recvfrom to receive data and the sender's address. The received data is stored in data , and the sender's
address is stored in address .
7. Print a message indicating the address of the sender and the received message, decoded from bytes using UTF-8.

1 except KeyboardInterrupt:
2 print("Receiver stopped.")
3 receiver_socket.close()

8. Handle a KeyboardInterrupt exception (triggered by pressing Ctrl+C) to stop the receiver script gracefully.
9. Print a message indicating that the receiver has been stopped.
10. Close the receiver socket to release system resources.
This script creates a UDP socket, binds it to a specific address and port, and then enters a loop where it continuously listens for
incoming UDP messages. When a message is received, it prints the sender's address and the content of the message. The script can
be stopped by pressing Ctrl+C in the terminal.

In this example, the sender sends a broadcast message every 2 seconds, and the receiver listens for any incoming broadcast messages.
Make sure to run the receiver script before the sender script. You can adjust the message content, timing, and ports based on your
requirements.

Example of multicast via UDP


Below is an example of a simple multicast program in Python using UDP. This example includes a sender ( sender_multicast.py ) that
sends multicast messages and a receiver ( receiver_multicast.py ) that listens for and prints the received messages.

Sender ( sender_multicast.py ):

1 import socket
2 import time
3
4 # Multicast group address and port
5 multicast_group = '224.0.0.1'
6 multicast_port = 12345
7
8 # Message to be multicast
9 message = "Hello, multicast world!"
10
11 # Create a UDP socket
12 sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
13
14 # Set the time-to-live (TTL) for the multicast message
15 sender_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)
16
17 try:
18 while True:
19 # Send the message to the multicast group
20 sender_socket.sendto(message.encode('utf-8'), (multicast_group, multicast_port))
21 print(f"Sent: '{message}' to {multicast_group}:{multicast_port}")
22 time.sleep(2) # Multicast every 2 seconds
23
24 except KeyboardInterrupt:
25 print("Multicast stopped.")
26 sender_socket.close()

Let's go through the sender_multicast.py script line by line

1 # Import necessary modules


2 import socket
3 import time

1. Import the socket and time modules.

1 # Multicast group address and port


2 multicast_group = '224.0.0.1'
3 multicast_port = 12345

2. Define the multicast group address as '224.0.0.1' and the multicast port as 12345 .

1 # Message to be multicast
2 message = "Hello, multicast world!"
3. Set the message to be multicast.

1 # Create a UDP socket


2 sender_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

4. Create a UDP socket using socket.socket() . AF_INET specifies the address family (IPv4), and SOCK_DGRAM specifies the socket
type (UDP).

1 # Set the time-to-live (TTL) for the multicast message


2 sender_socket.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

5. Set the time-to-live (TTL) for the multicast message. The TTL determines how many hops the message can make before being
discarded. In this case, it's set to 2 .

1 try:
2 while True:
3 # Send the message to the multicast group
4 sender_socket.sendto(message.encode('utf-8'), (multicast_group, multicast_port))
5 print(f"Sent: '{message}' to {multicast_group}:{multicast_port}")
6 time.sleep(2) # Multicast every 2 seconds

6. Start an infinite loop using while True .


7. Inside the loop, use sendto to send the encoded message to the specified multicast group and port.
8. Print a message indicating that the multicast message has been sent.
9. Introduce a 2-second delay using time.sleep(2) to multicast the message every 2 seconds.

1 except KeyboardInterrupt:
2 print("Multicast stopped.")
3 sender_socket.close()

10. Handle a KeyboardInterrupt exception (triggered by pressing Ctrl+C) to stop the sender script gracefully.
11. Print a message indicating that the multicast has stopped.
12. Close the sender socket to release system resources.

This script creates a UDP socket, sets the TTL for multicast, enters an infinite loop where it continuously sends multicast messages,
and can be stopped by pressing Ctrl+C in the terminal. The script prints messages indicating the content of the sent message and the
multicast group information.

Receiver ( receiver_multicast.py ):

1 import socket
2
3 # Multicast group address and port
4 multicast_group = '224.0.0.1'
5 multicast_port = 12345
6
7 # Create a UDP socket
8 receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
9
10 # Bind the socket to the multicast group address and port
11 receiver_socket.bind((multicast_group, multicast_port))
12
13 # Join the multicast group
14 receiver_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(multicast_group) + sock
15
16 print(f"Waiting for multicasts on {multicast_group}:{multicast_port}...")
17
18 try:
19 while True:
20 # Receive the message
21 data, address = receiver_socket.recvfrom(1024)
22 print(f"Received message from {address}: '{data.decode('utf-8')}'")
23
24 except KeyboardInterrupt:
25 print("Receiver stopped.")
26 receiver_socket.close()

Let's go through the receiver_multicast.py script line by line

1 # Import necessary modules


2 import socket

1. Import the socket module.

1 # Multicast group address and port


2 multicast_group = '224.0.0.1'
3 multicast_port = 12345

2. Define the multicast group address as '224.0.0.1' and the multicast port as 12345 .

1 # Create a UDP socket


2 receiver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

3. Create a UDP socket using socket.socket() . AF_INET specifies the address family (IPv4), and SOCK_DGRAM specifies the socket
type (UDP).

1 # Bind the socket to the multicast group address and port


2 receiver_socket.bind((multicast_group, multicast_port))

4. Bind the UDP socket to the multicast group address and port. This is where the receiver listens for incoming multicast messages.

1 # Join the multicast group


2 receiver_socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, socket.inet_aton(multicast_group) + s

5. Join the multicast group by setting a socket option. IP_ADD_MEMBERSHIP is used to join a multicast group, and
socket.inet_aton(multicast_group) + socket.INADDR_ANY specifies the multicast group address.

1 print(f"Waiting for multicasts on {multicast_group}:{multicast_port}...")

6. Print a message indicating that the script is waiting for multicast messages.

1 try:
2 while True:
3 # Receive the message
4 data, address = receiver_socket.recvfrom(1024)
5 print(f"Received message from {address}: '{data.decode('utf-8')}'")

7. Start an infinite loop using while True .


8. Inside the loop, use recvfrom to receive data and the sender's address. The received data is stored in data , and the sender's
address is stored in address .

9. Print a message indicating the address of the sender and the received message, decoded from bytes using UTF-8.

1 except KeyboardInterrupt:
2 print("Receiver stopped.")
3 receiver_socket.close()

10. Handle a KeyboardInterrupt exception (triggered by pressing Ctrl+C) to stop the receiver script gracefully.

11. Print a message indicating that the receiver has been stopped.
12. Close the receiver socket to release system resources.

This script creates a UDP socket, binds it to a specific multicast group address and port, joins the multicast group, and then enters an
infinite loop where it continuously listens for and prints incoming multicast messages. The script can be stopped by pressing Ctrl+C in
the terminal.

This multicast example uses the multicast group address '224.0.0.1' and port 12345. The sender sends a multicast message every 2
seconds, and the receiver listens for and prints the received messages. Note that both scripts need to be run in separate terminals. Also,
ensure that your network environment allows multicast communication.

Remember that multicast may not work on all networks, especially if routers are not configured to support multicast forwarding.

*network hops

in the context of IP multicast, the concept of network hops is typically associated with the Time-to-Live (TTL) field in the IP header. The
TTL field limits the number of routers or network devices a multicast packet can traverse. As the packet passes through each device,
the TTL is decremented. If the TTL reaches zero, the packet is discarded.

However, in some scenarios, network hops may not be explicitly indicated, especially in local area networks where multicast is confined
to a single subnet and doesn't need to traverse routers. In such cases, the TTL can be set to a value that allows multicast traffic to stay
within the local subnet without being limited by the TTL field.

Here's a brief explanation of how multicast can work without explicitly setting the TTL for network hops in a local subnet scenario:
1. Local Multicast:
In a local area network (LAN) or subnet, multicast traffic is often confined to devices within that subnet. Routers typically don't
forward multicast traffic between different subnets unless specifically configured to do so.
2. Default TTL:
Multicast packets may have a default TTL value set by the sender. This default TTL is often chosen to ensure that the multicast
traffic remains within the local subnet and doesn't go beyond the routers or Layer 3 devices that separate subnets.
3. Router Configuration:
If routers are configured to forward multicast traffic between subnets, the TTL value may need to be adjusted accordingly. Routers
can be configured to decrement the TTL when forwarding multicast packets, preventing them from circulating indefinitely.

In summary, while the concept of network hops and TTL is integral to multicast communication, in a local subnet scenario, default TTL
values and router configurations may allow multicast to function without explicit TTL adjustments. It's crucial to consider the network
architecture and configuration to determine the appropriate TTL settings for multicast traffic.

You might also like