0% found this document useful (0 votes)
21 views41 pages

Client-Server Networking Basics

The document provides an overview of client-server networking, focusing on network stacks, libraries, and the OSI model, which outlines the layers involved in network communication. It explains the importance of protocols in facilitating communication between devices, highlighting TCP and UDP as key protocols with distinct characteristics. Additionally, it covers concepts like IP addresses, routing, and the processes of encoding and decoding in network interactions.

Uploaded by

gopal110823
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views41 pages

Client-Server Networking Basics

The document provides an overview of client-server networking, focusing on network stacks, libraries, and the OSI model, which outlines the layers involved in network communication. It explains the importance of protocols in facilitating communication between devices, highlighting TCP and UDP as key protocols with distinct characteristics. Additionally, it covers concepts like IP addresses, routing, and the processes of encoding and decoding in network interactions.

Uploaded by

gopal110823
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-I: Client-Server Networking [10L] Max Marks: 20

1.1 The Foundations: Stacks and Libraries :-


Stacks:-
A network stack is a series of protocols and layers that work together to enable
communication between devices over a network. Each layer in the network stack has a
specific role and is responsible for a specific aspect of the communication process.
A network stack is composed of multiple layers, each with a specific role to play in the
communication process. These layers work together to enable the efficient and reliable
transfer of data between devices. Let’s take a closer look at how each layer interacts with the
layer above and below it.
Each layer in the network stack relies on the layer below it to perform its functions, and
provides services to the layer above it. Data is passed down through the layers of the network
stack, with each layer adding additional information as it passes through. This process is
called encapsulation.
Once the data reaches its destination, it is stripped of the added information, in a process
called decapsulation.
This process allows the data to be sent across different types of networks and to be
interpreted by different types of devices.
Network stacks provide numerous benefits to users, including increased reliability and
efficiency of network communication, and simplified development of network applications.
However, there are also some challenges associated with using network stacks. Let’s take a
closer look at these benefits and challenges.
Libraries:
In network programming, libraries are collections of pre-written code that help developers
perform specific tasks without having to write all the code from scratch. They provide
reusable functions and tools that simplify the coding process.
A library in programming is a set of functions and routines that can be used by a program to
perform common tasks. This allows developers to save time and effort by reusing existing
code instead of creating new code for every function they need.
Types of Libraries:
Static Libraries: These are linked to a program during the build process, becoming part of the
executable file.
Dynamic Libraries: These are linked at runtime, allowing multiple programs to use the same
library without including it in their executable files.

1.2 Layers of Application :-


The concept of layers in network programming, particularly as defined by the OSI (Open
Systems Interconnection) model, helps to simplify and standardize how different systems
communicate over a network. Here’s a simple breakdown of the relevant layers, focusing on
the Application Layer and its context within the OSI model.
The OSI model consists of seven layers, each serving a specific function in the
communication process:
1) Physical Layer: Deals with the p hysical connection and transmission of raw data bits
over a medium (like cables).
2) Data Link Layer: Ensures reliable transmission of data frames between two nodes
connected by a physical layer.
3) Network Layer: Manages the routing of data packets across multiple networks.
4) Transport Layer: Provides end-to-end communication services for applications,
ensuring complete data transfer.
5) Session Layer: Manages sessions or connections between applications, handling the
setup and teardown of these sessions.
6) Presentation Layer: Translates data between the application layer and the network,
handling data formatting, encryption, and compression.
7) Application Layer: The topmost layer where user interaction occurs, enabling
applications to communicate over the network.
Application Layer Explained
The Application Layer is crucial because it directly interacts with end-user software
applications. Here are its main functions:
User Interface: It provides a way for users to interact with software applications, such as
web browsers or email clients.
Communication Services: This layer facilitates various network services, including email
(SMTP), file transfer (FTP), and web browsing (HTTP).
Data Presentation: It ensures that data is presented in a format that users can understand,
abstracting the complexities of the underlying layers.
Protocol Handling: The Application Layer uses different protocols to manage how data is
sent and received. For instance, it can handle multiple protocols simultaneously, such as
HTTP for web traffic and FTP for file transfers.
Error Handling: It includes mechanisms to check for errors in data transmission and
ensure data integrity.
the Application Layer is where network applications operate, allowing users to send and
receive information in a user-friendly manner. It acts as a bridge between the user and the
underlying network infrastructure, ensuring that data is formatted correctly and
transmitted securely. Understanding this layer is essential for grasping how networked
applications function and communicate.
1.3 Talking a protocol :-

OSI Reference Model TCP/IP Protocol

Application Layer
HTTP, HTTPS, SSL, FTP, Telnet

Email: SMTP, POP, IMAP


Presentation Layer

Session Layer
TCP UDP

Transport Layer

Network Layer IP

Data Link Layer


Ethernet, PPP

Physical Layer

In network programming, a protocol is like a set of rules that computers follow to


communicate with each other.
What is a Protocol?
A protocol is a standardized way for devices to format, send, and receive data. Think of it as a
common language that allows different devices (like computers, smartphones, and servers) to
understand each other, even if they have different internal designs or software.
Why Are Protocols Important?
Without protocols, devices wouldn’t know how to talk to each other. For example, if one
computer uses a certain method to send data and another computer doesn’t understand that
method, they won’t be able to communicate. Protocols ensure that everyone is on the same
page, making it possible for data to flow smoothly across the network.
Key Components of Protocols
Syntax: This is about how the data is structured. It includes the format of the messages and
how they are organized.
Semantics: This refers to the meaning of the messages. It defines what the data being sent
represents.
Types of Protocols
Protocols can be categorized into different types based on their functions:
Communication Protocols: These handle the exchange of data, such as HTTP (for web
browsing) and FTP (for file transfers).
Management Protocols: These help manage and monitor network performance, like SNMP
(Simple Network Management Protocol).
Security Protocols: These ensure that data is transmitted securely, such as HTTPS (secure
version of HTTP) and SSL (Secure Sockets Layer).

Protocols are essential for enabling communication between devices on a network. They
provide the necessary rules and standards to ensure that data is sent and received correctly,
allowing the internet and other networks to function effectively.
TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) are two
fundamental protocols used for data transfer over the internet, each with distinct
characteristics and use cases.
1. Connection Type
TCP: Connection-oriented. A connection is established between the sender and receiver
before data transfer begins. This involves a process called a three-way handshake to ensure
that both parties are ready to communicate.
UDP: Connectionless. Data is sent without establishing a connection or checking if the
recipient is ready. Each packet (called a datagram) is sent independently.
2. Reliability
TCP: Highly reliable. It ensures that all data packets are delivered accurately and in the
correct order. If any packets are lost during transmission, TCP will retransmit them.
UDP: Unreliable. There is no guarantee that packets will arrive or that they will arrive in the
order they were sent. If packets are lost, they are not retransmitted.
3. Speed and Efficiency
TCP: Slower due to the overhead of establishing connections, error-checking, and ensuring
data delivery. The reliability mechanisms add extra time to the transmission process.
UDP: Faster because it has less overhead. There are no connection setups or error recovery
processes, making it suitable for applications where speed is crucial.

1.4 A Network Conversation in its Natural State :-


A "Network Conversation in its Natural State" refers to the way devices within a network
communicate and exchange information seamlessly, mimicking a natural dialogue. This
concept emphasizes the importance of intuitive interactions between users and network
systems, often facilitated by technologies like conversational AI.
Networking is like having a conversation between two computers. Just like how you talk to
your friends, computers can exchange information with each other using a set of rules called
protocols.
Imagine you want to ask your friend for their phone number. You would say something like:
"Hey, can I have your phone number?"
Your friend would then reply with their number, like:
"Sure, it's 555-1234."
This exchange follows a simple protocol - you ask for information, and your friend provides
it. Networking works the same way, but with computers instead of people.
Key Aspects of Network Conversations
Natural Language Interaction: Modern network systems, such as those integrated with
conversational AI, allow users to interact using everyday language. This is akin to asking a
question in a conversation and receiving a coherent response, making it easier for users to
engage with complex network functionalities without needing technical jargon.
Conversational AI: This technology enables machines to understand and generate human-
like responses. It combines natural language processing (NLP) and machine learning to
facilitate smooth interactions. For instance, users can ask about their network status or
troubleshoot issues in a way that feels like a natural conversation.
Real-Time Communication: Just as in a conversation where responses are immediate,
network conversations aim for real-time feedback. This allows users to quickly resolve issues
or access information, enhancing the user experience and operational efficiency.
Context Awareness: Effective network conversations consider the context of the interaction.
This means the system understands the user's intent and can provide relevant information or
solutions based on previous interactions or current queries.
User Empowerment: By simplifying the communication process, users at all levels can
engage with network systems more effectively. This democratizes access to network
management tools, allowing individuals without deep technical knowledge to navigate and
utilize network resources efficiently.
"Network Conversation in its Natural State" encapsulates the evolution of network
interactions towards more intuitive, conversational formats, leveraging AI to enhance user
engagement and streamline communication processes.
1.5 The process of encoding and decoding :-

The process of encoding and decoding is essential for effective communication, whether
between people or in computer systems. Here's a simple breakdown of these concepts:
Encoding
What is Encoding?
Encoding is the process of converting thoughts or ideas into a format that can be
communicated. This could be through spoken words, written text, gestures, or symbols.
How it Works:
Imagine you have a thought you want to share, like "I want to go for ice cream." You need to
put that thought into words. So, you say, "Do you want to go for ice cream?" This
transformation of your idea into a verbal message is encoding.
Purpose of Encoding:
The goal is to ensure that the message is clear and understandable to the receiver. It involves
choosing the right words and the appropriate way to convey the message.
Decoding
What is Decoding?
Decoding is the reverse process. It involves interpreting or understanding the message that
has been encoded by someone else.
How it Works:
Continuing with the previous example, when your friend hears your question about ice
cream, they need to interpret what you mean. They think about your words and their context,
and then they respond accordingly. This interpretation is decoding.
Purpose of Decoding:
The aim is to accurately understand the message as intended by the sender. Effective
decoding depends on the receiver's prior knowledge and experiences related to the topic.
The Communication Cycle
Interaction: Encoding and decoding are part of a continuous cycle in communication. The
sender encodes a message, the receiver decodes it, and then they might respond by encoding
a new message based on their understanding.
Feedback: After decoding, the receiver often provides feedback, which can lead to further
encoding and decoding, continuing the conversation.
In simple terms, encoding is about putting your thoughts into a communicable format, while
decoding is about understanding that message. Both processes are crucial for effective
communication, allowing people (or systems) to share and interpret information successfully.
Common examples of encoding in everyday communication include various forms of
expressing thoughts and ideas.
Usages-
1) Client Server Communication
2) Data Storage
3) API Integration
Here are some key examples:
Verbal Communication:
When you speak to someone, you encode your thoughts into spoken words. For instance,
saying "Let's meet for coffee at 3 PM" is an encoding of your desire to meet.
Written Communication:
Writing a text message or an email involves encoding your message into written language.
For example, typing "Can you pick up groceries on your way home?" encodes your request
into a format that the recipient can read.

1.6 Internet Protocol (IP Addresses) :-

All the computers of the world on the Internet network communicate with each other with
underground or underwater cables or wirelessly. If I want to download a file from the
internet or load a web page or literally do anything related to the internet, my c omputer
must have an address so that other computers can find and locate mine in order to deliver
that particular file or webpage that I am requesting. In technical terms, that address is
called IP Address or Internet Protocol Address.
IP address is referred as a number sticker given to each device that belongs to the network
which utilizes Internet Protocol to communicate. It serves two main purposes: host or
network interface recognition, identifier or location addressing.
The Internet Protocol (IP) which is pivotal in computer network protocols is responsible for
the transmission of data packages from or to devices that are connected to the Internet or
any other network. Moreover, it provides the addressing and routing mechanisms that the
devices require for their communications. IP addresses represent the unique identifiers
given to each device on a network to be able to route data packets to their receivers. IP
operates at the network layer of the OSI model. Consequently, IP operates together with
other protocols, including CP (Connection Protocol) and UDP (User Datagram Protocol), to
provide reliable and efficient communication for different devices.
A packet in IP is a meaning of both data bits and meta information for each net 0work step.
As part of it, there is a header and a payload too. The header transport on the other hand
contains control information like source and destination IP addresses, what kind of IP is
being used (V4 and V6 respectively), and others. The transmitted data is, in fact, carried in
the payload of the data stream. IP header helps in locating destination by such routers.
Routers look up into the header and check the target IP address with their routing tables and
decide the most optimal route for the packet through the entire network. Then at the
moment when the packet is to reach the destination, the header of the IP is peeled off and
the payload in which the data is encapsulated is presented to the appropriate application or
protocol running on the destination device. IP packets are the unit packets which serves as
the building blocks of message exchange on the IPR network and allows the devices to
communicate with each other irrespective of the network they use to convey data.
IP Address is a number assigned to a particular computer and is usually assigned to those
that have access to the internet. IP address consists of a block of characters like
[Link]. The process in which human-readable domain names are converted into a
series of characters is performed by DNS resolvers and as a result the users cannot access
for each website the domain name with the help of these characters. This packet includes
two addresses: the IP address of the device that is transferring the packet and that of the
device where the packet is being received.

