0% found this document useful (0 votes)
11 views28 pages

Unit 1

Unit 1 covers the fundamentals of networking, including the OSI model, TCP/IP architecture, and socket programming in Python. It explains key concepts such as client-server architecture, types of network connections, and addressing in computer networks. The unit also provides practical guidance on creating sockets and developing a simple chat program using Python.

Uploaded by

singh vijay
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)
11 views28 pages

Unit 1

Unit 1 covers the fundamentals of networking, including the OSI model, TCP/IP architecture, and socket programming in Python. It explains key concepts such as client-server architecture, types of network connections, and addressing in computer networks. The unit also provides practical guidance on creating sockets and developing a simple chat program using Python.

Uploaded by

singh vijay
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
You are on page 1/ 28

Unit 1: Network Connectivity with Python

Structure

1.0 Introduction
1. 1 Learning Outcomes
1.2 Basics of Networking
1.3 OSI Model and TCP/IP architectures
1.4 Addressing in ComputerNetworks
1.5 Transmission Control Protocol and User Datagram Protocol
1.6 Client-Server Architecture
1.7 Sockets
1.8 Socket Programming in Python
1.8.1 Creating a Socket
1.8.2 Server Socket Methods
1.8.3 Client Socket Methods
1.8.4 General socket Methods
1.8.5 Connecting with the Server
1.8.6 Creating a simple Server
1.8.7 Creating a simple Client
1.9 Let Us Sum Up
1.10 Check your progress: The key
1.0 Introduction

This unit aims to cover the basics of networking, addressing computer networks,

transport layer protocols, client-server architecture, basics of sockets, socket

programming in Python, and creating a simple chat program in Python using sockets.

1.1 Learning Outcomes

After having studied this unit, you will be able to:

2
 understand basics of networking, communication models, and addressing in

computer networks

 describe TCP and UDP transport layer protocols, the client-server architecture, and

the basics of sockets;

 explain the usage of sockets in Python & creating a small chat program using sockets

in Python.

1.2 Basics of Networking

In this section, we will discuss the conceptual framework of networking.

These are:

 Data communications: Data is exchanged between two devices using a transmission

medium.

 A data communication system has five components – message, sender, receiver,

transmission medium, and protocol.

 Protocol is a collection of rules or algorithms defining how two entities can

communicate across the network. It governs data communications. Examples of

protocols are TCP, UDP, IP, FTP, etc.

 Types of communication between two devices can be simplex, half-duplex, or full-

duplex.

o Simplex mode: Communication is unidirectional. Only one device can

transmit, and the other can only receive.

Example: one-way street.

3
Figure 1: Data flow in Simplex mode
o Half-duplex mode: Each device can transmit and receive data, but not

simultaneously. When one device transmits, the other device can only receive

it, and vice-versa. Example: walkie-talkies.

Figure 2: Data Flow in Half-duplex mode


o Full-duplex mode: Both devices can transmit and receive simultaneously.

Example: telephone.

Figure 3: Data flow in Full-duplex mode

 Network: It is a set of devices (often referred to as nodes) connected by

communication links, i.e., a network is two or more devices connected through links.

 Node: A node is any device capable of sending or receiving data generated by other

nodes on the network.

 Link: A communications pathway that transfers data from one device to another.

 There are two types of connections in which nodes can be connected to the same link

for communication to occur: point-to-point and multipoint.

4
o Point-to-point connection: It establishes a dedicated link between two devices

and reserves the link's capacity for transmission between the two devices.

Figure 4: Point-to-point connection


o Multipoint: More than two devices share the same link in this connection. The

link’s capacity is shared, either spatially or temporally.

Figure 5: Multipoint connection

 Physical Topology is the arrangement of nodes and links in a computer network. A

topology is of four types – mesh, star, bus, and ring.

Figure 6: Types of Physical Topology

o Mesh topology: A dedicated point-to-point link connects each device to the

( )
other. In a mesh topology, we need duplex-mode links. Every device

must have (𝑛 − 1) I/O ports connected to other 𝑛 − 1 stations.

5
Figure 7: Mesh topology
o Star topology: A specialized point-to-point link connects each device to a

central controller such as a hub. The devices do not have to be linked

together. Each device requires only one link and one I/O port to connect to

any number of devices.

Figure 86: Star topology


o Bus topology: A single lengthy cable is the network’s backbone, connecting

all devices. Hence, it is multipoint.

6
Figure 97: Bus topology
o Ring topology: Only the two devices on either side of the connection have a

dedicated point-to-point connection. Each device has a repeater, and when it

