0% found this document useful (0 votes)
8 views

CN Lab

Uploaded by

darjihemil4902
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)
8 views

CN Lab

Uploaded by

darjihemil4902
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/ 51

NEOTECH INSTITUTE OF TECHNOLOGY

Th
isistoce
rtifythat
Mr. /Ms.….……………………………………………….
… ................. with enrolmentno. Has
successfulycompletedhis/herlaboratoryexperimentsin the
subject(w
ithcode) from
the
departmentof during
the academic year……………………….

Date of Submission : ………… Staff in Charge : …………….


Study of different network devices in detail.

Study of basic network command and Network


configuration commands

Implement different LAN topologies using


CISCOPacket Tracer.

Implement the concept of VLAN using CISCO


PacketTracer.

Implement the concept of VLAN trunking using


CISCO Packet Tracer.

Implement the concept of static routing.

Implement the concept of dynamic routing (RIP).

Packet capture and header analysis by wire-


shark(TCP, UDP, IP)

To implement RIP and OSPF.

Client server TCP and UDP socket programing.


Network devices are components used to connect computers or other electronic devices
together so thatthey can share files or resources like printers or fax machines.

These devices transfer data in a fast, secure and correct way over same or different
networks. Networkdevices may be inter-network or intra-network.
Some devices are installed on the device, like NIC card or RJ45 connector, whereas some are
part of thenetwork, like router, switch, modem etc.

Hub is one of the basic icons of networking devices which works at physical layer and hence connect
networking devices physically together.

A hub is a common connection point for devices in a network. It contains multiple ports.

Hubs and switches serve as a central connection for all of your network equipment and
handles a datatype known as frames. Frames carry your data.

They are designed to transmit the packets to the other appended devices without altering any of
thetransmitted packets received. They act as pathways to direct electrical signals to travel along.

They transmit the information regardless of the fact if data packet is destined for the device
connectedor not.

They not only provide the path for the data signals infact they regenerate,
concentrate and strengthen the signals before sending them to their destinations.
Active hubs are also termedas ‘repeaters’.

They are more like point contact for the wires to built in the physical network.
They havenothing to do with modifying the signals.

1|Pag
Switches are the linkage points of an Ethernet network. Just as in hub, devices in switches are
connectedto them through twisted pair cabling.

But the difference shows up in the manner both the devices; hub and a switch treat the data they receive.

Hub works by sending the data to all the ports on the device whereas a switch transfers it
only to thatport which is connected to the destination device.

Switches operate in full-duplex mode where devices can send and receive data from the switch at
thesimultaneously unlike in half-duplex mode.

The transmission speed in switches is double than in Ethernet hub transferring a 20Mbps
connectioninto 30Mbps and a 200Mbps connection to become 300Mbps.

A bridge is a computer networking device that builds the connection with the other bridge
networkswhich use the same protocol.

It works at the Data Link layer of the OSI Model and connects the different networks
together anddevelops communication between them.

It connects two local-area networks; two physical LANs into larger logical LAN or two
segments of thesame LAN that use the same protocol.

2|Pag
Routers are network layer devices and are particularly identified as Layer- 3 devices of the OSI Model.

They process logical addressing information in the Network header of a packet such as IP
Addresses.Router is used to create larger complex networks by complex traffic routing.

It has the ability to connect dissimilar LANs on the same protocol. It also has the ability to limit
the flowof broadcasts.

A router primarily comprises of a hardware device or a system of the computer which has
more thanone network interface and routing software.

Network cards also known as Network Interface Cards (NICs) are hardware devices that
connect acomputer with the network. They are installed on the mother board.

They are responsible for developing a physical connection between the network and the
computer.Computer data is translated into electrical signals send to the network via Network
Interface Cards.

They can also manage some important data-conversion function. These days network cards are
softwareconfigured unlike in olden days when drivers were needed to configure them.

Earlier Ethernet card had maximum speed of 10 Mbps. However modern cards support
fast Ethernetupto speed of 100 Mbps and some have a capacity of 1Gbps.

3|Pag
Gateway is a device which is used to connect multiple networks and passes packets from one
packet tothe other network.