1.7 Routing :-
The process of choosing a path across one or more networks is known as Network Routing.
Nowadays, individuals are more connected on the internet and hence, the need to use Routing
Communication is essential.
Routing chooses the routes along which Internet Protocol (IP) packets get from their
source to their destination in packet-switching networks. This article will discuss the
details of the Routing Process along with its different types and working principles.
What is a Router?
Routers are specialized pieces of network hardware that make these judgments about
Internet routing. It is a networking device that forwards data packets between
computer networks. Also, it helps to direct traffic based on the destination IP address.
It ensures that data reaches its intended destination.
As the router connects different networks, it manages data traffic between them. The
Router operates at Layer 3 (the network layer) of the OSI Model. It is also responsible
for determining the best path for data to travel from one network to another.
What is Routing?
Routing refers to the process of directing a data packet from one node to another. It is
an autonomous process handled by the network devices to direct a data packet to its
intended destination. Note that, the node here refers to a network device called –
‘Router‘.
Routing is a crucial mechanism that transmits data from one location to another across
a network (Network type could be any like LAN, WAN, or MAN). The process of
routing involves making various routing decisions to ensure reliable & efficient
delivery of the data packet by finding the shortest path using various routing metrics
which we will be discussing in this article.
Routing of a data packet is done by analysing the destination IP Address of the packet.
Look at the below image:

1.8 Fragmentation of packets. :-


The process of dividing the packet into smaller parts referred to as fragments when the
maximum segment size of the network is smaller than the packet size is called fragmentation
of a packet. The fragmented packets can be sent simultaneously with different routes to the
different ports of the destination. The destination then performs the reassembly process for
the received fragments.
In this article, we will explore the fragmentation of a packet in detail along with the fields of
Ipv4 used for fragmentation. We will also discuss the steps of fragmentation and solve some
examples of the fragmentation of a packet.
What is Fragmentation of a Packet?
Fragmentation is done in the network layer in which the large packets are divided into small
pieces called fragments to improve the data transmission over a network.
Why is Fragmentation Required?
Fragmentation of a packet is done so that the sender can send multiple fragments at the same
point of time through various paths to different ports of the destination. It is also required
when the MSS i.e., Maximum Segment Size a network can accept is smaller than the packet
size. Hence, the fragmentation is done so that the packet can be transferred easily through the
smaller MSS network.
Fragmentation Formulas
Some formulas of fragmentation of the packets are listed below.


• The actual data bytes sent previously = Sum of the fragmentation offsets.
Advantages of Fragmentation
Some advantages of fragmentation of a packet are as follows:
• Fragmentation allows different fragments to be sent simultaneously.
• Fragmentation increases the performance and efficiency of the network.
• It also enhances the throughput.
Disadvantages of Fragmentation
Some disadvantages of fragmentation are as follows:
• Reordering of the fragments required at the destination.
• Loss of data increases.
• All the networks are not capable to handle fragments.
Example:-
A datagram of 3000B (20B of IP header + 2980 of payload) reached at router and must be forward to
link with MTU of 500B. How many fragments will be generated and also write MF, offset, Total
length for value.
2980B
480B
= 7 Fragments
Fragment Offset (in 8-byte units) Payload Size Total Length MF (More Fragments)
1 0 480 500 1
2 60 480 500 1
3 120 480 500 1
4 180 480 500 1
5 240 480 500 1
6 300 480 500 1
7 360 100 120 0

Unit-II: UDP and TCP [15L] Max Marks: 25


2.1 UDP (User Datagram Protocol) :-
User Datagram Protocol (UDP) is a Transport Layer protocol. UDP is a part of the Internet Protocol
suite, referred to as UDP/IP suite. Unlike TCP, it is an unreliable and connectionless protocol. So,
there is no need to establish a connection before data transfer. The UDP helps to establish low-latency
and loss-tolerating connections over the network. The UDP enables process-to-process
communication.
User Datagram Protocol (UDP) is one of the core protocols of the Internet Protocol (IP) suite. It is a
communication protocol used across the internet for time-sensitive transmissions such as video
playback or DNS lookups. Unlike Transmission Control Protocol (TCP), UDP is connectionless and
does not guarantee delivery, order, or error checking, making it a lightweight and efficient option for
certain types of data transmission.

UDP header is an 8-byte fixed and simple header, while for TCP it may vary from 20 bytes to 60
bytes. The first 8 Bytes contain all necessary header information and the remaining part consists of
data. UDP port number fields are each 16 bits long, therefore the range for port numbers is defined
from 0 to 65535; port number 0 is reserved. Port numbers help to distinguish different user requests or
processes.

Source Port: Source Port is a 2 Byte long field used to identify the port number of the source.
Destination Port: It is a 2 Byte long field, used to identify the port of the destined packet.
Length: Length is the length of UDP including the header and the data. It is a 16-bits field.
Checksum: Checksum is 2 Bytes long field. It is the 16-bit one’s complement of the one’s
complement sum of the UDP header, the pseudo-header of information from the IP header, and the
data, padded with zero octets at the end (if necessary) to make a multiple of two octets.
Applications of UDP
• Used for simple request-response communication when the size of data is less and hence there
is lesser concern about flow and error control.
• It is a suitable protocol for multicasting as UDP supports packet switching.
• UDP is used for some routing update protocols like RIP(Routing Information Protocol).
• Normally used for real-time applications which can not tolerate uneven delays between
sections of a received message.
• VoIP (Voice over Internet Protocol) services, such as Skype and WhatsApp, use UDP for real-
time voice communication. The delay in voice communication can be noticeable if packets
are delayed due to congestion control, so UDP is used to ensure fast and efficient data
transmission.
• DNS (Domain Name System) also uses UDP for its query/response messages. DNS queries
are typically small and require a quick response time, making UDP a suitable protocol for this
application.
• DHCP (Dynamic Host Configuration Protocol) uses UDP to dynamically assign IP addresses
to devices on a network. DHCP messages are typically small, and the delay caused by packet
loss or retransmission is generally not critical for this application.

2.2 Numbers of particular service on the particular system :-


In network programming, the concept of "numbers of particular service on the particular system"
typically refers to the use of port numbers associated with network services. These port numbers are
crucial for identifying specific services running on a host and facilitating communication between
clients and servers.
Port Numbers and Their Ranges
Port numbers are 16-bit integers used in networking to distinguish between different services on a
single device. They are categorized into three primary ranges:
Well-known ports (0-1023): These ports are reserved for widely used services and protocols. For
example, HTTP operates on port 80, while FTP uses port 21.
Registered ports (1024-49151): These ports are assigned by the Internet Assigned Numbers Authority
(IANA) for specific services that are not as universally recognized as those using well-known ports.
Dynamic or private ports (49152-65535): These ports are typically used for temporary connections,
often assigned dynamically by the operating system when a connection is initiated.
Network Services and Protocols
Network services are applications that operate at the application layer of the network stack. They
provide functionalities such as data storage, communication, and resource sharing. Examples include:
Web services (HTTP): Typically use port 80 for unencrypted traffic and port 443 for encrypted traffic
(HTTPS).
Email services (SMTP): Use port 25 for sending emails.
File transfer services (FTP): Use ports 20 and 21.
These services rely on underlying transport layer protocols, primarily TCP (Transmission Control
Protocol) for connection-oriented services, which ensures reliable data transmission, and UDP (User
Datagram Protocol) for connectionless services, which is faster but does not guarantee delivery or
order of packets.
Client-Server Architecture
In a typical client-server model, the server provides services to clients. Each server application listens
on a specific port number, allowing clients to connect and request services. The communication is
established through sockets, which are endpoints for sending and receiving data. Each socket is bound
to a port number, enabling the operating system to route incoming messages to the correct application.
Example of Services
DNS (Domain Name System): Translates domain names to IP addresses, typically using port 53.
DHCP (Dynamic Host Configuration Protocol): Assigns IP addresses to devices on a network, usually
operating on ports 67 and 68.

2.3 Communications connection point (Socket) :-


A socket in network programming serves as a communications connection point, functioning as an
endpoint for data exchange between two software applications. It is essential for enabling
communication over a network, whether between processes on the same machine or across different
systems.
Definition and Functionality
A socket represents a unique connection between two programs, allowing them to communicate using
established protocols. This communication can be either connection-oriented (like TCP) or
connectionless (like UDP). In a connection-oriented scenario, a connection is established, allowing for
a continuous dialogue, whereas connectionless communication does not require a persistent
connection.
Types of Sockets
Stream Sockets (SOCK_STREAM):
These are connection-oriented and ensure reliable data transfer. They establish an end-to-end
connection and handle data flow control to prevent overruns. Data is sent as a continuous stream of
bytes without record boundaries.
Datagram Sockets (SOCK_DGRAM):
These are connectionless and do not guarantee delivery, order, or error-checking. Each datagram is
sent independently, similar to sending letters through the postal service, where each letter may take a
different route.
Communication Process
In a typical client-server model, the server creates a socket bound to a specific port and listens for
incoming connection requests. The client, knowing the server's address and port, initiates a
connection. Upon acceptance, both client and server can communicate by sending and receiving data
through their respective sockets. This interaction can be visualized as a two-way phone call, where
each party can speak and listen simultaneously.
Socket API Functions
The socket API provides several functions to manage socket operations:
socket(): Creates a new socket.
bind(): Associates the socket with a specific port.
listen(): Prepares the socket to accept incoming connections.
accept(): Accepts a connection from a client.
send() and recv(): Used for sending and receiving data.
close(): Terminates the socket connection.
Sockets are crucial for network programming, enabling robust communication between applications
across various platforms and networks. They facilitate both simple and complex interactions in client-
server architectures, making them fundamental to modern networking.
2.4 Unreliability: Backoff, blocking, and timeouts :-
In network programming, unreliability refers to challenges in network communications where data
delivery may not be guaranteed due to various issues like network congestion, packet loss, or server
overload. Handling unreliability often involves implementing mechanisms like backoff, blocking, and
timeouts to manage delays, retries, and connection failures effectively.
1. Backoff
Back-off algorithm is a collision resolution mechanism which is used in random access MAC
protocols (CSMA/CD). This algorithm is generally used in Ethernet to schedule re-transmissions after
collisions. If a collision takes place between 2 stations, they may restart transmission as soon as they
can after the collision. This will always lead to another collision and form an infinite loop of
collisions leading to a deadlock. To prevent such scenario back-off algorithm is used. Let us consider
a scenario of 2 stations A and B transmitting some data:
After a collision, time is divided into discrete slots (Tslot) whose length is equal to 2t, where t is the
maximum propagation delay in the network. The stations involved in the collision randomly pick an
integer from the set K i.e {0, 1}. This set is called the contention window. If the sources collide again
because they picked the same integer, the contention window size is doubled and it becomes {0, 1, 2,
3}. Now the sources involved in the second collision randomly pick an integer from the set {0, 1, 2,
3} and wait for that number of time slots before trying again. Before they try to transmit, they listen to
the channel and transmit only if the channel is idle. This causes the source which picked the smallest
integer in the contention window to succeed in transmitting its frame. So, the Back-off algorithm
defines a waiting time for the stations involved in collision, i.e. for how much time the station should
wait to re-transmit.
Example -Case-1 : Suppose 2 stations A and B start transmitting data (Packet 1) at the same time
then, collision occurs. So, the collision number n for both their data (Packet 1) = 1. Now, both the
station randomly pick an integer from the set K i.e. {0, 1}.