receives a signal intended for another device, the repeater regenerates the bits

and sends them along.

Figure 10: Ring topology

 There are two best-known network models – OSI (Open Systems Interconnection)

model, which defines a seven-layer network, and the internet model, also known as

TCP/IP model, which describes a five-layer network.

7
 Networks are of two types – Local Area Networks (LAN) and Wide Area Networks

(WAN).

 Local Area Networks (LAN): It connects the devices in a single office, building, or

campus and is usually privately owned. Its range is limited to a few kilometers and

only provides speeds of about 100 or 1000 Mbps.

 Wide Area Networks (WAN): It provides long-distance transmission of data like

image, audio, and video information over large geographic areas such as a country,

continent, or even the whole world.

 Metropolitan Area Networks (MAN): It has a size between that of a LAN and a

WAN. It usually covers a town or a city.

 Hostname: Each device in the network is associated with a unique system device

name.

Check Your Progress 1


Note: a) For writing answers, space is given below.
b) Check your answers with the one given at this unit's end.

i) How many I/O ports are needed by each device, and how many communication
links are required to connect 𝑛 devices in case of:
a) Mesh topology?
b) Star topology?
--------------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------------

-------------------------------------------------------------------------------------------------------

8
1.3 OSI model and TCP/IP architecture

The OSI model comprises seven layers –

1. Physical layer: It is responsible for moving individual bits from one hop to the next.

2. Data Link layer: the transmission of frames from one hop to the next is handled by

this layer. It ensures hop-to-hop (node-to-node) delivery.

3. Network layer: This layer sends individual packets from the source host to the

destination host. It ensures host-to-host delivery.

4. Transport layer: the delivery of the message from one process to another is handled

by this layer. It ensures end-to-end delivery or process-to-process delivery.

5. Session layer: this layer manages dialog control and synchronization.

6. Presentation layer: Translation, compression, and encryption are all performed by

this layer.

7. Application layer: This layer acts as a window via which users and application

processes can access network services.

The TCP/IP protocol suite comprises five layers – Physical, Data link, Network,

Transport, and Application. TCP/IP represents the three uppermost layers of the OSI

model (Session, Presentation, and Application) by a single layer termed the Application

layer.

1.4 Addressing in Computer Networks

Physical addresses, logical addresses, and port addresses are the three types of addresses

used on the Internet.

 Physical (MAC) address: It is the unique identifier of each host and is associated

with its Network Interface Card (NIC). It is composed of 48-bits (6 bytes). It is

9
usually written as 12 hexadecimal digits, and every byte, i.e., two hexadecimal digits,

is separated by a colon.

Example: 2C:54:91:88:C9:E3

 Logical address: It is the system's network address across the network. It can

uniquely define a host connected to the Internet. It is also known as an IP address. No

two publicly addressed and visible hosts on the Internet can have the same IP

address. IP addresses are of two types – IPv4 and IPv6.

An IPv4 address consists of 32-bits, represented using four octets, written

individually as decimal numbers, and separated using a period.

Example of IPv4 address: 192.168.0.5

An IPv6 address consists of 128-bits, represented as eight groups of four

hexadecimal digits, separated using colons, and each group represents 16 bits.

Example of IPv6 address: 2001:0db8:85a3:0000:0000:8a2e:0370:7334

 Port address: Today, computers are devices that can run multiple processes

simultaneously. So, the end objective of data communications is to deliver data to the

relevant process on the destination host. Hence, a port is a communication endpoint.

The data is transmitted to the correct target host using the physical and IP addresses

and then forwarded to the valid process executing on the destination system using the

port address. A port address is 16 bits in length, so we have 216 ports available. These

port addresses are divided into three categories:

Total port addresses – 65,536

Range of port addresses – 0 - 65,535

10
Table 1: Port Category and Ranges

Category Range

Well-known ports 0 - 1023

Registered ports 1024 - 49151

Private or dynamic ports 49152 - 65535

Table 2: Well-Known Ports

Port number Assignment


20 File Transfer Protocol (FTP)
23 Telnet
25 Simple Mail Transfer Protocol (SMTP)
53 Domain Name System (DNS)
80 Hypertext Transfer Protocol (HTTP)

 Socket address: A socket address is formed by combining an IP address and a port

number. The client socket address is used to identify the client process, whereas the

server socket address is used to determine the server process. The transport layer

requires a pair of socket addresses: one for the client and one for the server. The IP

header includes the client and server's IP addresses, whereas the TCP or UDP header

includes the port numbers.

Figure 11: socket Address