Acting as the ‘gateway’ between different networking systems or computer programs, a


gateway is adevice which forms a link between them.

It allows the computer programs, either on the same computer or on different


computers to shareinformation across the network through protocols.

A router is also a gateway, since it interprets data from one network protocol to another.

Others such as bridge converts the data into different forms between two networking
systems. Then asoftware application converts the data from one format into another.

Gateway is a viable tool to translate the data format, although the data itself remains

unchanged.Gateway might be installed in some other device to add its functionality into

another.

Modem is a device which converts the computer-generated digital signals of a computer into
analogsignals to enable their travelling via phone lines.

The ‘modulator-demodulator’ or modem can be used as a dial up for LAN or to connect to an ISP.

Modulator converts digital data into analog data when the data is being sent by computer. And
demodulator does the vice-versa operation.

4|Pag
5|Pag
Study of basic network command and Network configuration commands.
Command Prompt

Retrieves Basic TCP/IP Network Information (IP, subnet mask, gateway)

Retrieves All TCP/IP Network Information (MAC address, adapter description, DHCP details)

6|Pag
Displays information from Domain Name System (DNS) name servers.

is a computer network administration software utility used to test the reachability of a host on an
InternetProtocol (IP) network.

7|Pag
Tracert is a command which can show you the path a packet of information takes from your computer
to one youspecify. It will list all the routers it passes through until it reaches its destination, or fails to
and is discarded. In addition to this, it will tell you how long each 'hop' from router to router takes.

A better version of tracert that gives you statics about packet lost and latency

8|Pag
9|Pag
Implement different LAN topologies using CISCO Packet Tracer.
CISCO Packet Tracer

A Computer Network is the group of computers connected together to share resources. The resource
can be hardware or software, if it is hardware example is printer shared between number of computers
and if it is softwareexample can be application program shared between number of clients.

To design the computer network the important component are sender who generates the information,
receiver who receives the information, link that connects between two stations, information which
travels on link e.g. image, audio, text, video etc, and protocol which is set of rules defined for successful
communication.

It is a visual simulation tool designed by CISCO system that allows user to create network topologies and
implement different computer network. It allows the construction, visualization and simulation of
various practical implementations involved in the field of Computer Networking.

Packet Tracer makes use of a drag and drop user interface, allowing users to add and remove
simulated network devices as they see fit. Packet Tracer allows users to create simulated network
topologies by dragging and dropping routers, switches and various other types of network devices. A
physical connection between devices is representedby a 'cable' item.

It is the way in which number of computers connected together to share information or it is geometric
representationof number of computers connected together.

It is the topology in which number of devices are connected to the central hub by point-to-point link i.e.
dedicated link between each device. In star topology, all the cables run from the computer to central
location where they are connected by a device called Hub. Hub is a device for connecting multiple
Ethernet devices together and making them act as single network. If one device wants to send data to
another, it sends the data to the Hub, which then sends that data to all other devices. This is the most
common type of topology used in offices, computer labs.

Advantages
□ Easy to install & reconfigure
□ Easy troubleshooting
□ Failure of any node does not affect system
Disadvantages
□ Failure of hub affects whole system
□ Each device requires its own cable

10 | P a g
In CISCO Packet Tracer,

Steps for network implementation and simulation:

1) Place Computing Devices on the main workspace. You can find Computers easily in the tools menu
(bottom left corner). In the tools menu, find ‘End Devices’ option to find Computing Devices. There
are plenty of end devices like Server, Laptop, Desktop, Tablet PC and many more that you can use.
Click on the end device youwant to use. Same way from the network devices, select hub and for
connection between end system and hub select the straight through cable from the connection
cables.

2) After connecting the end system with the hub through Ethernet port, assign IP address to each end
system. For assigning IP address follow: Click on PC you want to assign IP > Desktop > IP

Configuration.

3) To check the MAC address, IP address of system, connectivity, follow:


Click on PC > Desktop > Command Prompt. Use command like ipconfig, ipconfig /all, ping etc.