• When both A and B choose K = 0 --> Waiting time for A = 0 * T slot = 0 Waiting time for B
= 0 * T slot = 0 Therefore, both stations will transmit at the same time and hence collision
occurs.
• When A chooses K = 0 and B chooses K = 1 --> Waiting time for A = 0 * T slot = 0 Waiting
time for B = 1 * T slot = T slot Therefore, A transmits the packet and B waits for time
T slot for transmitting and hence A wins.
• When A chooses K = 1 and B chooses K = 0 --> Waiting time for A = 1 * T slot =
T slot Waiting time for B = 0 * T slot = 0 Therefore, B transmits the packet and A waits for
time T slot for transmitting and hence B wins.
• When both A and B choose K = 1 --> Waiting time for A = 1 * T slot = T slot Waiting time
for B = 1 * T slot = T slot Therefore, both will wait for the same time T slot and then transmit.
Hence, a collision occurs.
Probability that A wins = 1/4
Probability that B wins = 1/4
Probability of collision = 2/4

2. Blocking
Blocking occurs when a network operation (like reading from a socket or establishing a connection)
waits indefinitely until the operation is complete or data is available. A blocking operation can make
an application unresponsive if the network is slow or down.

Blocking Sockets: In blocking mode, a socket operation (e.g., receiving data) will wait until it has
completed or an error occurs. This can be a problem if there are unexpected delays, as it halts program
execution.
Non-blocking Sockets: With non-blocking sockets, a network operation returns immediately if it
cannot be completed, allowing the program to perform other tasks or try again later.
Usage Example: Non-blocking mode or asynchronous programming is often used in networked
applications to avoid hanging on slow network responses, enhancing the application’s responsiveness.
3. Timeouts
Timeouts are limits on how long a program will wait for a network operation to complete. Setting a
timeout ensures that the program doesn't wait indefinitely and can handle delays or failures gracefully.

Connection Timeout: Limits how long to wait for a network connection to be established.
Read/Write Timeout: Sets limits on the time allowed to read from or write to a network connection.
Usage Example: In web applications or APIs, timeouts prevent the client from waiting too long for a
response from the server, which improves the user experience by providing feedback on network
status.
In network programming, backoff, blocking, and timeouts are often combined to ensure robust
communication. For instance, if a client attempts to connect to a server but fails, it might use
exponential backoff for retries, set timeouts to avoid waiting indefinitely, and manage blocking
behavior to prevent the application from freezing.

2.5 UDP Socket Connection


UDP does not establish a connection, making it faster
UDP is a connection less protocol. There is no connection is established between client and server. In
UDP, the client does not form a connection with the server like in TCP and instead, It just sends a
datagram. Similarly, the server need not to accept a connection and just waits for datagrams to arrive.
We can call a function called connect() in UDP but it does not result anything like it does in TCP.
There is no 3 way handshake. It just checks for any immediate errors and store the peer's IP address
and port number. connect() is storing peers address so no need to pass server address and server
address length arguments in sendto().
• The UDP does not provide guaranteed delivery of message packets. If for some issue in a
network if a packet is lost it could be lost forever.
• Since there is no guarantee of assured delivery of messages, UDP is considered an unreliable
protocol.
• The underlying mechanisms that implement UDP involve no connection-based
communication. There is no streaming of data between a UDP server or and an UDP client.
• An UDP client can send "n" number of distinct packets to an UDP server and it could also
receive "n" number of distinct packets as replies from the UDP server.
• Since UDP is connectionless protocol the overhead involved in UDP is less compared to a
connection based protocol like TCP.
Datagram Sockets: Datagram sockets allow processes to use the User Datagram Protocol (UDP). It
is a two-way flow of communication or messages. It can receive messages in a different order from
the sending way and also can receive duplicate messages. These sockets are preserved with their
boundaries. The socket type of datagram socket is SOCK_DGRAM.
Server Socket Creation
import socket
s = [Link](socket.AF_INET, socket.SOCK_DGRAM)
[Link](("localhost", 9999))
print("UDP server waiting...")
while True:
data, addr = [Link](1024)
[Link](data, addr)

Socket Module- [Link](socket_family, socket_type, protocol=0)

• socket_family-AF_UNIX
• socket_type- SOCK_DGRAM
• protocol-left out, ot defaulting to 0
• Once socket object is created as mentioned above, now we can use functions below to create
client server programs.
Socket methods

2.6 The Use of Request IDs Is a Good Idea :-


A system called an intrusion detection system (IDS) observes network traffic for malicious
transactions and sends immediate alerts when it is observed. It is software that checks a network or
system for malicious activities or policy violations. Each illegal activity or violation is often recorded
either centrally using an SIEM system or notified to an administration. IDS monitors a network or
system for malicious activity and protects a computer network from unauthorized access from users,
including perhaps insiders. The intrusion detector learning task is to build a predictive model (i.e. a
classifier) capable of distinguishing between ‘bad connections’ (intrusion/attacks) and ‘good (normal)
connections’.
Working of Intrusion Detection System(IDS)
• An IDS (Intrusion Detection System) monitors the traffic on a computer network to detect any
suspicious activity.
• It analyzes the data flowing through the network to look for patterns and signs of abnormal
behavior.
• The IDS compares the network activity to a set of predefined rules and patterns to identify
any activity that might indicate an attack or intrusion.
• If the IDS detects something that matches one of these rules or patterns, it sends an alert to the
system administrator.
• The system administrator can then investigate the alert and take action to prevent any damage
or further intrusion.
Understanding Intrusion Intrusion is when an attacker gets unauthorized access to a device, network,
or system. Cyber criminals use advanced techniques to sneak into organizations without being
detected. Common methods include:
• Address Spoofing: Hiding the source of an attack by using fake, misconfigured, or unsecured
proxy servers, making it hard to identify the attacker.
• Fragmentation: Sending data in small pieces to slip past detection systems.
• Pattern Evasion: Changing attack methods to avoid detection by IDS systems that look for
specific patterns.
• Coordinated Attack: Using multiple attackers or ports to scan a network, confusing the IDS
and making it hard to see what is happening.
Benefits of IDS
• Detects Malicious Activity: IDS can detect any suspicious activities and alert the system
administrator before any significant damage is done.
• Improves Network Performance: IDS can identify any performance issues on the network,
which can be addressed to improve network performance.
• Compliance Requirements: IDS can help in meeting compliance requirements by
monitoring network activity and generating reports.
• Provides Insights: IDS generates valuable insights into network traffic, which can be used to
identify any weaknesses and improve network security.

2.7 From Binding till Interfaces :-


Binding in networking refers to the process of associating a network service or socket with a specific
network interface or IP address. This is crucial in scenarios where multiple network interfaces are
present, allowing for more controlled traffic management and security.
Binding to Interfaces
Binding a service or socket to a specific network interface can be achieved through various methods,
depending on the operating system and the programming context. The primary goal is to ensure that
traffic is directed through the intended network interface, which can help in load balancing, security,
and network management.
1. Service Binding:
• Services can also be bound to specific network interfaces. For instance, in systems
like Commvault, services can be configured to bind to a specific Network Interface
Card (NIC) to limit exposure to public networks. This is done by specifying the
interface's IP address in the service configuration settings.
• Load Balancing: Binding SNIPs to specific interfaces can facilitate load balancing across
multiple links to an upstream switch, especially in scenarios lacking Link Aggregation
support.
• Security: By binding services to specific interfaces, organizations can restrict access to
sensitive services, ensuring they are only reachable through secure or internal networks.
• Network Management: Binding allows network administrators to control traffic flow and
monitor performance on specific interfaces, aiding in troubleshooting and optimization.
Network programming involves creating software that can communicate with other devices over a
network. Key concepts such as binding and interfaces are fundamental to the way network
applications operate, especially when dealing with sockets.
What is Binding in Network Programming?
Binding is the process of associating a socket with a specific local IP address and port number. When
a server program creates a socket to listen for incoming connections, it must bind that socket to a local
address and port to "claim" it. This process informs the operating system which network endpoint the
socket will use to send and receive data.
For example, in socket API (e.g., Berkeley sockets), the function bind() is used:
It binds a socket descriptor to a sockaddr structure containing an IP address and port.
Without binding, the OS will not know how to route incoming packets to your application.
Binding is mandatory for server sockets that listen for incoming connections.
For clients, binding is optional because the OS can automatically assign an ephemeral port.
Role of Network Interfaces
A network interface is a hardware or virtual networking device that connects a computer to a network.
Examples include Wi-Fi cards, Ethernet cards, loopback devices, or virtual adapters.
Each interface has one or more IP addresses assigned.
When binding a socket, you can specify which interface’s IP address your server program should use
to listen.
Interfaces allow you to have multiple networking paths. For example, a machine can have:
Ethernet interface: [Link]
Wi-Fi interface: [Link]
Loopback interface: [Link]
How Interfaces Relate to Binding
If you bind a socket to INADDR_ANY (for IPv4) or the equivalent for IPv6, it means the socket will
listen on all available interfaces.
Binding to a specific IP exposes the service only on that particular interface.
This is important for security and network design. For example, listening on [Link] means the
server only accepts connections from the local machine.
Summary Flow: From Binding to Interfaces in Network Programming
Socket Creation: Create a socket descriptor.
Binding: Associate socket with a specific local IP address and port.
Interface Selection:
Binding to a specific interface’s IP means listening only there.
Binding to INADDR_ANY means listening on all interfaces.
Listening and Accepting: The socket listens and accepts connections on the designated interface and
port.
Communication: Data is sent or received via the bound network interface.
Why This Matters
Understanding binding and network interfaces helps:
Design network servers that listen on the correct interfaces.
Avoid conflicts such as two programs trying to bind to the same port.
Implement multi-interface network applications.
Secure applications by limiting exposure.

2.8 Fragmentation of UDP :-


An UDP application may wish to avoid IP fragmentation, because when the size of the resulting
datagram exceeds the link’s MTU, the IP datagram is split across multiple IP packets, which can lead
to performance issues because if any fragment is lost, the entire datagram is lost.
A single UDP datagram with 2992 UDP payload bytes is fragmented into three UDP/ IPv4 packets
(no options). The UDP header that contains the source and destination port numbers appears only in
the first fragment (a complicating factor for firewalls and NATs). Fragmentation is controlled by
the Identification, Fragment Offset, and More Fragments (MF) fields in the IPv4 header.
The original UDP datagram included 2992 bytes of application (UDP payload) data and 8 bytes of
UDP header, resulting in an IPv4 Total Length field value of 3020 bytes (IP header is 20-byte). When
this datagram was fragmented into three packets, 40 extra bytes were created (20 bytes for each of the
newly created IPv4 fragment headers). Thus, the total number of bytes sent is 3060. [p489]
Fields:
• Identification: its value (set by the original sender) is copied to each fragment and is used to
group them together when they arrive
• Fragment Offset: the offset of the first byte of the fragment payload byte in the original IPv4
datagram (in 8-byte units)
• MF: indicates whether more fragments in the datagram should be expected and is 0 only in
the final fragment
If one fragment is lost, the entire datagram is lost, since IP itself has no error correction mechanism of
its own. Mechanisms such as timeout and retransmission are left as the responsibility of the higher
layers. For this reason, fragmentation is often avoided.
We can use our sock program and increase the size of the datagram until fragmentation occurs. On an
Ethernet, the maximum amount of data in a frame is ordinarily 1500 bytes, which leaves at most 1472
bytes for application data to avoid fragmentation, assuming 20 bytes for the IPv4 header and 8 bytes
for the UDP header.
We will run our sock program with data sizes of 1471, 1472, 1473, and 1474 bytes. We expect the last
two to cause fragmentation:
[p490-492]
Linux% sock -u -i -n1 -w1471 [Link] discard
Linux% sock -u -i -n1 -w1472 [Link] discard
Linux% sock -u -i -n1 -w1473 [Link] discard
Linux% sock -u -i -n1 -w1474 [Link] discard
1 23:42:43.562452 [Link].46530 > [Link].9:
udp 1471 (DF) (ttl 64, id 61350, len 1499)
2 23:42:50.267424 [Link].46531 > [Link].9:
udp 1472 (DF) (ttl 64, id 62020, len 1500)
3 23:42:57.814555 [Link] > [Link]:
udp (frag 37671:1@1480) (ttl 64, len 21)
4 23:42:57.814715 [Link].46532 > [Link].9:
udp 1473 (frag 37671:1480@0+) (ttl 64, len 1500)
5 23:43:04.368677 [Link] > [Link]:
udp (frag 37672:2@1480) (ttl 64, len 22)
6 23:43:04.368838 [Link].46535 > [Link].9:
udp 1474 (frag 37672:1480@0+) (ttl 64, len 1500)
One observation that may be surprising is that the fragments with larger offsets are delivered prior to
the first fragments. In effect, the sender has intentionally reordered the fragments. This behavior can
be beneficial. If the last fragment is delivered first, the receiving host is able to ascertain the
maximum amount of buffer space it will require in order to reassemble the entire datagram.