1.5 Transmission Control Protocol and User Datagram Protocol

11
Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are transport

layer protocols.

Characteristics of TCP are:

 It is a connection-oriented protocol.

 It is reliable as it guarantees the delivery of packets to the destination host.

 It provides error checking and flow control.

 It provides acknowledgment mechanisms.

 Sequenced delivery, i.e., order of packets, is preserved.

 Retransmission of lost packets is possible.

 It is slower than UDP.

 It does not support broadcasting.

 It is used by HTTP, FTP, SMTP, Telnet, etc.

Characteristics of UDP are:

 It is a connectionless protocol.

 It is unreliable as it does not guarantee the delivery of packets to the destination host.

 It only provides basic error checking using checksums.

 No acknowledgment is provided in the case of UDP.

 Packets can arrive out of order.

 No retransmission of lost packets is performed.

 It is faster than TCP.

 It supports broadcasting.

 It is used by DNS, VoIP, SNMP, etc.

12
Check Your Progress 2

Note: a) For writing answers, space is given below.


b) Check your answers with the one given at this unit's end.

i. Mention the port numbers assigned to the services of HTTP, SMTP, and Telnet.

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

ii. What is the difference between the session layer and presentation layer of the OSI

model?

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

iii. What is a socket address?

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

--------------------------------------------------------------------------------------------------

1.6 Client-Server Architecture

13
A client is the one who requests a service, while a server is the one who provides the

service. Client-server architecture is a computing approach in which the server hosts,

manages, and delivers most of the client’s resources and services. Because all requests

and services are delivered across a network, it is known as the networking computing

model or client-server network. Other systems are connected across a network, and

resources are shared among the various computers under the client-server architecture or

model. Client-server architecture is typically set up so that clients are located at

workstations or personal computers, and servers are located elsewhere on the network,

usually on more powerful machines.

Figure 12: Client-Server architecture

Examples of Client-Server architecture:

 Mail servers: They are used for sending and receiving emails;

 Web servers: They are used for hosting websites;

 File servers act as a centralized file location, and multiple users can access these files.

Components of a Client-Server architecture are:

14
 Workstations: They are called client computers. They are subordinate to servers and

request them to provide access to shared files and databases.

 Servers: Servers are high-performance computing machines that serve as centralized

storage and retrieval centers for network files, applications, and databases. They have

plenty of storage space and memory to handle several requests coming in from

different workstations at the same time.

 Networking devices: Networking devices are a medium that connects workstations

and servers in a client-server architecture. Examples of networking devices are a hub,

bridge, repeater, etc.

1.7 Sockets

A network socket is a software component of the node of a computer network that

functions as a data transmission and reception endpoint. The socket mechanism

establishes contact points between communication, allowing inter-process

communication (IPC). A socket is created to connect to the network on either end of the

connection. Every socket's address is unique and comprises an IP address and a port

number.

Sockets are utilized in the majority of client-server applications. The server creates a

socket, assigns it to a network port, and then waits for the client to communicate. After

generating a connection, the client tries to connect to the server socket. Data is

exchanged after the link is established.

15
Figure 13: Socket Programming

There are two types of sockets:

 Datagram socket: These are connectionless sockets that use User Datagram Protocol

(UDP). Each packet sent or received over a datagram connection is separately

addressed and routed. Datagram sockets can not guarantee order or dependability.

Therefore numerous packets transmitted from one machine or process to another

could arrive in any order.

 Stream socket: These are connection-oriented sockets that use Transmission Control

Protocol (TCP), Stream Control Transmission Protocol (SCTP), or Datagram

Congestion Control Protocol (DCCP). A stream socket provides a consistent,

sequential, and unique flow of error-free data without the need for record boundaries,

an organized way for creating and terminating connections, and reporting errors. On

16
the Internet, stream sockets are often implemented using TCP to allow applications to

run across any network that supports TCP/IP.

Check Your Progress 3

Note: a) For writing answers, space is given below.


b) Check your answers with the one given at this unit's end.
i) Differentiate between the client and server in client-server architecture?

…………………………………………………………………………………………

…………………………………………………………………………………………

…………………………………………………………………………………………

…………………………………………………………………………………………

ii) What are the different components of client-server architecture?

…………………………………………………………………………………………

…………………………………………………………………………………………

…………………………………………………………………………………………

1.8 Socket programming in Python

Socket programming is a technique for allowing two network nodes to communicate. One

socket listens on a specific port at an IP address, while the other establishes a connection with

it. While the client connects to the server, the server creates the listener socket.

1.8.1 Creating a socket