4) For simulation, switch to the simulation mode from realtime mode. Assign the packet to the
source PC andclick on PC you want as the destination PC. Play the simulation.

11 | P a g
5) Simulation result show that packet get transferred from source to hub. Then hub broadcast the
message toall other system. Destination PC will receive the packet and other system will reject
the packet. Then destination will send the acknowledgement packet to hub and hub will
broadcast the message.

(a) Packet transferred from PC0 (source) to Hub & hub broadcast the packet to all

Destination PC then sends the Hub then broadcast the ACK Only destination (source PC0)
(b) Only destination PC accepts
ACK packet back to the hub packet to all other PC’s acceptsthe packet and all other PC
thepacket and all other PC
(d) (e) rejects it.
rejects it.

It is the topology in which each computer is connected to the next computer, with last one connected to
the first computer in circular fashion. When any device wants to send data, then data is passed along the
ring in one direction,from device to device, until it reaches its destination. In ring topology,
each device consists of repeater which regenerates the bits and
passesthem along.
Advantages
□ Easy to find cable failure
□ To add and remove device requires changing only two connections

Disadvantages
□ Failure of one computer affects whole network
□ Unidirectional traffic

12 | P a g
It is the topology in which one long cable acts as a backbone to link all the devices in a network. In bus
topology, multiple devices are connected one by one by means of single cable called as bus. Nodes are
connected to the bus cable by drop lines and taps. A drop line is a connection running between the
device and the main cable. A tap is aconnector that either splices into main cable to create a contact
with the metallic core. When any computer wants to send data to other computer, then it will send that
data to bus first, all the computers on the network receives theinformation but only destination node
accepts it and all other reject that information.

Advantages
□ Easy to install
□ Easy to use
□ Low cost

Disadvantages
□ Difficult to troubleshot bus topology
□ Heavy network traffic can slow down bus
□ Failure of cable affects all devices

It is the topology in which every device has a dedicated point-to-point link to every other device. The term
dedicated means that the link carries traffic only between the two devices it connects. Here Node 1
must be connected to n-1 nodes, Node 2 must be connected to n-1 nodes, finally node n must be
connected to n-1 nodes. Therefore, for meshtopology we need n(n-1)/2 duplex mode lines.

Advantages
□ Privacy and security
□ Easy fault identification & fault isolations

Disadvantages
□ Difficult to install

A tree topology is a type of structure in which all the computers are connected with each other in
hierarchical fashion. The top-most node in tree topology is known as a root node, and all other nodes
are the descendants of theroot node.

Advantages
□ Extension of bus and star topologies.
□ Expansion of nodes is possible and
easy,Easily managed.

Disadvantages
□ If any fault occurs in the node, then it
becomes difficult to troubleshoot the
problem.
□ A tree topology mainly relies on main bus
cable and failure in main bus cable will
damagethe overall network.

13 | P a g
The combination of various different topologies is known as Hybrid topology. Its a connection between
differentlinks and nodes to transfer the data.

Advantages
□ Reliable: If a fault occurs in any part of
the network will not affect the functioning
of the rest of the network.
□ Scalable: Size of the network can be
easily expanded by adding new devices
without affecting the functionality of the
existing network.
□ It is very flexible as it can be designed
according to the requirements of the
organization.

Disadvantages
□ Complex design, Costly Hub

14 | P a g
15 | P a g
Implement the concept of VLAN using CISCO Packet Tracer.

CISCO Packet Tracer

Switch that supports VLANs allows multiple virtual local area networks to be defined over a single
physical local area network infrastructure. Hosts within a VLAN communicate with each other as if
they (and no otherhosts) were connected to the switch. In a port-based VLAN, the switch’s ports
(interfaces) are divided into groups by the network manager. Each group constitutes a VLAN, with
the ports in each VLAN forming a broadcast domain (i.e., broadcast traffic from one port can only
reach other ports in the group).
Figure shows a single switch with 16 ports. Ports 2 to 8 belong to the EE VLAN, while ports 9 to 15
belong tothe CS VLAN (ports 1 and 16 are unassigned). EE and CS VLAN frames are isolated from
each other, and if the user at switch port 8 joins the CS Department, the network operator simply
reconfigures the VLAN softwareso that port 8 is now associated with the CS VLAN.
The network manager declares a port to belong to a given VLAN (with undeclared ports belonging to
a defaultVLAN) using switch management software, a table of port-to-VLAN mappings is maintained
within the switchand switch hardware only delivers frames between ports belonging to the same
VLAN.