2.9 Options for Sockets :-


In network programming, socket options are settings that control the behavior of sockets, allowing
fine-tuning for different network conditions or specific application requirements. By configuring
socket options, developers can adjust performance, manage connection stability, handle timeouts, and
more. These options can be set and retrieved using functions like setsockopt() and getsockopt() in
languages such as C and Python.
Here’s an overview of commonly used socket options and their purposes:
1. SO_REUSEADDR (Reuse Address)
Purpose: Allows a socket to bind to a port that is in a TIME_WAIT state (a state that prevents
immediate reuse after a connection is closed).
Use Case: Useful in servers that restart frequently and need to rebind to the same port without waiting
for the old connection to clear.
Example: Setting SO_REUSEADDR lets a web server bind to a port that may have lingering
connections in TIME_WAIT.
Socket options allow applications to tailor network communication for specific requirements, from
latency-sensitive applications (like gaming and voice calls) to high-throughput applications (like file
transfers). Understanding and correctly applying socket options can greatly enhance network
performance, reliability, and responsiveness in various networked applications.

2.10 Broadcast :-
broadcasting is a communication method where a message is sent from one host to all devices on a
network simultaneously. Broadcasting is commonly used in local area networks (LANs) for
operations such as network discovery, where a device announces its presence or requests services
from others in the network.
Broadcast Address: A broadcast message is sent to a special address that represents all devices on the
network. For example, in IPv4 networks, the broadcast address [Link] targets all devices in
the local network.
Broadcast Domain: Broadcasting is limited to a specific network segment called the broadcast
domain, usually defined by a router. Routers typically do not forward broadcast packets across
different network segments, so broadcasts stay local.

UDP Broadcasting: UDP (User Datagram Protocol) is often used for broadcasting because it doesn’t
require a connection, allowing data to be sent out to multiple devices with minimal overhead.
Broadcast messages are often sent over specific UDP ports relevant to the service being broadcast.
Network Discovery: Devices use broadcasts to find others on the network, such as printers or file
servers, especially if they don’t know the exact IP address.
Address Assignment (DHCP): DHCP (Dynamic Host Configuration Protocol) relies on broadcasting
for clients to request an IP address. The client broadcasts a request, and a DHCP server responds with
configuration information.
Service Discovery: Protocols like SSDP (Simple Service Discovery Protocol) use broadcasts to let
devices advertise their services, commonly used in smart home devices and media streaming
applications.
2.11 When Should We Use UDP?
In situations where you really want to get a simple answer to another server quickly, UDP works best.
In general, you want the answer to be in one response packet, and you are prepared to implement your
own protocol for reliability or to resend. DNS is the perfect description of this use case. The costs of
connection setups are way too high (yet, DNS does support a TCP mode as well).
Another case is when you are delivering data that can be lost because newer data coming in will
replace that previous data/state. Weather data, video streaming, a stock quotation service (not used for
actual trading), or gaming data comes to mind.
Another case is when you are managing a tremendous amount of state and you want to avoid using
TCP because the OS cannot handle that many sessions. This is a rare case today. In fact, there are now
user-land TCP stacks that can be used so that the application writer may have finer grained control
over the resources needed for that TCP state. Prior to 2003, UDP was really the only game in town.
One other case is for multicast traffic. UDP can be multicasted to multiple hosts whereas TCP cannot
do this at all.
Examples include video streaming and especially VoIP (e.g. Skype). In those instances, however, a
dropped packet is not such a big deal: our senses aren't perfect, so we may not even notice. That is
why these types of applications use UDP instead of TCP.
The "unreliability" of UDP is a formalism. Transmission isn't absolutely guaranteed. As a practical
matter, they almost always get through. They just aren't acknowledged and retried after a timeout.
The overhead in negotiating for a TCP socket and handshaking the TCP packets is huge. Really huge.
There is no appreciable UDP overhead.
Most importantly, you can easily supplement UDP with some reliable delivery hand-shaking that's
less overhead than TCP. Read this: [Link]
UDP is useful for broadcasting information in a publish-subscribe kind of application. IIRC, TIBCO
makes heavy use of UDP for notification of state change.
Any other kind of one-way "significant event" or "logging" activity can be handled nicely with UDP
packets. You want to send notification without constructing an entire socket. You don't expect any
response from the various listeners.
System "heartbeat" or "I'm alive" messages are a good choice, also. Missing one isn't a crisis. Missing
half a dozen (in a row) is.

2.12 Transmission Control Protocol (TCP) :-


Transmission Control Protocol (TCP) is a connection-oriented protocol for communications that helps
in the exchange of messages between different devices over a network. The Internet Protocol (IP),
which establishes the technique for sending data packets between computers, works with TCP.
The position of TCP is at the transport layer of the OSI model. TCP also helps in ensuring that
information is transmitted accurately by establishing a virtual connection between the sender and
receiver.
What is Internet Protocol (IP)?
Internet Protocol (IP) is a method that is useful for sending data from one device to another from all
over the internet. It is a set of rules governing how data is sent and received over the internet. It is
responsible for addressing and routing packets of data so they can travel from the sender to the correct
destination across multiple networks. Every device contains a unique IP Address that helps it
communicate and exchange data across other devices present on the internet.
Working of Transmission Control Protocol (TCP)
Transmission Control Protocol (TCP) model breaks down the data into small bundles and afterward
reassembles the bundles into the original message on the opposite end to make sure that each message
reaches its target location intact. Sending the information in little bundles of information makes it
simpler to maintain efficiency as opposed to sending everything in one go.
After a particular message is broken down into bundles, these bundles may travel along multiple
routes if one route is jammed but the destination remains the same.

TCP
For Example: When a user requests a web page on the internet, somewhere in the world, the server
processes that request and sends back an HTML Page to that user. The server makes use of a protocol
called the HTTP Protocol. The HTTP then requests the TCP layer to set the required connection and
send the HTML file.
Now, the TCP breaks the data into small packets and forwards it toward the Internet Protocol (IP)
layer. The packets are then sent to the destination through different routes.
The TCP layer in the user’s system waits for the transmission to get finished and acknowledges once
all packets have been received.

Unit-III: Network Servers [15L] Max Marks: 20


3.1 Architecture of the server :-
In network programming, the architecture of a server refers to how the server is structured and how
it interacts with clients (like your computer or phone). Here’s a simple breakdown:
Client-Server Model:
The server is a powerful computer that provides resources or services to other computers, known as
clients. When you use an app or a website, your device (the client) sends requests to the server, which
processes these requests and sends back the appropriate responses.
Components of a Server:
Hardware: This includes the physical parts of the server, like the CPU, memory, and storage.
Software: This is the operating system and applications that run on the server. The software manages
how the server responds to client requests.
When a client wants to access data (like a webpage), it sends a request to the server over the internet.
The server receives this request, processes it (which might involve accessing a database or performing
calculations), and then sends back the data to the client.
Types of Server Architectures:
One-Tier Architecture: This is the simplest form where everything runs on a single machine without
network access. It’s not common for web applications but is useful for standalone applications.
Multi-Tier Architecture: This involves multiple layers, such as a web server, application server, and
database server. Each layer has its own responsibilities, which helps in managing complex
applications more efficiently.
Event-Driven Architecture:
In more advanced setups, servers can use an event-driven architecture. This means the server reacts to
events (like a user clicking a button) rather than following a strict sequence of operations. This can
make the server more responsive and efficient.
The architecture of a server in network programming is all about how it is built and how it
communicates with clients. It involves both hardware and software components, and it can be
structured in various ways to handle different types of requests efficiently. Understanding this
architecture is crucial for developing robust network applications.
3.2 Message queues and caches:-
In network programming, message queues and caches are two important concepts that help improve
the efficiency and performance of applications. Let’s break them down in simple terms.
Message Queues
What is a Message Queue?
A message queue is like a waiting line for messages. When one part of a program (like a server) wants
to send information to another part (like a client or another server), it puts that information in the
queue. This way, the receiving part can process the messages one at a time, without getting
overwhelmed.
Imagine you’re at a coffee shop. You place your order (send a message), and the barista (the server)
takes your order and puts it in a queue. The barista then prepares each order in the order they were
received. This helps manage the flow of orders and ensures that no one gets skipped.
Benefits:
Decoupling: The sender and receiver don’t need to be online at the same time. The sender can send a
message, and the receiver can process it later.
Load Balancing: If many messages come in, they can be distributed across multiple servers to handle
them efficiently.
Caches
What is a Cache?
A cache is like a temporary storage area that keeps frequently accessed data close at hand. Instead of
fetching the same data from a database every time, the application can quickly retrieve it from the
cache.
Think of a library. If you frequently borrow the same book, the librarian might keep a copy on the
front desk for you. This way, you don’t have to go all the way to the back of the library every time
you want that book. The cache works similarly by storing copies of data that are used often.
Benefits:
Speed: Accessing data from a cache is much faster than retrieving it from a database, which can take
longer.
Reduced Load: By using a cache, the server doesn’t have to work as hard to fetch data from the
database, which can improve overall performance.
Message queues help manage communication between different parts of an application by organizing
messages in a way that prevents overload, while caches speed up data retrieval by storing frequently
used information for quick access. Both are essential for building efficient and responsive network
applications!
3.3 HTTP clients :-
In network programming, an HTTP client is a tool or software that allows a user or application to
send requests to a server using the HTTP (Hypertext Transfer Protocol). Let’s break this down in very
simple terms.
What is HTTP?
• HTTP is a protocol used for transferring data over the web. It’s the foundation of any data
exchange on the Web and is used for loading web pages, images, and other resources.
What is an HTTP Client?
Definition:
o An HTTP client is like a messenger that sends requests to a server and waits for a
response. When you use a web browser (like Chrome or Firefox), you are using an
HTTP client.
o When you type a website address (URL) into your browser and hit enter, the browser
(HTTP client) sends a request to the server that hosts that website. The server
processes the request and sends back the requested data (like the webpage), which the
browser then displays to you.
Types of HTTP Clients:
o Web Browsers: These are the most common HTTP clients. They allow users to
navigate the web.
o API Clients: These are used by developers to interact with web services. For
example, tools like Postman allow developers to send requests to APIs to test and
retrieve data.
Why Are HTTP Clients Important?
• Communication: They enable communication between users (or applications) and servers.
Without HTTP clients, we wouldn’t be able to access websites or use online services.
• Data Retrieval: They help retrieve data from servers, making it possible to load content like
images, videos, and text.
An HTTP client is a software tool that sends requests to servers using the HTTP protocol and
receives responses. It plays a crucial role in how we interact with the web, allowing us to access and
retrieve information easily. Whether it’s a web browser or a specialized tool for developers, HTTP
clients are essential for network programming and web communication!
3.4 Servers that handle HTTP :-

3.5 www (World Wide Web) :-