17
You must use the socket() method in the socket module to create a socket. The

syntax for creating a socket is as follows –

s = socket.socket(socket_family, socket_type,

protocol=0)

where,

 socket_family is either AF_UNIX or AF_INET;

 socket_type is either SOCK_STREAM or SOCK_DGRAM;

 protocol is usually left out, defaulting to 0.

For example,

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

The first parameter socket.AF_INET refers to the IPv4 family of IP addresses and

the second parameter, socket.SOCK_STREAM refers to the connection-oriented

Transmission Control Protocol (TCP).

1.8.2 Server socket methods

 socket.bind(address): This method binds the socket to the address consisting

of the hostname and the port number. The socket must not already be bound.

 socket.listen(backlog): This method sets up and starts the TCP listener and

listens for any connections to the socket. The backlog argument is the upper

bound to the number of queued connections, which should be at least 1.

 socket.accept(): This passively accepts a TCP client connection and waits

until the link arrives (blocking). The socket must be assigned an address and

18
be ready to receive connections. The return value of this function is a pair

(conn, address), with conn being a new socket object for sending and

receiving data across the connection, and address is the address linked to the

socket on the other end.

1.8.3 Client socket methods

 socket.connect(address): This method actively initiates a TCP server

connection and connects to a remote socket at the address.

1.8.4 General socket methods

 Socket. recv(bufsize[, flags]): The data from the socket is received using this

method. The data received is represented by a bytes object in the return value.

Bufsize specifies the maximum amount of data that can be received at once.

The flags option defaults to zero.

 Socket. send(bytes[, flags]): This method sends the data to the socket. A

remote socket must be connected to this socket. The optional flags argument

has the same significance as the recv() method. The number of bytes sent is

also returned using this method.

 Socket. recvfrom(bufsize[, flags]): The data from the socket is received by

this method. The return value of this method is a pair (bytes, address), where

bytes represent the received data, and address signifies the socket’s address

that sent the data.

 Socket. sendto(bytes[, flags], address): This method sends the data to the

socket. Because the target socket is identified by address, the socket should

not be connected to a remote socket. The optional flags argument has the

19
same significance as the recv() method. It also returns the number of bytes

sent.

 Socket.close(): This method closes the socket. Following the execution of this

method, all subsequent operations on the socket object will fail. There will be

no more data sent to the remote end. When the garbage collector of Python is

executed, sockets are automatically closed.

 Socket.gethostname(): The Hostname of the machine where the Python

interpreter is presently running is returned by this method.

20
Check Your Progress 4

Note: a) For writing answers, space is given below.


b) Check your answers with the one given at this unit's end.
(i) What is the difference between socket.recv() and socket.recvfrom() methods of

socket module?

…………………………………………………………………………………………

…………………………………………………………………………………………

…………………………………………………………………………………………

(ii) What does the parameter bufsize signify in the socket.recv() method?

…………………………………………………………………………………………

…………………………………………………………………………………………

……………………………………………………………………………………

(iii) What is the use of the backlog parameter in the socket.listen() method?

…………………………………………………………………………………………

…………………………………………………………………………………………

……………………………………………………………………………………

1.8.5 Connecting with the server:

We can only connect with the server if we know its IP address. The

gethostbyname() method of the socket module can be used to determine the

server’s IP address.

For example, if we want to find the IP address of Google’s server,

google_ip = socket.gethostbyname('www.google.com')

print(google_ip)

21
Output:

173.194.211.106

Note that this IP address may change each time you run the above code because

Google uses a worldwide content distribution network, with data centres

everywhere. So, each server will respond to a range of addresses, and a given IP

address may move from one server to another depending on various load factors.

1.8.6 Creating a simple server

 To create a server, we use the socket method available in the socket module to

create a socket object. This socket object is then used to call other methods to

set up a socket server.

 Subsequently, on the given host, we use the bind(hostname, port) method to

specify a port for the service.

 The accept() function of the returned object is then called. This method waits

for a client to connect to the port you provided before returning a connection

object representing that client's connection.

# Name this file as server.py

# Import the socket module first.

import socket

# Create a socket object.

s = socket.socket()

# Get local machine name.

host = socket.gethostname()

# Reserve a port number for the service.

port = 123

22
# Bind to the port.

s.bind((host, port))

# Wait for a client connection.

# Here, 3 signifies that there can be maximum of 3

queued connections.

s.listen(3)

while True:

# Establish a connection with the client.

connection, address = s.accept()

print('Received connection from', address)

# Send a message to the client.