16 | P a g
Configuring from terminal, memory, or network [terminal]?
Enter configuration commands, one per line. End with
CNTL/Z.

Switch#
%SYS-5-CONFIG_I: Configured from console by console

VLAN Name Status Ports

1 default active Fa0/1, Fa1/1, Fa2/1,


Fa3/1Fa4/1, Fa5/1

1002 fddi-default active


1003 token-ring-default active
1004 fddinet-default active
1005 trnet-default active

VLAN Type SAID MTU Parent RingNo BridgeNo Stp BrdgMode Trans1 Trans2

1 enet 100001 1500 00


10 enet 100010 1500 00
20 enet 100020 1500 00
17 | P a g
1002 fddi 101002 1500 00
1003 tr 101003 1500 00
1004 fdnet 101004 1500 - - - ieee - 0 0
1005 trnet 101005 1500 - - - ibm - 0 0

VLAN Type SAID MTU Parent RingNo BridgeNo Stp BrdgMode Trans1 Trans2

Remote SPAN VLANs

Primary Secondary Type Ports

Configuring from terminal, memory, or network [terminal]?


Enter configuration commands, one per line. End with
CNTL/Z.

Switch#
%SYS-5-CONFIG_I: Configured from console by console

18 | P a g
VLAN Name Status Ports

1 default active Fa4/1,


Fa5/1

1002 fddi-default
active
1003 token-ring-default active
1004 fddinet-default active
1005 trnet-default active

VLAN Type SAID MTU Parent RingNo BridgeNo Stp BrdgMode Trans1 Trans2

1 enet 100001 1500 00


10 enet 100010 1500 00
20 enet 100020 1500 00
1002 fddi 101002 1500 00
1003 tr 101003 1500 00
1004 fdnet 101004 1500 - - - ieee - 0 0
1005 trnet 101005 1500 - - - ibm - 0 0

VLAN Type SAID MTU Parent RingNo BridgeNo Stp BrdgMode Trans1

Trans2Switch#

19 | P a g
20 | P a g
Implement the concept of VLAN trunking using CISCO Packet Tracer.

CISCO Packet Tracer

With VLAN trunking, it’s possible to extend a VLAN across the network. To implement multiple
VLANs across a network, trunk links are necessary to ensure that VLAN signals remain properly
segregated for each to reach their intended destination. This is also more efficient, as multiple
VLANs can be configured on a single port.

Configure the VLAN database by adding VLAN Number and VLAN Name inside the Switch. Add
VLAN database for both IT and CP Dept.

Configure interface FastEthernet0/1 to VLAN 10 and FastEthernet1/1 to VLAN 20.

21 | P a g
Same way configure VLAN database for another switch and its interface to VLAN.
Now to configure a switch port on one end of a trunk link, use the command.
Withthis command, the interface changes to permanent trunking mode.

Now the using VLAN trunking, multiple VLAN in the network can be connected and packet get
transferred toits inter VLAN.

22 | P a g
23 | P a g
Implement the concept of static

routing. CISCO Packet

Tracer

Routers forward packets using either route information from route table entries that you manually
configure orthe route information that is calculated using dynamic routing algorithms.
Static routing is a form of routing that occurs when a router uses a manually-configured routing
entry, rather than information from dynamic routing traffic. In many cases, static routes are
manually configured bya network administrator by adding in entries into a routing table, though
this may not always be the case.
Static routing is the most secure way of routing. It reduces overhead from network resources. In
this type of routing we manually add routes in routing table. It is useful where numbers of route are
limited.

Configure Interface FastEthernet0/0 in router R0.

24 | P a g
25 | P a g
Configure Interface FastEthernet1/0 in router R0.

Configure Interface FastEthernet0/0 in router R1.