The World Wide Web, commonly known as the Web or WWW, is a vast system of interconnected
documents and resources that are accessed via the Internet. It allows users to view and interact with a
wide variety of content, including text, images, videos, and applications. Here’s a detailed explanation
of its components, history, and significance.
The World Wide Web is a powerful and essential part of modern life, enabling access to information,
communication, and commerce on a global scale. Its invention by Tim Berners-Lee has had a
profound impact on society, shaping how we interact with the world and each other. The Web
continues to evolve, influencing various aspects of our daily lives and the future of technology.
History of the World Wide Web
The World Wide Web was invented by Tim Berners-Lee, a British scientist, in 1989 while he was
working at CERN (the European Organization for Nuclear Research). His goal was to create a system
that would allow researchers to share information easily.
The first website went live in 1991, and it provided information about the World Wide Web project
itself. This marked the beginning of the Web as we know it today.
The Web gained significant popularity in the mid-1990s, leading to the development of web browsers
that made it easier for people to access and navigate the Internet. The introduction of graphical
browsers like Netscape Navigator transformed the Web into a user-friendly platform.
The World Wide Web is a collection of web pages and resources that are linked together using
hyperlinks. It operates over the Internet, which is the underlying network that connects computers
globally.
The Web uses the Hypertext Transfer Protocol (HTTP) to transmit data. When you enter a web
address (URL) in your browser, it sends a request to a server that hosts the website. The server then
responds by sending the requested web page back to your browser, which displays it for you to view.
Components:
Web Pages: These are documents written in HTML (Hypertext Markup Language) that can include
text, images, and links to other pages.
Web Browsers: Software applications like Chrome, Firefox, and Safari that allow users to access and
navigate the Web.
Web Servers: Computers that store web pages and respond to requests from browsers.

3.6 E-mail construction and parsing :-


Parsing an email involves reading and interpreting the components of the email message.
Extract Headers: Read header fields to understand sender, recipient, subject, etc.
Each header ends with a newline, making it easier to parse line by line.
Headers are Metadata about the email.
Example of Header:
From: sender@[Link]
To: recipient@[Link]
Subject: Hello World
Date: Wed, 30 Oct 2024 10:30:00 +0000
Look for specific headers like “From,” “To,” and “Subject.”
Read the Body: Extract the main content of the email.
Body is Main content of the email.
Use MIME types to determine whether the body is plain text or HTML.
MIME Standard for including multiple parts in an email.
For HTML bodies, you might need to render HTML or strip it down for text-only use.
Decode Attachments: If the email has attachments, they’re encoded in Base64.
Use the MIME boundary markers to identify where attachments start.
Decode Base64 data to retrieve the actual file.
Protocols for Parsing:
IMAP (Internet Message Access Protocol) and POP3 (Post Office Protocol) are used to receive emails
from a server.
IMAP allows for more complex features like searching emails directly on the server without
downloading.
Constructing an Email: Setting up headers, adding body content, encoding attachments, and sending
over SMTP.
Parsing an Email: Reading headers, identifying body and MIME types, decoding attachments, and
retrieving data using IMAP or POP3.
Parsing: Separating headers and body, and processing each part.
3.7 SMTP :-
SMTP, or Simple Mail Transfer Protocol, is a protocol used in network programming to send and
transfer emails between email servers and from clients to servers. Operating over TCP/IP, SMTP is
specifically designed for reliable and efficient email delivery across different systems. Here's a
detailed explanation of how it works and why it's essential in email transmission.
SMTP is fundamentally a "push" protocol used for sending emails. It operates primarily on port 25,
although secure versions also use ports 465 and 587. When a user sends an email, their email client
(like Outlook or Gmail) establishes a connection with the SMTP server. The client then sends
commands to the SMTP server, which processes each command, providing a response code for every
operation.
For example:
The Client Connects: The email client connects to the SMTP server, and the server responds with a
greeting. This initial handshake starts the process.
Authentication (if required): If the SMTP server requires authentication, the client must provide login
credentials to verify the sender's identity. This helps prevent unauthorized users from sending spam
emails.
Mail From Command: After authentication, the client uses the MAIL FROM command to specify the
sender's email address. The SMTP server will respond with a success code if it accepts the email
address.
Recipient Command: Next, the client specifies the recipient(s) using the RCPT TO command. For
each recipient, the SMTP server verifies that it can deliver to the address or transfer it to another
server.
Data Command: After specifying all recipients, the client sends the DATA command, signaling the
start of the email content. The SMTP server responds with a code to indicate it’s ready to receive the
data.
Sending the Email Content: The client then sends the email’s headers and body. The message ends
with a single line containing just a period (.), which tells the server the email is complete. The SMTP
server processes the email and confirms it’s ready to be sent.
Quit Command: Finally, the client sends the QUIT command to end the SMTP session. The SMTP
server closes the connection, marking the end of the email transfer.
SMTP Commands and Response Codes
SMTP relies on specific commands and response codes to ensure smooth communication. Each
command receives a response code, confirming the outcome of the operation.
HELO/EHLO: The client introduces itself to the server.
MAIL FROM: Specifies the sender's address.
RCPT TO: Specifies the recipient(s).
DATA: Signals the start of the email’s content.
QUIT: Ends the connection.
Response Codes provide feedback:
250: Requested action completed successfully.
354: Start mail input; end with a period on a new line.
421: Service not available.
550: Requested action not taken (e.g., mailbox unavailable or authentication failure).
SMTP Relay and Email Routing
SMTP servers often work in relay to transmit emails from one server to another until it reaches the
recipient's mail server. If the recipient's server is on the same network, the email is delivered directly.
If not, it’s relayed through several servers until it reaches its destination. SMTP servers also use DNS
(Domain Name System) to look up the recipient’s email server by checking MX (Mail Exchange)
records.
Secure SMTP (SMTPS)
To protect email content and prevent unauthorized access, SMTP can be secured with Transport Layer
Security (TLS). In secure SMTP, the communication between the client and server is encrypted,
commonly using ports 465 or 587, ensuring the email content remains confidential.
SMTP and POP/IMAP
SMTP only handles sending emails. Receiving emails relies on other protocols like POP3 (Post Office
Protocol) or IMAP (Internet Message Access Protocol), which allow users to access and manage their
emails from their mail server.
SMTP is crucial for email transmission, enabling email clients and servers to communicate efficiently,
ensuring that email content is transferred securely and reliably across networks. Through its series of
commands and response codes, SMTP forms the backbone of email delivery on the internet.
3.8 POP :-
POP, or Post Office Protocol, is a protocol in network programming primarily used for retrieving
emails from a remote server to a local client. Designed to allow users to download their emails to a
device and then read them offline, POP is one of the oldest and most widely used email retrieval
protocols. The current version, POP3, has become the standard, often referred to simply as POP.
Here’s a detailed look at how POP works, its commands, and how it differs from other protocols.
POP operates on a client-server model and typically uses port 110 for unencrypted connections or port
995 for secure, encrypted connections (POP3S). When a user wants to retrieve their emails, their
email client (such as Outlook or Thunderbird) connects to the email server using POP. Once the
connection is established, the protocol enables the user to download messages from the server to their
local device. After download, emails are often deleted from the server by default, meaning they’re
accessible only on the device where they were downloaded. This behavior is why POP is preferred for
users who wish to manage their emails offline or who don’t require constant synchronization across
multiple devices.
POP Workflow
Connecting to the Server: The email client opens a connection to the mail server, and the server
responds with a greeting. This initial connection is straightforward and establishes the communication
channel between the client and server.
Authentication: After establishing the connection, the client sends a username and password to the
server for authentication. If the credentials match the server’s records, the client is granted access to
the user’s mailbox.
Retrieving Emails: Once authenticated, the client can issue commands to retrieve emails. Messages
are downloaded from the server to the client’s local storage. By default, POP downloads the entire
email, including any attachments, allowing the user to view it offline.
Deleting Messages: In a traditional POP setup, once an email is downloaded, it’s deleted from the
server, although many clients today offer an option to leave copies on the server. This deletion is part
of the protocol’s original design, aiming to free up server space and minimize the time messages
spend on the server.
Ending the Session: After downloading the emails, the client sends a command to close the
connection, and the session ends. The next time the client connects, it will only retrieve any new
messages that arrived since the last session.
POP Commands and Response Codes
POP is a simple protocol, with a limited set of commands and response codes that guide the retrieval
process.
USER: Specifies the username for authentication.
PASS: Provides the password for authentication.
STAT: Returns the number of messages and their total size in the user’s mailbox.
LIST: Lists each message and its unique identifier, allowing clients to manage specific emails.
RETR: Retrieves a specific message by its unique identifier.
DELE: Marks a message for deletion from the server.
QUIT: Ends the session and applies any deletions specified during the session.
Response codes indicate the server’s status or if an error occurs:
+OK: Indicates that the previous command was successful.
-ERR: Indicates an error, such as a failed login or attempt to retrieve a non-existent message.
Secure POP (POP3S)
For secure email retrieval, POP can operate over SSL/TLS encryption, known as POP3S, using port
995. This secure version protects login credentials and the data transferred between the client and
server, preventing unauthorized access to sensitive information.
Limitations of POP
While POP is straightforward and effective for downloading emails, it has limitations:
No Synchronization: Emails aren’t synchronized across devices; changes made on one device won’t
reflect on others.
Limited Server Storage Management: POP doesn’t support advanced server-side management options,
such as creating folders or searching.
Deletes Emails by Default: Since messages are deleted from the server by default, users who wish to
keep emails accessible online or on other devices must manually adjust settings to retain copies on the
server.
POP is a protocol designed for retrieving emails from a server to a local device, enabling users to
manage emails offline. It operates with a simple command set and minimal resource requirements,
making it ideal for single-device usage without the need for constant synchronization. However, as
email needs have evolved, the lack of syncing and management features in POP have led to IMAP
becoming more popular for multi-device access. Despite these limitations, POP remains a practical
choice for users who prefer to download and store their emails locally.
3.9 IMAP :-
IMAP, or Internet Message Access Protocol, is a protocol in network programming used for retrieving
and managing email messages on a remote server. Unlike POP (Post Office Protocol), which primarily
downloads emails to a device and often deletes them from the server, IMAP is designed for syncing
emails across multiple devices. This protocol provides greater flexibility and control, allowing users
to access their emails from any device with changes synced in real-time. The current version, IMAP4,
is widely used by email clients and services.
IMAP uses a client-server model and typically operates on port 143 for unencrypted connections or
port 993 for secure, encrypted connections (IMAPS). When a user connects to their email account
through an IMAP client, such as Outlook, Gmail, or Apple Mail, the client communicates with the
email server to display email folders, message lists, and specific message content as requested.
IMAP’s design allows users to interact with their emails directly on the server, which supports real-
time syncing, folder management, and other features across all connected devices.
Features of IMAP :-
IMAP is designed with flexibility and accessibility in mind, offering several features that make it ideal
for modern, multi-device email management:
Real-Time Synchronization: IMAP synchronizes changes in real-time between the client and the
server. When a user reads, deletes, or organizes emails on one device, these changes reflect
immediately on the server and any other devices connected to the same account. This makes IMAP
suitable for users who need to manage their emails across multiple devices.
Folder Support and Organization: IMAP allows users to create, delete, and manage folders directly on
the server. Users can categorize emails into folders, which are visible and accessible from any
connected device.
Partial Downloading: IMAP supports downloading only the headers (such as the subject and sender)
of emails first, allowing the client to show a list of messages without downloading the entire content.
The body and attachments of a message are downloaded only when the user requests them, which
saves bandwidth and speeds up the loading process.
Multiple Clients Access: Since IMAP retains emails on the server, multiple clients or devices can
access the same email account concurrently without causing conflicts. Each client can connect to the
server independently, and any changes made on one device are synchronized across all others.
Message Flagging and Status Tracking: IMAP allows users to mark messages with different statuses
(such as "read," "unread," "flagged," or "replied"). These statuses are stored on the server, ensuring
that message flags and statuses remain consistent across all devices.
IMAP Workflow
Connecting to the Server: When a user opens an email client, the client establishes a connection with
the IMAP server. Once connected, the server responds with a greeting, indicating that the session is
ready to begin.
Authentication: The email client authenticates by sending the username and password to the server.
Upon successful authentication, the server grants access to the user's mailbox.
Listing Folders and Messages: After authentication, the client sends commands to view available
folders (such as Inbox, Sent, Trash) and retrieves message headers. This allows the user to browse
through emails without downloading them fully.
Fetching Email Content: When the user opens an email, the client requests the full content, including
the body and any attachments. This data is downloaded temporarily for viewing but remains stored on
the server unless explicitly moved or deleted.
Making Changes and Synchronizing: Any changes, such as marking emails as read, deleting, moving
them to folders, or flagging them, are synchronized to the server immediately. This real-time syncing
ensures that the user’s mailbox status remains consistent across all devices.
Ending the Session: When the user closes the email client or logs out, the client sends a command to
end the session, and the server closes the connection.
3.10 SSH and Telnet :-
SSH, or Secure Shell, is a network protocol used for securely accessing and managing remote
computers over a network. In network programming, SSH provides a way to remotely log into
systems, execute commands, and manage network devices, all while maintaining high security
through encryption. This protocol was created as a secure alternative to older protocols like Telnet,
which transmit data in plaintext and are vulnerable to interception.
Key Features of SSH in Network Programming
Encryption: SSH encrypts all data transmitted between the client and the server, including login
credentials and commands. This ensures data privacy and prevents unauthorized access.
Authentication: SSH supports secure authentication methods, including:
Password-based Authentication: Users can log in with a username and password, with data encrypted
in transit.
Key-based Authentication: Users authenticate using cryptographic key pairs, enhancing security by
eliminating the need for passwords.
Command Execution: SSH allows users to execute commands on remote systems as if they were
physically present. This makes it ideal for remote administration, troubleshooting, and managing
network resources.
Port Forwarding and Tunneling: SSH can securely tunnel network connections, allowing users to
access other services through encrypted channels. Port forwarding is useful for securely accessing
services that are otherwise only accessible on a local network.
File Transfer: SSH supports secure file transfers using protocols like SCP (Secure Copy Protocol) and
SFTP (Secure File Transfer Protocol), which allow files to be transferred over SSH's secure
connection.
Telnet :-
Telnet is a network protocol used for connecting to and managing remote systems over a network,
allowing users to remotely access and control a computer as if they were physically present. Created
in the early days of network programming, Telnet operates over port 23 by default and provides a text-
based interface for sending commands to a remote machine. However, due to its lack of security
features, Telnet has largely been replaced by more secure protocols like SSH (Secure Shell) in modern
network environments.
Use Cases and Modern Replacements
Telnet was initially popular for remote server administration and configuring network devices, as it
allows direct command-line access to the server. However, due to security concerns, Telnet is now
rarely used in production environments, except in highly controlled, private, or testing networks
where security risks are minimized.
Today, SSH (Secure Shell) is the preferred alternative to Telnet, offering encryption, strong
authentication, and data integrity checks, which make it secure for managing systems over public or
private networks. Telnet, while an important protocol in network history, has become obsolete in most
network programming practices where security is a priority.