connection. send(b’Thank you for connecting!’)

# Close the connection.

connection.close()

1.8.7 Creating a simple client

 To create a client, we use the socket method available in the socket module to

create a socket object.

 Next, we use the socket.connect(hostname, port) method to open a TCP

connection to the hostname on the port.

 Once the connection is opened, you can read from it like any I/O object.

 Remember to close the socket after completion of the task.

# Name this file as client.py

23
# Import the socket module first.

import socket

# Create a socket object.

s = socket.socket()

# Get local machine name.

host = socket.gethostname()

# Reserve a port number for the service.

port = 123

# Connect to the host on the given port.

s.connect((host, port))

# Receive data from the server.

print(str(s.recv(1024), 'utf-8'))

# Close the socket after completion.

s.close()

Now, run server.py followed by client.py. An output similar to this would be

obtained:

On server.py’s terminal:

Received connection from ('192.168.0.108', 58357)

On client.py’s terminal:

Thank you for connecting!

Let’s summarise:

We first created a socket object in the server program, fetched the local machine

name, bound a port number to specify the service, and then started listening for

24
connection requests. Once a request arrives, it is accepted, followed by sending a

confirmation message to the client.

The client program creates a socket object, and a connection request is sent to the

server on its address and the specified port number. Once the request is accepted, a

confirmation message is received.

Once the communication is done, both client and server close their sockets.

1.9 Creating a simple chat program

We will now create a simple chat program consisting of two files – sender.py and

receiver.py.

sender.py will take a message as input and send it to receiver.py, which will print the

message received and then send back an acknowledgment message to sender.py. The

program is simple and very similar to the client and server programs we discussed in the

previous sections.

Code for sender.py:

import socket

s = socket.socket()

host = socket.gethostname()

port = 123

s.bind((host, port))

s.listen(3)

while True:

connection, address = s.accept()

25
# Take the message as input

message = bytes(input('Enter your message: '), 'utf-8')

# Send the message

connection.send(message)

print('Message sent!')

# Receive the message

message = str(connection.recv(1024), 'utf-8')

print('Message received:', message)

# Close the connection

connection.close()

Code for receiver.py:

import socket

s = socket.socket()

host = socket.gethostname()

port = 123

s.connect((host, port))

# Receive the message

message = str(s.recv(1024), 'utf-8')

print('Message received:', message)

# Take the message as input

message = bytes(input('Enter your message: '), 'utf-8')

# Send the message

s.send(message)

print('Message sent!')

s.close()

26
Output for the above program:

Terminal of sender.py:

Enter your message: Hello, I am the sender program!

Message sent!

Message received: Hi, I am the receiver one!

Terminal of receiver.py:

Message received: Hello, I am the sender program!

Enter your message: Hi, I am the receiver one!

Message sent!

Let’s summarise:

The procedure is almost similar to that of the previous program, except that here, the

sender (server) program takes the message as input from the user and sends it to the

receiver (client), which in turn, takes the reply message as input from the user, and sends

it back to the sender as an acknowledgment.

1.10 Check Your Progress: The Key

1.

a) In a mesh topology, (𝑛 − 1) I/O ports are needed by each device, and 𝑛(𝑛 −

1)/2 links are required in total.

b) In a star topology, a single I/O port is needed by each device, and 𝑛 links are

required in total.

27
2.

i. The port numbers assigned to HTTP, SMTP, and Telnet services are 80, 25,

and 23, respectively.

ii. The session layer manages dialog control and synchronization, whereas the

presentation layer is responsible for translation, compression, and encryption.

iii. A socket address is formed by combining an IP address and a port number. It

is used to define the client and server process uniquely.

3.

i. The difference between a client and a server is that a client is the one who

requests a service, while a server is the one who provides the service.

ii. Different components of a client-server architecture are workstations, servers,

and networking devices.

4.

i. The difference between socket. recv() and socket.recvfrom() methods of socket

module is that the socket.recv() method is used to receive data from the socket in

the case of TCP. The client and server have already established a connection. The

return value of the socket.recv() method is a bytes object representing the data

received, whereas the socket.recvfrom() method is used to receive data from the

socket in the case of UDP, where no prior connection is established between the

client and the server. The return value of the socket.recvfrom() method is a pair

(bytes, address), where bytes represent the data received, and address denotes the

socket’s address from which the data was transmitted.

ii. The parameter bufsize in the socket.recv() method signifies the maximum amount

of data to be received at once.

28
iii. The backlog parameter in the socket.listen() method specifies the maximum

number of queued connections and should be at least 1.

29

You might also like