Configure Interface Serial2/0 in router R0 by providing clock rate, IP configuration & switch on the port
status.

26 | P a g
Configuration of routers should coincide with two things: 1) Physical Connection 2) Configuration
Here network 1 & 2 machines have an information about router R0 but not about router R1. So it’s
needed to provide information of router R1, where is the network. This can be done by Static
routing where router uses a manually configured routing entry.
Configure Interface Serial2/0 in router R1 by providing IP configuration & switch on the port status.

R0 must provide information of network 192.168.3.0 for the static routes. So configure Static
routing by providing information of network and next hop. Here next hop is 10.10.0.3, it means
when packet arrives at the network 3, router R1 will handle the packet.

Same way router R1 should have information about network 1 and network 2 in its own routing
table. So configure router R1 and add network 1 and network 2 and its next hop.

27 | P a g
Now transferring of packets from one network to another network will be successful using static routing.

28 | P a g
29 | P a g
Implement the concept of dynamic routing

(RIP). CISCO Packet Tracer

The Routing Information Protocol (RIP) is one of the oldest distance-vector routing protocols which
employs
the hop count as a routing metric. RIP prevents routing loops by implementing a limit on the
number of hops allowed in a path from source to destination. The largest number of hops allowed
for RIP is 15, which limits the size of networks that RIP can support. In RIP, routers broadcast
updates with their routing table every30 seconds.

Consider the network 1 with IP 192.168.1.0 and network 2 with IP 192.168.2.0. Between two
routers there is network with IP 10.0.0.0. Configure the systems by providing IP address and
default gateway to every end system in the network.
Configure the router 0 to interface FastEthernet0/0 by providing default gateway IP address and
switching onthe port status.

30 | P a g
Same way configure the router 1 to interface FastEthernet0/0 by providing default gateway IP
address andswitching on the port status.

Configure Interface Serial2/0 in router R0 by providing clock rate, IP configuration & switch on the port
status.

Configure router 0 with Routing Information Protocol (RIP), by adding network address in the RIP
Routingand then save this in NVRAM from the setting.

31 | P a g
Same way configure router 1 with Routing Information Protocol (RIP), by adding network address in the
RIPRouting and then save this in NVRAM from the setting.

Now transferring of packets from one network to another network will be successful using RIP routing.

32 | P a g
33 | P a g
Packet capture and header analysis by wire-shark (TCP, UDP, IP)

Wireshark

Wireshark is a free open source network packet analyzer. It is used for network troubleshooting
andcommunication protocol analysis. Wireshark captures network packets in real time and display
them in human readable format. It provides many advanced features including live capture and
offline analysis, three-pane packet browser, colouring rules for analysis.

The following are some of the many features Wireshark provides:

• Available for UNIX and Windows.


• Capture live packet data from a network interface.
• Open files containing packet data captured with tcpdump/WinDump, Wireshark, and many
other packetcapture programs.
• Import packets from text files containing hex dumps of packet data.
• Display packets with very detailed protocol information.
• Save packet data captured.
• Export some or all packets in a number of capture file formats.
• Filter packets on many criteria.
• Search for packets on many criteria.
• Colorize packet display based on filters.
• Create various statistics.

When you run the Wireshark program, the Wireshark graphic user interface will be shown as Figure.
Currently, the program is not capturing the packets. Then, you need to choose an interface. If you
are running the Wireshark on your laptop, you need to select Wi-Fi interface. If you are at a desktop,
you need to select the Ethernet interface being used. Note that there could be multiple interfaces.
In general, you can select any interface but that does not mean that traffic will flow through that
Interface.

They are standard pulldown menus located at the top of the window. The File
menu allowsyou to save captured packet data or open a file containing previously captured packet
data, and exit the Wireshark application. The Capture menu allows you to begin packet capture.

: It displays a one-line summary for each packet captured, including the packet
number (assigned by Wireshark; this is not a packet number contained in any protocol’s header),
the time at which the packet was captured, the packet’s source and destination addresses, the
protocol type, and protocol-specific information contained in the packet.