3.11 FTP, RPC :-


FTP, or File Transfer Protocol, is a standard network protocol used for transferring files between
computers over a TCP/IP network, like the internet. It allows a client (user) to connect to an FTP
server to upload, download, delete, or manage files on the server. FTP operates over port 21 for
command control and, by default, uses a separate data channel for transferring files.

How FTP Works


FTP follows a client-server model, where a client program initiates a connection to an FTP server and
issues commands to manage files. The client can access, upload, or download files stored on the
server, making FTP useful for file sharing, backups, and remote data management.
Connection Establishment: The client connects to the FTP server using port 21, where the server
listens for incoming FTP requests.
Authentication: FTP can require a username and password for authentication. However, traditional
FTP does not encrypt this information, so login credentials and files are transmitted in plaintext,
making FTP vulnerable to interception.
Data Channels: FTP uses two separate channels:
Control Channel: Used on port 21 to send commands (such as login or file operations) between the
client and server.
Data Channel: A separate channel used to transfer files. FTP can use either active or passive mode to
establish this data channel.
Active Mode: The client opens a port, and the server connects to it for data transfer.
Passive Mode: The server opens a port, and the client connects to it, which is more firewall-friendly.
File Transfer Operations: FTP clients allow users to list files, download, upload, delete, rename, and
move files on the remote server. Commands for these actions are sent over the control channel, while
the actual data transfer happens over the data channel.