34 | P a g
The packet listing can be sorted according to any of these categories by clicking on a column
name. The protocol type field lists the highest-level protocol that sent or received this packet, i.e.,
the protocol that is thesource or ultimate sink for this packet.

It provides details about the packet selected (highlighted) in the packet-listing


window.(To select a packet in the packet-listing window, place the cursor over the packet’s one-line
summary in the packet-listing window and click with the left mouse button.). These details include
information about the Ethernet frame and IP datagram that contains this packet.

The amount of Ethernet and IP-layer detail displayed can be expanded or minimized by clicking on
the right pointing or down-pointing arrowhead to the left of the Ethernet frame or IP datagram line
in the packet detailswindow.
If the packet has been carried over TCP or UDP, TCP or UDP details will also be displayed, which can
similarly be expanded or minimized. Finally, details about the highest-level protocol that sent or
received this packet arealso provided.

It displays the entire contents of the captured frame, in both ASCII and
hexadecimal format.

When you run the Wireshark program, the Wireshark graphic user interface will be shown as Figure.
Currently,the program is not capturing the packets.

Then, you need to choose an interface. If you are running the Wireshark on your laptop connected to
Wi-Fi, select Wi-Fi interface. There could be multiple interfaces.

35 | P a g
After you select the interface, you can click start to capture the packets as shown in

Figure.Selecting the UDP packet from all the network packets from Wireshark.

First line shows a summary of the frame. The other lines show the data link layer, the network layer, the
User
datagram protocol, and finally, the actual data contained within the frame.

Listing of captured

Details of selected packet

Packet Content in hexadecimal and

36 | P a g
ROUTER 1
37 | P a g
END DEVICES:
PC0

PC1

FOR DISABLING RIP:

38 | P a g
ROUTER 0

39 | P a g
ROUTER 1

SHOW IP ROUTE

40 | P a g
• se2/0 refers to the serial interface on a router, specifically the interface labeled as Serial 2/0. Routers often use
serial interfaces to connect to Wide Area Networks (WANs) or other routers over point-to-point links.
• :

• Serial interfaces are typically used for connections between routers across longer distances (e.g., between
two different locations or two different routers).
• In your configuration, the Serial 2/0 interface (se2/0) is being used to connect Router 1 to another router
(possibly Router 2).

• : 10.0.0.1 is the IP address assigned to the Serial 2/0 interface on Router 1.


• :
o The 10.0.0.0/30 network (where the IP address 10.0.0.1 falls) is being used as the point-to-point link
between Router 1 and another router. The 10.0.0.1 IP address is assigned to the Router 1 side of this
connection.
o The corresponding interface on the other router (Router 2) would typically have an IP address like
10.0.0.2, which is in the same network (10.0.0.0/30).

WHAT IS NETWORK 10.0.0.0/30?

The notation 10.0.0.0/30 represents a specific IP address range (or subnet) using a combination of an IP
address (10.0.0.0) and a subnet mask (/30). Here's a breakdown of what it means:

• : 10.0.0.0 is the network address for this particular subnet. It is not assignable to any
device because it represents the entire subnet.

• : The /30 is a shorthand (in CIDR notation) that indicates the subnet mask. The /30 means
that the first 30 bits of the IP address are used for the network portion, leaving the remaining 2 bits for host
addresses.
• : In binary, a /30 subnet mask looks like this: 11111111.11111111.11111111.11111100

Decimal:255.255.255.252

• : A /30 subnet provides a total of 4 IP addresses.


o : (e.g., 10.0.0.0)
o : (e.g., 10.0.0.1 and 10.0.0.2)
o : (e.g., 10.0.0.3)
• :

41 | P a g
o : Typically assigned to one device or router (e.g., the first router in a point-to-point
connection).
o : Typically assigned to the other device or router (e.g., the second router in a point-to-point
connection).

42 | P a g
Aim: Client server TCP and UDP socket prograaming.

client :

import socket

def run_client():
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = "127.0.0.1" # replace with the server's IP address


server_port = 8000 # replace with the server's port number
# establish connection with server
client.connect((server_ip, server_port)) import socket

def run_client():
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = "127.0.0.1" # replace with the server's IP address


server_port = 8000 # replace with the server's port number
# establish connection with server
client.connect((server_ip, server_port))

while True:
# input message and send it to the server
msg = input("Enter message: ")
client.send(msg.encode("utf-8")[:1024])

# receive message from the server


response = client.recv(1024)
response = response.decode("utf-8")

# if server sent us "closed" in the payload, we break out of the loop and close our socket if
response.lower() == "closed":
break

print(f"Received: {response}")

# close client socket (connection to the server)


client.close()
print("Connection to server closed")

run_client()

while True:
# input message and send it to the server

43 | P a g
msg = input("Enter message: ")
client.send(msg.encode("utf-8")[:1024])

# receive message from the server


response = client.recv(1024)
response = response.decode("utf-8")

# if server sent us "closed" in the payload, we break out of the loop and close our socket if
response.lower() == "closed":
break

print(f"Received: {response}")

# close client socket (connection to the server)


client.close()
print("Connection to server closed")

run_client()

import socket

def run_client():
# create a socket object
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = "127.0.0.1" # replace with the server's IP address


server_port = 8000 # replace with the server's port number
# establish connection with server
client.connect((server_ip, server_port))

while True:
# input message and send it to the server
msg = input("Enter message: ")
client.send(msg.encode("utf-8")[:1024])

# receive message from the server


response = client.recv(1024)
response = response.decode("utf-8")

# if server sent us "closed" in the payload, we break out of the loop and close our socket if
response.lower() == "closed":
break

print(f"Received: {response}")

# close client socket (connection to the server)


client.close()
print("Connection to server closed")

run_client()

44 | P a g
Server :

import socket

def run_server():
# create a socket object
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_ip = "127.0.0.1"
port = 8000

# bind the socket to a specific address and port


server.bind((server_ip, port))
# listen for incoming connections
server.listen(0)
print(f"Listening on {server_ip}:{port}")

# accept incoming connections


client_socket, client_address = server.accept()
print(f"Accepted connection from {client_address[0]}:{client_address[1]}")

# receive data from the client


while True:
request = client_socket.recv(1024)
request = request.decode("utf-8") # convert bytes to string

# if we receive "close" from the client, then we break


# out of the loop and close the conneciton
if request.lower() == "close":
# send response to the client which acknowledges that the
# connection should be closed and break out of the loop
client_socket.send("closed".encode("utf-8"))
break

print(f"Received: {request}")

response = "accepted".encode("utf-8") # convert string to bytes #


convert and send accept response to the client
client_socket.send(response)

# close connection socket with the client


client_socket.close()
print("Connection to client closed")
# close server socket
server.close()

run_server()

45 | P a g
UDP_client :

import socket

msgFromClient = input("enter your message")

bytesToSend = str.encode(msgFromClient)

serverAddressPort = ("127.0.0.1", 20001)

bufferSize = 1024

# Create a UDP socket at client side

UDPClientSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Send to server using created UDP socket

UDPClientSocket.sendto(bytesToSend, serverAddressPort)

msgFromServer = UDPClientSocket.recvfrom(bufferSize)

msg = "Message from Server {}".format(msgFromServer[0])

print(msg)

46 | P a g
UDP_server :

import socket

localIP = "127.0.0.1"

localPort = 20001

bufferSize = 1024

msgFromServer = "Hello UDP Client"

bytesToSend = str.encode(msgFromServer)

# Create a datagram socket

UDPServerSocket = socket.socket(family=socket.AF_INET, type=socket.SOCK_DGRAM)

# Bind to address and ip

UDPServerSocket.bind((localIP, localPort))

print("UDP server up and listening")

# Listen for incoming datagrams

while(True):

bytesAddressPair = UDPServerSocket.recvfrom(bufferSize)

message = bytesAddressPair[0]

address = bytesAddressPair[1]

clientMsg = "Message from Client:{}".format(message)


clientIP = "Client IP Address:{}".format(address)

47 | P a g
print(clientMsg)
print(clientIP)

# Sending a reply to client

UDPServerSocket.sendto(bytesToSend, address)

48 | P a g

You might also like