Features :
• No Encryption
• Reliability for Large Transfers
• Directory Operations
• Secure Alternatives to FTP
• FTPS (FTP Secure
• SFTP (SSH File Transfer Protocol
Common Use Cases of FTP in Network Programming
Website Management: FTP is used to upload and manage files on web servers.
Data Backups and Archiving: FTP is commonly used for transferring large datasets between systems
or storing data backups.
Controlled File Sharing: Organizations use FTP for file sharing within controlled, secure networks.
FTP is a foundational protocol for file transfer in network programming but has largely been replaced
by its secure alternatives for handling sensitive data.
RPC :-
RPC, or Remote Procedure Call, is a protocol in network programming that allows a program to
request a service or execute code on a remote server or another machine in a network, as if it were a
local function call. RPC simplifies distributed computing by hiding the complexities of network
communication, enabling developers to invoke remote procedures just like local ones.
Advantages of RPC
Abstraction of Network Complexity: RPC abstracts the details of the network, allowing developers to
invoke remote functions as if they were local.
Code Reusability: Functions or services on one machine can be used by multiple clients without
needing to duplicate code.
Simplifies Distributed Applications: RPC enables distributed computing, where different parts of an
application can run on different machines, allowing for load distribution and [Link] is a
foundational protocol in network programming, essential for building scalable, distributed
applications that interact seamlessly across networks.
Unit-IV: Domain Name System & Socket Names [10L] Max Marks: 20
4.1 Sockets and Hostnames :
Socket: A way for computers to talk to each other over a network. Think of it like a phone line that
connects two devices.
Hostname: A human-friendly name for a computer on a network. Instead of remembering a long
number (IP address), you use names like "[Link]".
IP Address: The unique number assigned to each device on a network. It’s like a home address for
computers.
How They Work Together:
When you type a hostname in your web browser, it gets translated to an IP address using a service
called DNS (Domain Name System).
Your computer uses this IP address to create a socket connection to the server.
Types of Sockets:
TCP Socket: Reliable connection; ensures data is sent and received correctly (like a phone call).
UDP Socket: Faster, but less reliable; doesn’t guarantee delivery (like sending a postcard).
Example:
You enter "[Link]" in your browser.
Your device finds the IP address for Google.
It creates a TCP socket to connect to Google’s server and start exchanging data.
Importance:
Sockets allow different applications (like browsers and servers) to communicate.
Hostnames make it easier for people to access websites without memorizing numbers.
4.2 Five Socket Coordinates:
Socket Coordinate: Represents where a connection is made between two devices. Think of it as a
specific point where they communicate.
Local IP Address: The unique address of your device on your local network. It’s like your home
address within a neighborhood.
Local Port Number: A specific channel on your device for sending and receiving data. Imagine it as a
door that allows information to enter and exit.
Remote IP Address: The address of the device you’re connecting to, like a friend's home address.
Remote Port Number: The channel on the remote device you’re connecting to. It’s like the specific
door your message will go through.
Example: If you’re using a web browser:
Local IP Address: Your computer’s address (e.g., [Link]).
Local Port Number: A number chosen by your computer (e.g., 54321).
Remote IP Address: The server you want to connect to (e.g., [Link]).
Remote Port Number: The server’s port for web traffic (usually 80 for HTTP).
Summary: These five coordinates help establish a connection between your device and another
device, ensuring data can flow smoothly between them.
4.3 IPv6 :
IPv6, or Internet Protocol version 6, is the most recent version of the Internet Protocol designed to
replace IPv4, which has been the foundation of internet addressing since the early days of the internet.
With the rapid growth of the internet and the increasing number of devices connected to it, IPv4's
limitations in address space became apparent.
IPv6 addresses this issue by providing a vastly larger address space. While IPv4 uses 32-bit addresses,
allowing for approximately 4.3 billion unique addresses, IPv6 uses 128-bit addresses. This means
IPv6 can support about 340 undecillion (3.4 x 10^38) unique addresses—more than enough for the
foreseeable future.
IPv6 addresses are written in hexadecimal format, separated by colons. For example, an IPv6 address
looks like this: 2001:0db8:85a3:0000:0000:8a2e:0370:7334. This notation not only allows for a much
larger number of addresses but also includes features like better support for auto-configuration and
improved routing efficiency.
One significant advantage of IPv6 is its ability to simplify network configuration and improve
security. It includes built-in IPsec support, which helps in securing internet communications, making
it easier to create secure networks.
As more devices connect to the internet, from smartphones to smart home devices, the need for a
more expansive addressing scheme becomes crucial. Transitioning from IPv4 to IPv6 is ongoing, with
many networks supporting both protocols to ensure compatibility.
IPv6 is a crucial advancement in internet technology that addresses the limitations of IPv4 by
providing a vast address space, enhanced security features, and improved connectivity for the growing
number of internet-enabled devices.
4.4 Modern Address Resolution :
Modern address resolution in network programming refers to the techniques and protocols used to
map human-friendly domain names to their corresponding IP addresses, enabling devices to
communicate effectively over a network. The most widely used method for this purpose is the
Domain Name System (DNS).
When a user types a website's name, like "[Link]," into a browser, the device must first resolve
this name into an IP address. This process begins with the browser querying the DNS resolver,
typically provided by the user's Internet Service Provider (ISP). The resolver checks its cache for the
requested IP address. If the address is not cached, the resolver initiates a series of queries across the
DNS hierarchy, starting from the root servers down to the authoritative name servers that hold the
actual records for the domain.
In modern networks, there are additional enhancements to address resolution. For instance, the
introduction of DNS over HTTPS (DoH) and DNS over TLS (DoT) provides privacy and security by
encrypting DNS queries, making it harder for third parties to snoop on users’ browsing activities.
Another important aspect is the use of caching mechanisms. Once an IP address is resolved, it is
stored temporarily, reducing the need for repeated queries and speeding up the overall resolution
process. This caching can occur at various levels, including the browser, the operating system, and the
DNS resolver.
Additionally, modern address resolution also incorporates techniques such as load balancing and
failover strategies. These allow multiple IP addresses to be associated with a single domain name,
directing traffic to different servers based on various criteria, like server health or geographical
location.
modern address resolution in network programming is an essential component that ensures smooth
communication over the internet. By efficiently mapping domain names to IP addresses and
incorporating advanced security measures and caching strategies, it enhances user experience and
optimizes network performance.
4.5 Bind Your Server to a Port Using getaddrinfo() :
Binding a server to a port is a crucial step in network programming, allowing it to listen for incoming
connections. The getaddrinfo() function simplifies this process by providing a way to translate
human-readable hostnames and service names into a structure that contains the necessary information
for creating a socket.
When you want to bind your server, you typically start by using getaddrinfo() to obtain a list of
potential socket addresses. This function takes three key parameters: the hostname (or NULL for local
binding), the service name (like a port number), and a set of hints that specify the type of socket you
want (e.g., stream or datagram). It returns a linked list of addrinfo structures, each containing
information about a possible address.
Once you have this list, you can iterate through it to create a socket and bind it to the desired address.
You begin by calling the socket() function, which creates a socket using the address family and socket
type specified in the addrinfo structure. If the socket creation is successful, you can then use the bind()
function to associate the socket with a specific port and IP address.
The bind() function takes three arguments: the socket descriptor, a pointer to the sockaddr structure
(which is derived from the addrinfo structure), and the size of the address structure. If bind() returns
zero, it indicates success, and your server is now bound to the specified port, ready to listen for
incoming connections.
If you encounter an error during this process, such as the port already being in use, you can handle it
appropriately by either trying another port or exiting the application.
using getaddrinfo() streamlines the process of binding a server to a port by providing a unified
interface for address resolution. This function enables you to easily manage different address families
and protocols, making your server code more portable and robust. By following this method, you
ensure that your server can efficiently accept incoming connections on the desired port, facilitating
smooth communication in your network application.
4.7 To connect to a service:
Connecting to a service in network programming involves several essential steps that enable a client
to establish a communication channel with a server. This process typically utilizes the socket API,
which provides the necessary functions to create sockets, connect to servers, and manage data
transmission.
First, you begin by creating a socket using the socket() function. This function requires specifying the
address family (such as IPv4 or IPv6) and the socket type (commonly TCP or UDP). Once the socket
is created successfully, you can proceed to prepare for the connection.
Next, you need to resolve the server's hostname and port number into an IP address. This is where the
getaddrinfo() function becomes invaluable. By providing the hostname and service name,
getaddrinfo() returns a linked list of addrinfo structures that contain all the necessary information for
establishing a connection. This step ensures compatibility with various address families and protocols,
making your client code more flexible.
With the resolved address information in hand, you iterate through the list of addrinfo structures. For
each address, you attempt to connect using the connect() function. This function requires the socket
descriptor and a pointer to the sockaddr structure obtained from the addrinfo. If the connection is
successful, the client can now communicate with the server. If an error occurs, you can try the next
address in the list until a successful connection is made or the list is exhausted.
After establishing the connection, you can use functions like send() and recv() to transmit and receive
data over the socket. This allows you to interact with the server, whether by sending requests or
processing responses.
Finally, once the communication is complete, it is important to close the socket using the close()
function to free up system resources.
connecting to a service in network programming involves creating a socket, resolving the server's
address using getaddrinfo(), attempting to connect with connect(), and managing data transmission
with send() and recv(). By following these steps, you enable effective communication between clients
and servers, facilitating various networked applications.

4.8 use getaddrinfo () :


The getaddrinfo() function is a crucial component in network programming, primarily used for
resolving hostnames and service names into a list of usable socket addresses. This function simplifies
the process of creating sockets by abstracting the complexities associated with different address
families and protocols, making it easier to write portable and efficient networking code.

When using getaddrinfo(), you typically begin by defining the parameters it requires: the hostname
you want to connect to (or NULL for the local machine), the service name (like a port number or a
protocol), and a set of hints that specify the desired socket type and address family. The function then
returns a linked list of addrinfo structures, each containing potential addresses to connect to.

For example, consider a simple TCP client that connects to a server. The client might use
getaddrinfo() as follows:
import socket
def main():
# Set up the address information
hints = [Link]('[Link]', 80, socket.AF_UNSPEC, socket.SOCK_STREAM)
sockfd = None
for result in hints:
af, socktype, proto, canonname, sockaddr = result
try:
# Create a socket with the given address family, socket type, and protocol
sockfd = [Link](af, socktype, proto)
# Connect to the server
[Link](sockaddr)
print("Connected successfully.")
break # Exit the loop on successful connection
except [Link] as e:
print(f"Socket error: {e}")
if sockfd:
[Link]()
continue # Try the next address
if sockfd:
# Use the socket (e.g., send and receive data)
# For example, you could send an HTTP GET request:
# [Link](b"GET / HTTP/1.1\r\nHost: [Link]\r\n\r\n")
[Link]() # Close the socket
print("Socket closed.")

if __name__ == "__main__":
main()In this example, the program first initializes a hints structure to specify the desired socket
type and address family. It then calls getaddrinfo() to resolve the hostname "[Link]" on port
"80". The resulting linked list of addresses is iterated over, attempting to create a socket and connect
to each address until a successful connection is established or all options are exhausted.
By using getaddrinfo(), the program can easily handle both IPv4 and IPv6 addresses, making it more
robust and versatile. This function eliminates the need for hardcoding IP addresses and simplifies
error handling, leading to cleaner and more maintainable code.
getaddrinfo() plays a vital role in network programming by facilitating address resolution, enabling
developers to write code that can seamlessly connect to services regardless of the underlying network
protocol.

4.9 Getting a Canonical Hostname with getaddrinfo() Other getaddrinfo() Flags :


In Python, the socket module provides a convenient way to work with networking functionalities,
including the use of getaddrinfo(). This function is essential for resolving hostnames and obtaining
their associated IP addresses, as well as for retrieving the canonical hostname. Utilizing getaddrinfo()
in Python allows developers to handle various network protocols seamlessly and efficiently.
To retrieve the canonical hostname, you would use the [Link]() function. This function
takes several parameters, including the hostname, service, and optional flags. The result is a list of
tuples, each containing information about a potential socket address. The first element of each tuple is
the family of the address, the second is the socket type, and the third is the protocol. The fourth
element is a tuple with the IP address and port, and the fifth element contains the canonical name,
which can be accessed easily.
For example, here’s how you can use getaddrinfo() to connect to a server and retrieve its canonical
hostname:
import socket
hostname = '[Link]'
service = 'http'
# Get address information
addr_info = [Link](hostname, service)
# Print the canonical hostname
if addr_info:
canonical_name = addr_info[0][0] # The first entry typically has the canonical name
print(f"Canonical hostname: {canonical_name}")
else:
print("No address info found.")
In this example, the code retrieves the address information for "[Link]" on port 80
(HTTP). The canonical name can typically be accessed from the first entry in the list returned by
getaddrinfo(), although it's important to note that this behavior can depend on how the underlying
DNS is set up.
Other getaddrinfo() Flags in Python
In addition to resolving hostnames, getaddrinfo() accepts flags that modify its behavior, allowing for
more control over the address resolution process. While Python's getaddrinfo() does not use flags in
the same way as the C implementation, you can still specify certain options to customize the behavior:
AF_INET / AF_INET6: You can specify the address family explicitly when calling getaddrinfo(). For
example, socket.AF_INET for IPv4 or socket.AF_INET6 for IPv6.
SOCK_STREAM / SOCK_DGRAM: You can also specify the socket type. Use
socket.SOCK_STREAM for TCP connections or socket.SOCK_DGRAM for UDP connections.
AI_PASSIVE: While Python does not use the same flag constants as C, you can still implement server
sockets by passing None as the hostname when you want to bind to all interfaces. This mimics the
behavior of AI_PASSIVE.
Here’s an example demonstrating how to use these parameters in a more controlled manner:
import socket
hostname = '[Link]'
service = 'http'
# Get address information with specific family and type
addr_info = [Link](hostname, service, socket.AF_INET, socket.SOCK_STREAM)
# Print the canonical hostname and address details
for family, socktype, proto, canonname, sockaddr in addr_info:
print(f"Canonical Name: {canonname}")
print(f"Address: {sockaddr[0]}:{sockaddr[1]}")
In this case, you specify AF_INET and SOCK_STREAM to indicate that you want to work with IPv4
and TCP sockets. The loop iterates through the list of addresses, printing out the canonical name and
address details for each entry.
using getaddrinfo() in Python is an effective way to resolve hostnames and obtain their canonical
names, enhancing the clarity of network interactions. By utilizing specific address families and socket
types, developers can create robust and flexible networking applications that cater to various protocols
and configurations.

4.10 PriITive Name Service Routines :


Primitive name service routines in Python primarily involve functions and methods provided by the
socket module that facilitate name resolution and networking tasks. These routines are essential for
converting human-readable hostnames into IP addresses, enabling seamless communication between
devices on a network.
The most commonly used primitive name service routines in Python include gethostbyname(),
gethostbyaddr(), and getaddrinfo(). Each of these functions serves a specific purpose in the domain of
network programming.
gethostbyname(): This function is used to resolve a hostname into an IPv4 address. It takes a single
argument—the hostname—and returns a string representation of the corresponding IP address. This
routine is straightforward and suitable for applications that only require IPv4 support. For example:
import socket

hostname = '[Link]'
try:
ip_address = [Link](hostname)
print(f"IP address of {hostname}: {ip_address}")
except [Link]:
print(f"Could not resolve hostname: {hostname}")
In this example, the hostname "[Link]" is resolved to its IP address. If the resolution fails,
a gaierror is raised, allowing for error handling.
gethostbyaddr(): This function performs the inverse operation of gethostbyname(). It takes an IP
address as an argument and returns a tuple containing the primary hostname associated with the
address, an alias list, and an IP address list. This routine is useful for looking up the hostname
corresponding to a known IP address:
ip_address = '[Link]' # Example IP address
try:
hostname, aliases, ip_addresses = [Link](ip_address)
print(f"Hostname: {hostname}")
print(f"Aliases: {aliases}")
print(f"IP Addresses: {ip_addresses}")
except [Link]:
print(f"Could not resolve IP address: {ip_address}")
Here, the IP address is resolved to its corresponding hostname, along with any aliases and associated
IP addresses. If the resolution fails, a herror is raised.
getaddrinfo(): This is the most versatile name resolution function in Python. It can handle both IPv4
and IPv6 addresses and provides more detailed information, including socket type and protocol.
getaddrinfo() returns a list of tuples, each containing various details about potential addresses. This
function is invaluable for applications that need to support multiple network protocols:
import socket
hostname = '[Link]'
service = 'http'
addr_info = [Link](hostname, service)
for family, socktype, proto, canonname, sockaddr in addr_info:
print(f"Address Family: {family}, Socket Type: {socktype}, "
f"Protocol: {proto}, Canonical Name: {canonname}, "
f"Socket Address: {sockaddr}")
In this example, getaddrinfo() resolves the hostname and service, returning a list of address
information. The output includes the address family, socket type, protocol, canonical name, and the
socket address for each entry.
Primitive name service routines in Python provide essential tools for hostname resolution and network
address management. Functions like gethostbyname(), gethostbyaddr(), and getaddrinfo() allow
developers to efficiently handle network communications, whether resolving hostnames to IP
addresses or vice versa. By leveraging these routines, applications can operate effectively across
different network protocols, enhancing their robustness and flexibility in diverse networking
environments.
4.11 Use getsockaddrQ :
the getsockname() method is part of the socket API and is used to retrieve the local address
information of a socket. This method is particularly useful for understanding which local address and
port a socket is bound to, especially in server applications or when you need to confirm the socket’s
configuration after creating a connection.
When you create a socket and bind it to a specific address and port, getsockname() allows you to
query that socket to obtain the actual address and port being used. This is helpful in various scenarios,
such as when your application might use a dynamically assigned port or when you need to verify the
local endpoint before starting communication.
How to Use getsockname()
To use getsockname(), you first create a socket, potentially bind it to an address and port, and then call
getsockname() on that socket. The method returns a tuple containing the IP address and the port
number currently assigned to the socket.
Here’s a detailed example to illustrate its usage:
import socket

# Create a TCP socket


sock = [Link](socket.AF_INET, socket.SOCK_STREAM)

# Bind the socket to a local address and port


server_address = ('localhost', 0) # Port 0 means the OS will choose an available port
[Link](server_address)

# Retrieve the local address and port using getsockname()


local_address = [Link]()
print(f"Socket is bound to: {local_address[0]} on port {local_address[1]}")

# Optionally, you can listen for incoming connections


[Link](5)
# The socket can now be used to accept connections
Explanation of the Code
Socket Creation: The socket is created using [Link](), specifying the address family (AF_INET
for IPv4) and the socket type (SOCK_STREAM for TCP).
Binding: The socket is bound to the address ('localhost', 0). By specifying port 0, the operating system
automatically selects an available port for the socket, which is particularly useful for testing or when
the specific port number is not crucial.
Getting Local Address: After binding, getsockname() is called on the socket object. This retrieves the
actual local address and port number that the socket is bound to. The returned tuple is unpacked to
print the IP address and port.
Listening for Connections: The socket is then set to listen for incoming connections, ready to accept
client requests.
The getsockname() method in Python provides an effective way to query the local address and port of
a socket. This is especially beneficial in server applications where dynamically assigned ports are
used, allowing developers to confirm the configuration of their sockets before initiating
communication. By utilizing getsockname(), applications can enhance their robustness and flexibility,
ensuring they operate correctly across different networking scenarios.

4.12 DNS Protocol, Why Shouldn't Use Raw DNS? :


The Domain Name System (DNS) is a fundamental component of the internet, serving as the
directory service that translates human-readable domain names (like [Link]) into IP
addresses that computers use to identify each other on the network. The DNS protocol operates
through a series of queries and responses, facilitating the resolution of domain names into IP
addresses, enabling seamless communication across the internet.

While it is possible to interact with DNS directly by crafting raw DNS queries and parsing responses,
doing so is generally not advisable for most applications, especially in Python. This is due to several
significant challenges and potential pitfalls associated with working with raw DNS.

Complexity and Low-Level Details


Interacting with DNS at a low level involves understanding and implementing the DNS protocol
specification, which can be quite complex. You need to manually construct DNS query packets,
handle various record types (like A, AAAA, MX, etc.), and parse the responses. This low-level
handling introduces a significant risk of errors and can make your code difficult to maintain.

In contrast, high-level libraries in Python, such as socket and dnspython, abstract away these
complexities. For example, using dnspython, you can perform DNS lookups with just a few lines of
code, allowing you to focus on the application logic rather than the intricacies of the DNS protocol.

Security Risks
Using raw DNS queries exposes your application to various security risks, such as DNS spoofing and
man-in-the-middle attacks. These attacks can compromise the integrity of the data being retrieved,
potentially leading users to malicious sites or intercepting sensitive information. High-level libraries
often include built-in security features, such as DNSSEC support, which help to mitigate these risks
by ensuring the authenticity and integrity of DNS responses.

Performance Considerations
Another reason to avoid raw DNS is performance. Implementing caching mechanisms for DNS
responses can significantly enhance performance, as DNS lookups can be slow if performed
repeatedly. High-level libraries typically include caching features out of the box, improving efficiency
and reducing latency in applications that perform frequent DNS queries.

Example of Using a High-Level Library


Instead of using raw DNS, you can utilize a library like dnspython for easy and efficient DNS queries.
Here’s an example:
import [Link]

# Perform a DNS lookup for the A record of a domain


domain = '[Link]'
try:
answers = [Link](domain, 'A')
for rdata in answers:
print(f'IP address: {rdata}')
except Exception as e:
print(f'Error resolving {domain}: {e}')
In this example, dnspython handles the complexities of DNS queries, allowing you to easily retrieve
the IP addresses associated with a domain. This approach minimizes the risk of errors and enhances
security and performance.
While the DNS protocol is essential for the functioning of the internet, directly using raw DNS
queries in Python is generally discouraged due to the complexity, security risks, and performance
challenges associated with it. Leveraging high-level libraries like dnspython provides a safer, more
efficient, and easier way to perform DNS lookups, allowing developers to focus on building robust
applications without getting bogged down by the intricacies of the DNS protocol.

4.13 Using Python to do a DNS query, Getting Mail Domains Resolved. :


performing DNS queries to resolve mail domains is a straightforward task, particularly with the help
of high-level libraries like dnspython. This library allows developers to easily interact with the
Domain Name System (DNS) to retrieve various types of records, including those related to email
services, such as MX (Mail Exchange) records.

MX records are essential for email delivery as they specify the mail servers responsible for receiving
email on behalf of a domain. By querying these records, you can determine which servers are set up to
handle incoming email for a specific domain.

Installing dnspython
Before you can use dnspython, you need to install it. This can be done easily via pip:

pip install dnspython


Performing a DNS Query for MX Records
To perform a DNS query for MX records in Python, you will follow these steps:

Import the [Link] module from dnspython.


Use the resolve() function to query the MX records for a given domain.
Handle any potential exceptions that may arise during the lookup process.
Here’s a detailed example to illustrate how to get mail domains resolved using dnspython:

import [Link]

def get_mail_domains(domain):
try:
# Query the MX records for the domain
mx_records = [Link](domain, 'MX')
print(f'MX records for {domain}:')

# Iterate through the MX records and print the mail servers


for mx in mx_records:
print(f'Priority: {[Link]}, Mail Server: {[Link].to_text()}')
except [Link]:
print(f'No MX records found for {domain}.')
except [Link]:
print(f'The domain {domain} does not exist.')
except Exception as e:
print(f'An error occurred: {e}')
# Example usage
get_mail_domains('[Link]')
Explanation of the Code
Importing the Library: The code begins by importing the [Link] module, which provides the
necessary functions for DNS queries.
Defining the Function: The function get_mail_domains(domain) takes a domain name as its
parameter.
Querying MX Records: Inside the function, [Link](domain, 'MX') is called to fetch the
MX records associated with the specified domain.
Iterating Over Records: The returned MX records are iterated over, and for each record,

Unit-V Mobile Ad-Hoc Network [10L] Max Marks: 15


5.1 Overview of Wireless Ad-Hoc Network- MANET and WSN :-
Wireless Ad-Hoc Networks are a type of wireless network that operates without a centralized
infrastructure or fixed access points. In these networks, each device (or "node") can communicate
directly with others nearby, enabling dynamic connectivity. Two common types of Wireless Ad-Hoc
Networks are Mobile Ad-Hoc Networks (MANETs) and Wireless Sensor Networks (WSNs). Let’s
break down each of these.
1. Mobile Ad-Hoc Networks (MANET)
MANETs consist of mobile devices (such as smartphones, laptops, or tablets) that can connect and
communicate with each other directly. Because there is no fixed infrastructure, each device in a
MANET acts as both a host (a device using the network) and a router (a device that helps forward
data for others). This setup allows for a decentralized network that can adapt to changes, as devices
frequently move around or enter and leave the network.
In MANETs, network topology (the layout of connections between devices) constantly changes as
devices move, which can make routing challenging. Protocols like AODV (Ad hoc On-Demand
Distance Vector) and DSR (Dynamic Source Routing) are used to manage data transmission and
ensure messages reach their destination, even when nodes are constantly changing position.
MANETs are commonly used in scenarios where traditional networks might be unavailable or
impractical, such as disaster recovery operations, military communication in remote areas, and
temporary events where quick network setup is required.
2. Wireless Sensor Networks (WSN)
Wireless Sensor Networks (WSNs) are networks of sensor devices spread across a specific area to
monitor and gather data. Each sensor node in a WSN is typically equipped with a sensor to collect
data, a small processor to process information, and a radio module for communication. These nodes
can measure environmental parameters like temperature, humidity, light levels, and sound.
WSNs are often deployed in remote or inaccessible areas, like forests for wildlife monitoring,
industrial sites for machinery status, or in cities for smart traffic management. The collected data from
each sensor node is typically sent to a central base station or gateway, where it is aggregated and
analyzed. In many WSNs, nodes are designed to use minimal power, as they are usually battery-
operated and may need to function for extended periods without human intervention.
WSNs often use specialized protocols like Zigbee, Bluetooth Low Energy (BLE), or custom low-
power protocols to ensure data reliability while conserving energy. Nodes in a WSN may also use
routing techniques like clustering, where some nodes act as cluster heads to reduce the number of
direct transmissions and thus save energy.
Network Programming in MANET and WSN
Network programming for MANETs and WSNs involves designing and implementing protocols and
applications that allow these networks to operate efficiently. Developers must account for factors like
limited battery life, varying network topology, and the need for reliable data transfer even with
frequent disconnections. Protocols are often optimized for energy efficiency in WSNs and dynamic
adaptability in MANETs.
In both MANETs and WSNs, the goal of network programming is to enable effective communication
and data management, even in challenging and variable network conditions. This field continues to
evolve as new applications emerge, like the Internet of Things (IoT), where WSNs and MANETs play
critical roles in connecting devices and collecting data across diverse environments.
5.2 Routing in Ad-Hoc Network :-
Routing in an Ad-Hoc Network is about figuring out the best paths for data to travel between devices,
or “nodes,” without relying on a fixed infrastructure, such as routers or central servers. Each device in
the network can act as both a sender and a relay point (or router) for data, allowing nodes to connect
and communicate directly or through other nodes.
Because the devices in an Ad-Hoc Network are often mobile and the network layout (called topology)
changes frequently, routing can be challenging. Protocols, or sets of rules, are needed to help devices
discover routes and make sure data reliably reaches its destination, even as nodes move in and out of
range.
There are two main types of routing protocols in Ad-Hoc Networks: Proactive and Reactive.
Proactive Routing
In proactive routing, also known as table-driven routing, each node maintains a routing table
containing the routes to other nodes within the network. These tables are constantly updated as the
network topology changes. This approach means that nodes always have a route ready when they need
to send data.
However, keeping track of all possible routes requires continuous updates, which can use up a lot of
bandwidth and energy, especially in networks where devices frequently move around. Proactive
routing is generally suited to networks where the topology doesn’t change too much.
Reactive Routing
In contrast, reactive routing, or on-demand routing, only establishes routes when they are needed.
When a node wants to send data, it initiates a route discovery process to find the best path to the
destination. Once a route is found, it is temporarily used for the data transfer. The route only stays
active while it’s in use; if it’s not needed, it’s dropped.
This approach saves bandwidth and power because routes are only created when necessary, which
makes it better suited for networks with high mobility. However, there can be a delay in setting up
routes since the route discovery process takes time.
Routing Protocols
Some popular routing protocols used in Ad-Hoc Networks include AODV (Ad hoc On-Demand
Distance Vector) and DSR (Dynamic Source Routing), both of which are reactive. AODV creates
routes only when needed and uses route requests and replies to establish connections, while DSR
builds a complete path from source to destination and uses this for data transmission.
In both proactive and reactive routing, the goal is to find a balance between speed, efficiency, and
reliability, ensuring data reaches its destination even if the network layout is constantly shifting. This
ability to adapt makes routing in Ad-Hoc Networks an essential area of network programming,
especially for situations like emergency response, military operations, and IoT applications, where a
fixed infrastructure isn’t available or feasible.
5.3 Routing Protocols for Ad-Hoc Wireless Network (Proactive, Reactive and Hybrid)
Clustering Protocol :-
In Ad-Hoc Wireless Networks, routing protocols are essential to ensure data is sent reliably from one
device (node) to another without a fixed infrastructure. These networks are dynamic, so protocols are
designed to find the best paths, even as devices move or enter and leave the network. Routing
protocols in Ad-Hoc Networks are generally classified into three main types: Proactive, Reactive, and
Hybrid. There is also a special approach called Clustering Protocols.
Proactive (Table-Driven) Routing Protocols
Proactive routing protocols continuously update and maintain routing tables with paths to every
possible destination in the network, even if no data needs to be sent immediately. Each node keeps a
list of the best routes, and these tables are updated regularly to reflect changes in network topology.
This approach ensures that routes are always available, which reduces delay when sending data.
However, the constant updates can consume a lot of bandwidth and power, especially in networks
with high mobility. Proactive protocols are more suitable for networks where devices do not move
often or where network stability is high. Examples of proactive protocols include OLSR (Optimized
Link State Routing) and DSDV (Destination-Sequenced Distance Vector).
Reactive (On-Demand) Routing Protocols
Reactive routing protocols, in contrast, only search for routes when they are needed. When a node
wants to send data, it initiates a route discovery process to find the best path. Once the data has been
transmitted, the route is discarded unless it’s used again soon afterward.
This approach saves energy and bandwidth because there are no continuous updates. However, it can
lead to delays, as routes need to be established before sending data. Reactive protocols are ideal for
networks with frequent changes, where it is not efficient to keep routing tables updated at all times.
Examples of reactive protocols include AODV (Ad hoc On-Demand Distance Vector) and DSR
(Dynamic Source Routing).
Hybrid Routing Protocols
Hybrid routing protocols combine the features of both proactive and reactive protocols. These
protocols divide the network into zones or clusters and apply different routing strategies within and
between these areas. For example, nodes within a particular zone may use proactive routing for quick
access to nearby devices, while nodes in different zones use reactive routing for data that needs to
travel farther distances.
This combined approach helps reduce the control overhead from proactive updates while still
providing faster access to nearby nodes. Hybrid protocols are designed to balance the advantages of
both proactive and reactive methods, making them efficient for larger networks with varying levels of
mobility. An example of a hybrid protocol is ZRP (Zone Routing Protocol).
Clustering Protocols
Clustering is a unique approach where the network is divided into clusters, and each cluster has a
designated leader or “cluster head.” Cluster heads are responsible for managing communication
within their clusters and for relaying data to other clusters. The cluster head handles the routing and
communication tasks for the nodes in its group, reducing the overall routing burden for each node.
In a clustered network, nodes communicate within their cluster more efficiently, and only a few nodes
need to handle inter-cluster communications, which reduces network congestion. Clustering protocols
are particularly useful for large networks, as they help organize the nodes into manageable groups and
conserve energy by limiting the number of nodes responsible for routing. Examples of clustering
protocols include LEACH (Low-Energy Adaptive Clustering Hierarchy) and HEED (Hybrid Energy-
Efficient Distributed Clustering).

Each type of routing protocol in Ad-Hoc Networks addresses different needs:


Proactive protocols keep routing information updated but require more bandwidth.
Reactive protocols find routes on-demand, reducing overhead but introducing delays.
Hybrid protocols blend the two for a balance of quick access and efficiency.
Clustering protocols organize nodes into groups to optimize large networks and save energy.
Together, these routing strategies help support efficient and reliable communication in dynamic Ad-
Hoc Networks, making them suitable for various applications, from disaster response to smart
environments.

You might also like