0% found this document useful (0 votes)
31 views92 pages

Lab Manual r20 Cnm...

Cn lab manual .mmm

Uploaded by

shaikasif7543
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)
31 views92 pages

Lab Manual r20 Cnm...

Cn lab manual .mmm

Uploaded by

shaikasif7543
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/ 92

ANDHRA LOYOLA INSTITUTE OF ENGINEERING AND TECHNOLOGY

DEPARTMENT OF INFORMATION TECHNOLOGY


VIJAYAWADA-8
COMPUTER NETWORKS – LAB MANUAL
REGULATION: R20

1. Study of Network devices in detail and connect the computers in Local Area Network.

BASIC NETWORK DEVICES


Hardware devices that are used to connect computers, printers, fax machines and other electronic devices to a
network are called network devices. These devices transfer data in a fast, secure and correct way over same or
different networks. Network devices 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 the network, like router, switch, etc. Let us explore some
of these devices in greater detail.

Modem
Modem is a device that enables a computer to send or receive data over telephone or cable lines. The data stored on
the computer is digital whereas a telephone line or cable wire can transmit only analog data.

The main function of the modem is to convert digital signal into analog and vice versa. Modem is a combination of
two devices − modulator and demodulator. The modulator converts digital data into analog data when the data is
being sent by the computer. The demodulator converts analog data signals into digital data when it is being received
by the computer.

Types of Modem
Modem can be categorized in several ways like direction in which it can transmit data, type of connection to the
transmission line, transmission mode, etc.
Depending on direction of data transmission, modem can be of these types −

 Simplex − A simplex modem can transfer data in only one direction, from digital device to network (modulator)
or network to digital device (demodulator).
 Half duplex − A half-duplex modem has the capacity to transfer data in both the directions but only one at a
time.
 Full duplex − A full duplex modem can transmit data in both the directions simultaneously.

RJ45 Connector
RJ45 is the acronym for Registered Jack 45. RJ45 connector is an 8-pin jack used by devices to physically connect
to Ethernet based local area networks (LANs). Ethernet is a technology that defines protocols for establishing a
LAN. The cable used for Ethernet LANs are twisted pair ones and have RJ45 connector pins at both ends. These
pins go into the corresponding socket on devices and connect the device to the network

Study of different types of Network cables and practically implement the cross-wired cable and
straight through cable using clamping tool.

Procedure:To do these practical following steps should be done:

1. Start by stripping off about 2 inches of the plastic jacket off the end of the cable. Be
verycareful at this point, as to not nick or cut into the wires, which are inside. Doing so could
alterthe characteristics of our cable, or even worse render is useless. Check the wires, one more
timefor nicks or cuts. If there are any, just whack the whole end off, and start over.

2. Spread the wires apart, but be sure to hold onto the base of the jacket with your other
hand.You do not want the wires to become untwisted down inside the jacket. Category 5 cable
mustonly have 1/2 of an inch of 'untwisted' wire at the end; otherwise it will be 'out of spec'. At
thispoint, you obviously have ALOT more than 1/2 of an inch of un-twisted wire.

3. You have 2 end jacks, which must be installed on your cable. If you are using a pre-
madecable, with one of the ends whacked off, you only have one end to install –thecrossed over
end.Below are two diagrams, which show how you need to arrange the cables for each type of
cableend. Decide at this point which end you are making and examine the associated picture
below.
Ethernet Card
Ethernet card, also known as network interface card (NIC), is a hardware component used by computers to
connect to Ethernet LAN and communicate with other devices on the LAN. The earliest Ethernet cards were
external to the system and needed to be installed manually. In modern computer systems, it is an internal hardware
component. The NIC has RJ45 socket where network cable is physically plugged in.

Ethernet card speeds may vary depending upon the protocols it supports. Old Ethernet cards had maximum speed
of 10 Mbps. However, modern cards support fast Ethernets up to a speed of 100 Mbps. Some cards even have
capacity of 1 Gbps.

Router
A router is a network layer hardware device that transmits data from one LAN to another if both networks support
the same set of protocols. So a router is typically connected to at least two LANs and the internet service
provider (ISP). It receives its data in the form of packets, which are data frames with their destination
address added. Router also strengthens the signals before transmitting them. That is why it is also called repeater.
A router is an electronic device that interconnects two or more computer networks, and
selectively interchanges packets of data between them. Each data packet contains address
information that a router can use to determine if the source and destination are on the same
network, or if the data packet must be transferred from one network to another. Where multiple
routers are used in a large collection of interconnected networks, the routers exchange
information about target system addresses, so that each router can build up a table showing the
preferred paths between any two systems on the interconnected networks.
Routing Table
A router reads its routing table to decide the best available route the packet can take to reach its destination quickly
and accurately. The routing table may be of these two types −

 Static − In a static routing table the routes are fed manually. So it is suitable only for very small networks that
have maximum two to three routers.
 Dynamic − In a dynamic routing table, the router communicates with other routers through protocols to
determine which routes are free. This is suited for larger networks where manual feeding may not be feasible
due to large number of routers.
Hub:

An Ethernet hub, active hub, network hub, repeater hub, hub or concentrator is a device for
connecting multiple twisted pair or fiber optic Ethernet devices together and making them act as
a single network segment. Hubs work at the physical layer (layer 1) of the OSI model. The
device is a form of multiport repeater. Repeater hubs also participate in collision detection,
forwarding a jam signal to all ports if it detects a collision.
Switch
Switch is a network device that connects other devices to Ethernet networks through twisted pair cables. It
uses packet switching technique to receive, store and forward data packets on the network. The switch maintains
a list of network addresses of all the devices connected to it.
On receiving a packet, it checks the destination address and transmits the packet to the correct port. Before
forwarding, the packets are checked for collision and other network errors. The data is transmitted in full duplex mode

Data transmission speed in switches can be double that of other network devices like hubs used for networking. This
is because switch shares its maximum speed with all the devices connected to it. This helps in maintaining network
speed even during high traffic. In fact, higher data speeds are achieved on networks through use of multiple switches.

A network switch or switching hub is a computer networking device that connects network
segments. The term commonly refers to a network bridge that processes and routes data at the
data link layer (layer 2) of the OSI model. Switches that additionally process data at the network
layer (layer 3 and above) are often referred to as Layer 3 switches or multilayer switches.
Repeater: Functioning at Physical Layer. Repeater is an electronic device that receives signal
and retransmits it at a higher level and/or higher power, or onto the other side of an obstruction,
so that the signal can cover longer distances. Repeater have two ports, so cannot be use to
connect for more than two devices
Bridge: A network bridge connects multiple network segments at the data link layer (Layer2) of
the OSI model. In Ethernet networks, the term bridge formally means a device that be haves
according to the IEEE 802.1D standard. A bridge and switch are very much alike; a switch being
a bridge with numerous ports. Switch or Layer 2 switch is often used interchangeably with
bridge. Bridges can analyze incoming data packets to determine if the bridge is able to send the
given packet to another segment of the network.
Gateway
Gateway is a network device used to connect two or more dissimilar networks. In networking parlance, networks that
use different protocols are dissimilar networks. A gateway usually is a computer with multiple NICs connected to
different networks. A gateway can also be configured completely using software. As networks connect to a different
network through gateways, these gateways are usually hosts or end points of the network.

Gateway uses packet switching technique to transmit data from one network to another. In this way it is similar to
a router, the only difference being router can transmit data only over networks that use same protocols.

In a communications network, a network node equipped for interfacing with another network
that uses different protocols.• A gateway may contain devices such as protocol translators,
impedance matching devices, rate converters, fault isolators, or signal translators as necessary to
provide system interoperability. It also requires the establishment of mutually acceptable
administrative procedures between both networks.
• A protocol translation/mapping gateway interconnects networks with different network
protocol technologies by performing the required protocol conversions.
Wi-Fi Card
Wi-Fi is the acronym for wireless fidelity. Wi-Fi technology is used to achieve wireless connection to any
network. Wi-Fi card is a card used to connect any device to the local network wirelessly. The physical area of the
network which provides internet access through Wi-Fi is called Wi-Fi hotspot. Hotspots can be set up at home, office
or any public space. Hotspots themselves are connected to the network through wires.

A Wi-Fi card is used to add capabilities like teleconferencing, downloading digital camera images, video chat, etc.
to old devices. Modern devices come with their in-built wireless network adapter.
Study of network IPAddress

• Classification of IP address• Sub netting• Super netting

• Classification of IP address

As show in figure we teach how the ip addresses are classified and when they are used.

1. Connect the computers in Local Area Network [LAN].

Procedure: On the host computer

On the host computer, follow these steps to share the Internet connection:

1. Log on to the host computer as Administrator or as Owner.


2. Click Start, and then click Control Panel.
3. Click Network and Internet Connections.
4. Click Network Connections.
5. Right-click the connection that you use to connect to the Internet. For example, if you connect
to the Internet by using a modem, right-click the connection that you want under Dial-up/ other
network available.6. ClickProperties.
7. Click the Advanced tab.
8. Under Internet Connection Sharing, select the Allow other network users to connect through
this computer's Internet connection check box.
9. If you are sharing a dial-up Internet connection, select the Establish a dial-up connection
whenever a computer on my network attempts to access the Internet check box if you want to
permit your computer to automatically connect to the Internet.

10. Click OK. You receive the following message:


When Internet Connection Sharing is enabled, your LAN adapter will be set to use IP
address192.168.0.
Your computer may lose connectivity with other computers on your network. If these other
computers have static IP addresses, it is a good idea to set them to obtain their IP addresses
automatically. Are you sure you want to enable Internet Connection Sharing?

11. Click Yes. The connection to the Internet is shared to other computers on the local area
network (LAN). The network adapter that is connected to the LAN is configured with a static IP
address of192.168.0. 1 and a subnet mask of 255.255.255.0
On the client computer

To connect to the Internet by using the shared connection, you must confirm the LAN adapter IP
configuration, and then configure the client computer. To confirm the LAN adapter IP
configuration, follow these steps:

1. Log on to the client computer as Administrator or as Owner.


2. Click Start, and then click Control Panel.
3. Click Network and Internet Connections.
4. Click Network Connections.
5. Right-click Local Area Connection and then click Properties.
6. Click theGeneraltab, clickInternet Protocol (TCP/IP)in theconnection uses the
followingitemslist, and then clickProperties.
7. In theInternet Protocol (TCP/IP) Propertiesdialog box, clickObtain an IP
addressautomatically(if it is not already selected), and then clickOK.

Note:You can also assign a uniquestatic IP address in the range of 192.168.0.2 to254.

For example, you can assign the following static IP address, subnet mask, and default gateway:

8. IP Address 192.168.31.2029. Subnetmask 255.255.255.0


10. Default gateway 192.168.31.1
11. In the Local Area Connection Properties dialog box, clickOK.12. Quit Control Panel.
INTERNET- Basics
Network: A network is a group of two or more computer systems linked together.

There are many types of computernetworks,


computer including:

-Local-area (LANs) The computers are geographically close together (that is, in the
area networks (LANs):
same building).
-Metropolitan-area MANs) A data network designed for a town or city.
area networks MANs):
-Wide-area
area networks (WANs) part (countries) and are connected
(WANs): The computers are farther apart
by telephone lines or radio waves.

Internet:The internet is a global system of interconnected computer networks


networks. It is a network
of networks. More than 200 countries are linked to exchange of data,, news and opinions. No one
actually owns the Internet, and no single person or organization controls the Internet in its entirety. It
contains unlimited number of users.

Intranet:Intranet is the generic term for a collection of private computer networks within an
organization. It contains limited number of user within the company.

Extranet:An "extranet" is a computer network that allows controlled access from the outside for
specific business or educational purposes.
TCP/IP (Transmission control protocol/Internet protocol):

What is a Protocol? - A standard set of regulations and requirements (or) that allow two
electronic items to connect to and exchange information with one another.

What is Host?-A network host is a computer connected to a computer network.

TCP/IP is the communication protocol for the internet.TCP/IP defines the rule that
computers (or) hosts must follow to communicate with each other over the internet.

IP (Internet protocol): The Internet Protocol is responsible for addressing hosts in


network and for routing (setting direction) information from a source host to a destination host.
IP by itself is something like the postal system.

An Internet Protocol address (IP address) is a numerical label assigned to each device
(e.g., computer, printer) (or) web page participating in a computer network that uses the Internet
Protocol for communication. The current version of IP address is IPv4 (Internet protocol
Version 4) and IPv6

IPv6 uses 128 bits for addressing and IPv4 uses 32 bits for addressing a computer.For
example

11011111 00111010 00000001 00001010 by converting it in to decimal it looks like


223.58.1.10which is called IP address. Here each number is 8 bit ranging from 0 to 255, so we
can have 2 unique addresses.

TCP (Transmission control protocol): TCP enables two hosts to establish a connection and
exchange streams of data. TCP guarantees delivery of data and also guarantees that data will be
delivered in the same order in which they were sent.

Creating the new internet connection: Most commonly used modes of connecting to
internet as follow
 Telephone modem
 Ethernet
 ISDN
 Cable modems
 Satellite
To create the new internet connection in windows xp
1. Go to start and select Control Panel.
2. Open Network Connections.
3. Click Create a new connection and then click Next
4. The New connection wizard window comes, click Next to continue.

5. Choose one of the following as per required, generally it is the first option.Hence,selectConnect
to the Internet and click Next
6. Choose among three options appearing in the wizard

Internet service provider (ISP) is the company or the organization which provides internet to the public
e.g. BSNL, AIRTEL etc.If you don’t have internet connection then select option one

7. Select connect using dial-up modem or Connect using broadband connection and click Next

8. On the next ongoing windows we have to provide ISP name(internet service provider name) and
phone number, user name, password
9. Click Finish to end setup and newly crearted connection will appear in the network connectins
10.

Select the newly created connection and open properties by right click. Here select the
Internet protocol (TCP/IP) and open properties.

Here use required system IP address to connect and DNS server address.
Connecting of computers in the internet network

Setup Network Connections


What is a 192.168 IP address? The IP address 192.168. 0.1 is one of 17.9 million private addresses, and it's used as the
default router IP address for certain routers, including some models from Cisco, D-Link, LevelOne, Linksys, and many
others.
What are the 4 types of IP address? An IP address allows computers to send and receive data over the internet. Most IP
addresses are purely numerical, but as internet usage grows, letters have been added to some addresses. There are four
different types of IP addresses: public, private, static, and dynamic.
What is IP address in simple words? An IP address is a unique address that identifies a device on the internet or a
local network. IP stands for "Internet Protocol," which is the set of rules governing the format of data sent via the internet or
local network. ... IP addresses provide a way of doing so and form an essential part of how the internet works.
Why IP address is important? IP addresses may identify your own computer, a favorite website, a network server, or even
a device (such as a webcam). IP addresses are especially important for sending and receiving information. They route
internet traffic where it needs to go, and they direct emails to your inbox.
What is a subnet mask used for? A subnet mask is used to divide an IP address into two parts. One part identifies the
host (computer), the other part identifies the network to which it belongs. To better understand how IP addresses and subnet
masks work, look at an IP address and see how it's organized.
What is a 255.255 255.0 subnet? A subnet mask of 255.255. 255.0 allows for close to 256 unique hosts within the
network (since not all 256 IP addresses can be used). ... This is the default subnet mask used by Class B networks and
provides up to 65,536 IP addresses (256 x 256).
What is the default gateway IP address? In the networking world, a default gateway is an IP address that traffic gets
sent to when it's bound for a destination outside the current network. On most home and small business networks—
where you have a single router and several connected devices—the router's private IP address is the default gateway.
What is default gateway example? In a home or small office environment, the default gateway is a device, such as a DSL
router or cable router, that connects the local network to the Internet. ... A device wishing to communicate with a host on
the public Internet, for example, forwards the packet to the default gateway for its network segment.

A gateway and a router are essentially the same. The term "default gateway" is used to mean the router on your LAN
which has the responsibility of being the first point of contact for traffic to computers outside the LAN.

What is the preferred DNS server? The preferred DNS is a specified primary choice to handle Internet protocol
mapping. If the preferred choice times out after a time limit defined by an operating system, it will then attempt to try the
alternate DNS. Servers are subject to the same connectivity problems a home user may experience.
What is a DNS server IPv4? The Domain Name System (DNS) Server is a server that is specifically used for matching
website hostnames (like example.com)to their corresponding Internet Protocol or IP addresses. ... Every device connected
to the internet has a unique IP address that helps to identify it, according to the IPv4 or IPV6 protocols.
What should I put for preferred DNS?
Public DNS Servers

Personally, I prefer OpenDNS (208.67. 220.220 and 208.67. 222.222) and Google Public DNS (8.8. 8.8 and 8.8.

What is Alternate DNS address?


The presence of an alternate DNS means that a single DNS server failure does not prevent clients from accessing web
pages. It allows devices to continue resolving addresses even if their primary server is down. Alternate DNS servers can
sometimes also be used to share the load of DNS requests on busy networks.
Third-party DNS Preferred IPv4 DNS server Alternate IPv4 DNS server
servers address address

Google Public DNS 8.8.8.8 8.8.4.4

OpenDNS 208.67.222.222 208.67.220.220

Advanced network settings

What device can be DHCP server? For companies with small networks or at home, a router generally acts as the DHCP
server. In large networks, a dedicated server, known as a host, might act as the DHCP server. The DHCP client device will
send a request for the allotment of an IP address to the DHCP Server.
The main difference between IPv4 and IPv6 is the address size of IP addresses. The IPv4 is a 32-bit address, whereas
IPv6 is a 128-bit hexadecimal address. IPv6 provides a large address space, and it contains a simple header as compared
to IPv4.

Which is faster IPv4 or IPv6? IPv4 occasionally won the test. In theory, IPv6 should be a little faster since cycles don't
have to be wasted on NAT translations. But IPv6 also has larger packets, which may make it slower for some use cases. ...
So with time and tuning, IPv6 networks will get faster.
Should I activate IPv6? Best answer: IPv6 can potentially add support for more devices, better security, and more efficient
connections. While some older software may not work as expected, most of your network should work fine with IPv6
enabled.
Obtaining an IP Address automatically on a computer using Windows® 8, 8.1 or 10 operating system
1. Right-click the Network. ...
2. Right-click on the Local Area Connection icon and click Properties.
3. Select Obtain an IP address automatically then click OK.
4. Press the Windows key + D on your keyboard to show the Desktop.
2. Write a Program to implement the data link layer farming methods such as

i) Character stuffing ii) bit stuffing.

2.1 Implement the data link layer farming methods such as and Character stuffing.

Introduction to character stuffing method of framing for Data Link Layer: The framing
method gets around the problem of resynchronization after an error by having each frame start with the
ASCII character sequence DLE STX and the sequence DLE ETX. If the destination ever losses the track of
the frame boundaries all it has to do is look for DLE STX or DLE ETX characters to figure out. The data link
layer on the receiving end removes the DLE before the data are given to the network layer. This
technique is called character stuffing.

Program Algorithm:

Begin
Step 1: Initialize I and j as 0
Step 2: Declare n and pos as integer and a[20],b[50],ch as character
Step 3: read the string a
Step 4: find the length of the string n, i.e n-strlen(a)
Step 5: read the position, pos
Step 6: if pos > n then
Step 7: print invalid position and read again the position, pos
Step 8: endif
Step 9: read the character, ch
Step 10: Initialize the array b, b[0…5] as ’d’, ’l’, ’e’, ’s’, ’t’,’x’ respectively
Step 11: j=6;
Step 12: Repeat step[(13to22) until i<n
Step 13: if i==pos-1 then
Step 14: initialize b array,b[j],b[j+1]…b[j+6] as‘d’, ‘l’, ‘e’ ,’ch, ’d’, ‘l’,‘e’ respectively
Step 15: increment j by 7, i.e j=j+7
Step 16: endif
Step 17: if a[i]==’d’ and a[i+1]==’l’ and a[i+2]==’e’ then
Step 18: initialize array b, b[13…15]=’d’, ‘l’, ‘e’ respectively
Step 19: increment j by 3, i.e j=j+3
Step 20: endif
Step 21: b[j]=a[i]
Step 22: increment I and j;
Step 23: initialize b array,b[j],b[j+1]…b[j+6] as‘d’, ‘l’,‘e’,’e’,‘t’, ‘x’,‘\0’ respectively
Step 24: print frame after stuffing
Step 25: print b
End
Program Code: //Program for Character Stuffing
#include<stdio.h>
#include<string.h>
#include<process.h>
void main()
{
int i=0,j=0,n,pos;
char a[20],b[50],ch;
printf("Enter string\n");
scanf("%s",&a);
n=strlen(a);
printf("Enter position\n");
scanf("%d",&pos);
if(pos>n)
{
printf("invalid position, Enter again :");
scanf("%d",&pos);}
printf("Enter the character\n");
ch=getche();
b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x';
j=6;
while(i<n)
{
if(i==pos-1)
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]=ch;
b[j+4]='d';
b[j+5]='l';
b[j+6]='e';
j=j+7;
}
if(a[i]=='d' && a[i+1]=='l' && a[i+2]=='e')
{
b[j]='d';
b[j+1]='l';
b[j+2]='e';
j=j+3;
}
b[j]=a[i];
i++;
j++;
}
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]='e';
b[j+4]='t';
b[j+5]='x';
b[j+6]='\0';
printf("\nframe after stuffing:\n");
printf("%s",b);
}

Program Output:
Enter string
MLRITM
Enter position
2
Enter the character
frame after stuffing:
dlestxMdldleLRITMdleetx
2.2 Implement the data link layer farming methods such as and bit stuffing.

Introduction to bit stuffing framing method used in Data Link layer:

The new technique allows data frames to contain an arbitrary number of bits and allows character codes
with an arbitrary no of bits per character. Each frame begins and ends with the special bit pattern,
01111110, called a flag byte. Whenever the sender's data link layer encounters five consecutive ones in
the data, it automatically stuffs a 0 bit into the outgoing bit stream. This bit stuffing is analogous to
character stuffing, in which a DLE is stuffed into the outgoing character stream before DLE in the data.

Program Algorithm:

Begin
Step 1: Read frame length n
Step 2: Repeat step (3 to 4) until i<n(: Read values into the input frame (0’s and
1’s) i.e.
Step 3: initialize I i=0;
Step 4: read a[i] and increment i
Step 5: Initialize i=0, j=0,count =0
Step 6: repeat step (7 to 22) until i<n
Step 7: If a[i] == 1 then
Step 8: b[j] = a[i]
Step 9: Repeat step (10 to 18) until (a[k] =1 and k<n and count <5)
Step 10: Initialize k=i+1;
Step 11: Increment j and b[j]= a[k];
Step 12: Increment count ;
Step 13: if count =5 then
Step 14: increment j,
Step 15: b[j] =0
Step 16: end if
Step 17: i=k;
Step 18: increment k
Step 19: else
Step 20: b[j] = a[i]
Step 21: end if
Step 22: increment I and j
Step 23: print the frame after bit stuffing
Step 24: repeat step (25 to 26) until i< j
Step 25: print b[i]
Step 26: increment i
End
Program Code: // BIT Stuffing program
#include<stdio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame length:");
scanf("%d",&n);
printf("Enter input frame (0's & 1's only):");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=0; count=1; j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1;a[k]==1 && k<n && count<5;k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}}
else
{ b[j]=a[i];}
i++;
j++;
}
printf("After stuffing the frame is:");
for(i=0;i<j;i++)
printf("%d",b[i]);
}

Program Output:
Enter frame length:5
Enter input frame (0's & 1's only):
1
1
1
1
1
After stuffing the frame is:111110
------------------
(program exited with code: 6)
Press return to continue
3. Write a Program to implement data link layer farming method checksum.

3.1 Implement the data link layer framing method such as character count

1. Start
2. Append DLE STX at the beginning of the string
3. Check the data if character is present; if character DLE is present in the string (example DOODLE)
insert another DLE in the string (ex: DOODLEDLE)
4. Transmit DLE ETXat the end of the string
5. Display the string 6. Stop

Program

#include<stdio.h>
#include<string.h>
main()
{
int i,j,k,l,count=0,n; char s[100],cs[50];
clrscr();
printf("\n ENTER THE BIT STRING:");
gets(s);
n=strlen(s);
printf("\nTHE STRING IS\n");
for(i=0;i<n;)
{
if(s[i]==s[i+1])
{
count=2; i++;
while(s[i]==s[i+1])
{ i++;
count++;
}
if(count>=5)
{
printf("$");
if(count<10)
printf("0");
printf("%d%c",count,s[i]);
i++;
}
else
{
for(j=0;j<count;j++)
printf("%c",s[i]);
i++;
}
}
else
{
printf("%c",s[i]);
i++;
}
}
getch();
}

INPUT/OUTPUT:

ENTER THE BIT STRING: 123AAAAAAAAAATYKKKPPPP P

THE STRING IS 123$10ATYKKK$05P


3.2 Implement Error detection method - even and odd parity.

// C program to find parity


// of an integer
# include <stdio.h>
# define bool int

/* Function to get parity of number n. It returns 1


if n has odd parity, and returns 0 if n has even
parity */
bool getParity(unsigned int n)
{
bool parity = 0;
while (n)
{
parity = !parity;
n = n & (n - 1);
}
return parity;
}

/* Driver program to test getParity() */


int main()
{
unsigned int n = 7;
printf("Parity of no %d = %s", n,
(getParity(n)? "odd": "even"));

getchar();
return 0;
}

Output:

Parity of no 7 = odd
4.Write a program for Hamming Code generation for error detection and correction.

4.1 Write a program for Hamming Code generation for error detection.

#include<iostream>
using namespace std;
int main() {
int data[10];
int dataatrec[10],c,c1,c2,c3,i;

cout<<"Enter 4 bits of data one by one\n";


cin>>data[0];
cin>>data[1];
cin>>data[2];
cin>>data[4];

//Calculation of even parity


data[6]=data[0]^data[2]^data[4];
data[5]=data[0]^data[1]^data[4];
data[3]=data[0]^data[1]^data[2];

cout<<"\nEncoded data is\n";


for(i=0;i<7;i++)
cout<<data[i];
cout<<"\n\nEnter received data bits one by one\n";
for(i=0;i<7;i++)
cin>>dataatrec[i];
c1=dataatrec[6]^dataatrec[4]^dataatrec[2]^dataatrec[0];
c2=dataatrec[5]^dataatrec[4]^dataatrec[1]^dataatrec[0];
c3=dataatrec[3]^dataatrec[2]^dataatrec[1]^dataatrec[0];
c=c3*4+c2*2+c1 ;
if(c==0)
{
cout<<"\nNo error while transmission of data\n";
}
else {
cout<<"\nError on position "<<c;
cout<<"\nDatasent : ";
for(i=0;i<7;i++)
cout<<data[i];
cout<<"\nDatareceived : ";
for(i=0;i<7;i++)
cout<<dataatrec[i];
cout<<"\nCorrect message is\n";
//if errorneous bit is 0 we complement it else vice versa
if(dataatrec[7-c]==0)
dataatrec[7-c]=1;
else
dataatrec[7-c]=0;
for (i=0;i<7;i++) {
cout<<dataatrec[i];
}}return 0;
}
Output

Enter 4 bits of data one by one


1
0
1
0

Encoded data is
1010010

Enter received data bits one by one


1
0
1
0
0
1
0

No error while transmission of data


4.2 Write a program for Hamming Code generation

Given a message bit in the form of an array msgBit[], the task is to find the Hamming Code of
the given message bit.

Examples:

Input: S = “0101”

Output:

Generated codeword:
r1 r2 m1 r4 m2 m3 m4
0 1 0 0 1 0 1

Explanation:
Initially r1, r2, r4 is set to ‘0’.
r1 = Bitwise XOR of all bits position that has ‘1’ in its 0th-bit position.
r2 = Bitwise XOR of all bits that has ‘1’ in its 1st-bit position.
r3 = Bitwise XOR of all bits that has ‘1’ in its 2nd-bit position.

Input: S = “0111”
Output:
Generated codeword:
r1 r2 m1 r4 m2 m3 m4
0 0 0 1 1 1 1

Approach: The idea is to first find the number of redundant bits which can be found by
initializing r with 1 and then incrementing it by 1 each time while 2r is smaller than (m + r +
1) where m is the number of bits in the input message. Follow the below steps to solve the
problem:
r
 Initialize r by 1 and increment it by 1 until 2 is smaller than m+r+1.
 Initialize a vector hammingCode of size r + m which will be the length of the
output message.
 Initialize all the positions of redundant bits with -1 by traversing from i = 0 to r –
1 and setting hammingCode [2i – 1] = -1. Then place the input message bits in all
the positions where hammingCode[j] is not -1 in order where 0 <= j < (r + m).
 Initialize a variable one_count with 0 to store the number of ones and then traverse
from i = 0 to (r + m – 1).
 If the current bit i.e., hammingCode[i] is not -1 then find the message bit
containing set bit at log2(i+1)th position by traversing from j = i+2 to r+m by
incrementing one_count by 1 if (j & (1<<x)) is not 0 and hammingCode[j –
1] is 1.
 If for index i, one_count is even, set hammingCode[i] = 0 otherwise
set hammingCode[i] = 1.
 After traversing, print the hammingCode[] vector as the output message
// C program for the above approach

#include <math.h>
#include <stdio.h>

// Store input bits


int input[32];

// Store hamming code


int code[32];

int ham_calc(int, int);


void solve(int input[], int);

// Function to calculate bit for


// ith position
int ham_calc(int position, int c_l)
{
int count = 0, i, j;
i = position - 1;

// Traverse to store Hamming Code


while (i<c_l) {

for (j = i; j <i + position; j++) {

// If current boit is 1
if (code[j] == 1)
count++;
}

// Update i
i = i + 2 * position;
}

if (count % 2 == 0)
return 0;
else
return 1;
}

// Function to calculate hamming code


void solve(int input[], int n)
{
int i, p_n = 0, c_l, j, k;
i = 0;

// Find msg bits having set bit


// at x'th position of number
while (n > (int)pow(2, i) - (i + 1)) {
p_n++;
i++;
}

c_l = p_n + n;

j = k = 0;

// Traverse the msgBits


for (i = 0; i<c_l; i++) {

// Update the code


if (i == ((int)pow(2, k) - 1)) {
code[i] = 0;
k++;
}

// Update the code[i] to the


// input character at index j
else {
code[i] = input[j];
j++;
}
}

// Traverse and update the


// hamming code
for (i = 0; i<p_n; i++) {

// Find current position


int position = (int)pow(2, i);

// Find value at current position


int value = ham_calc(position, c_l);

// Update the code


code[position - 1] = value;
}

// Print the Hamming Code


printf("\nThe generated Code Word is: ");
for (i = 0; i<c_l; i++) {
printf("%d", code[i]);
}
}

// Driver Code
void main()
{
// Given input message Bit
input[0] = 0;
input[1] = 1;
input[2] = 1;
input[3] = 1;

int N = 4;

// Function Call
solve(input, N);
}

Output:
The generated Code Word is: 0001111
5. Implement on a data set of characters the three CRC polynomials – CRC 12, CRC 16 and CRC
CCIP.

Introduction to Cyclic Redundancy Check:

CRC method can detect a single burst of length n, since only one bit per column will be changed, a burst
of length n+1 will pass undetected, if the first bit is inverted, the last bit is inverted and all other bits are
correct. If the block is badly garbled by a long burst or by multiple shorter burst, the probability that any
of the n columns will have the correct parity that is 0.5. so the probability of a bad block being expected
when it should not be 2 power(-n). This scheme sometimes is known as Cyclic Redundancy Code.

5.1 Simulate error correction code (like CRC).

1. A string of n as is appended to the data unit. The length of predetermined divisor is n+ 1.


2. The newly formed data unit 1. A string of n as is appended to the data unit. The length of
predetermined divisor is n+ 1.
i.e. original data + string of n as are divided by the divisor using binary division and remainder
is obtained. This remainder is called CRC.
3. Now, string of n Os appended to data unit is replaced by the CRC remainder (which is also
of n bit).
4. The data unit + CRC is then transmitted to receiver.
5. The receiver on receiving it divides data unit + CRC by the same divisor & checks the
remainder.
6. If the remainder of division is zero, receiver assumes that there is no error in data and it
accepts it.
7. If remainder is non-zero then there is an error in data and receiver rejects it.

Program

#include<stdio.h>
#include<math.h>
#include<conio.h>
#include<string.h>
main()
{

int i,j,k,m,n,cl;
char a[10],b[100],c[100];
clrscr();
printf("\n ENTER POLYNANOMIAL:");
scanf("%s",a);
printf("\n ENTER THE FRAME:");
scanf("%s",b);
m=strlen(a);
n=strlen(b);
for(i=0;i<m;i++) /* To eliminat first zeros in polynomial */
{
if(a[i]=='1')
{
m=m-i; break;
}
}
for(k=0;k<m;k++) /* To Adjust the polynomial */
a[k]=a[k+i];

cl=m+n-1;

for(i=0;i<n;i++) /* To copy the original frame to c[]*/


c[i]=b[i];
for(i=n;i<cl;i++) /* To add n-1 zeros at the end of frame */
c[i]='0';
c[i]='\0'; /*To make it as a string */
for(i=0;i<n;i++) /* To set polynomial remainder at end of c[]*/
if(c[i]=='1')
{
for(j=i,k=0;k<m;k++,j++)
if(a[k]==c[j])
c[j]='0';
else c[j]='1';
}
for(i=0;i<n;i++) /* To copy original data in c[] */
c[i]=b[i];
printf("\n THE MESSAGE IS: %s",c);
getch();
}

Output

ENTER POLYNANOMIAL:1011
ENTER THE FRAME:10011101
THE MESSAGE IS: 10011101011
5.2.Write a program for error detecting code using CRC-CCITT (16-bits).

Theory

It does error checking via polynomial division. In general, a bit string


b bb …b bb
n-1 n-2
n-3
As
210

Ex: -

bn-1Xn-1 + bn-2 Xn-2 + bn-3 Xn-3 + …b2 X2 + b1 X1 + b0 10010101110


As
X10 + X7 + X5 + X3 + X2 + X1
All computations are done in modulo 2

Algorithm:-

1. Given a bit string, append 0S to the end of it (the number of 0s is the same as the degree of the
generator polynomial) let B(x) be the polynomial corresponding to B.
2. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine the
remainder R(x). This division is to be done using Modulo 2 Division.
3. Define T(x) = B(x) –R(x)
(T(x)/G(x) => remainder 0)
4. Transmit T, the bit string corresponding to T(x).
5. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The
receiver divides 1(x) by G(x). If there is a 0 remainder, the receiver concludes T = T’ and no
error T
occurred otherwise, the receiver concludes an error occurred and requires a retransmission.

#include<stdio.h>
#include<string.h>
#include<conio.h>
#define N strlen(g)
char t[128], cs[128], g[]="10001000000100001";
int a, e, c;
void xor() {
for(c=1;c<N;c++) cs[c]=((cs[c]==g[c])?'0':'1');
}
void crc() {
for(e=0;e<N;e++) cs[e]=t[e];
do {
if(cs[0]=='1') xor();
for(c=0;c<N-1;c++) cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}
void main() {
clrscr();
printf("\nEnter poly : "); scanf("%s",t);
printf("\nGenerating Polynomial is : %s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++) t[e]='0';
printf("\nModified t[u] is : %s",t);
crc();
printf("\nChecksum is : %s",cs);
for(e=a;e<a+N-1;e++) t[e]=cs[e-a];
printf("\nFinal Codeword is : %s",t);
printf("\nTest Error detection 0(yes) 1(no) ? : ");
scanf("%d",&e);
if(e==0) {
printf("Enter position where error is to inserted : ");
scanf("%d",&e);
t[e]=(t[e]=='0')?'1':'0';
printf("Errorneous data : %s\n",t);
}
crc();
for (e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1) printf("Error detected.");
else printf("No Error Detected.");
getch();
}

Output

Enter poly : 1011101


Generating Polynomial is : 10001000000100001
Modified t[u] is : 10111010000000000000000
Checksum is : 1000101101011000
Final Codeword is : 10111011000101101011000
Test Error detection 0(yes) 1(no) ? : 0
Enter position where you want to insert error : 3
Errorneousdata : 10101011000101101011000
Error detected.
Enter poly : 1011101
Generating Polynomial is : 10001000000100001
Modified t[u] is : 10111010000000000000000
Checksum is : 1000101101011000
Final Codeword is : 10111011000101101011000
Test Error detection 0(yes) 1(no) ? : 1
No Error Detected.
6. Write a Program to implement Sliding window protocol for Goback N.

WHAT IS GO BACK-N?

The Go Back-N ARQ or Go Back Automatic Repeat Request is a way to implement sliding
window protocol. This protocol is used for flow control in networking and is a part of the
data-link layer. The sender’s window is of size N and the receiver’s window size is always
one.
The window sizes for Go Back-N are:

1. SENDER WINDOW SIZE (WS)

The WS is equal to N. If we say the protocol is GB-4, then WS = 4. In order to implement


pipelining, the window size should always be greater than one. If window size is one, the
protocol reduces to stop-and -wait protocol.

2. RECEIVER WINDOW SIZE (WR)

WR is always one in Go Back-N.

Now we will understand how Go Back-N actually works with the help of an example. In the
diagram below the sender’s window has a size of four, or Go Back-4. Assume that we’ve
plenty of sequence numbers, for the sake of explanation. Now the sender has despatched the
packets zero, one, two and three. After acknowledging the packets zero and one, the receiver
is now awaiting packet two and the sender window has additionally slided to similarly
transmit the packets four and five.

Now suppose packet two is misplaced within the network. The receiver will discard all the
packets which the sender has transmitted after packet two as it’s awaiting the packet with
sequence number two. On the sender side, for every packet dispatched there is a time-out
timer to expire for packet range two. Now from the remaining transmitted packet five the
sender will go back to the packet with sequence number two within the current window and
transmit all the packets until packet number five. That’s why it is referred to as Go Back-N.
In the Go Back-N approach the sender has to move back N places from the closing
transmitted packet within the unacknowledged window and not from the factor where the
packet is misplaced.

ACKNOWLEDGEMENTS

There are 2 kinds of acknowledgments, namely:

1.Cumulative ACK
2.Independent ACK

GBN makes use of cumulative acknowledgement. On the receiver side, it starts an


acknowledgment timer when any packet is received, which is constant, and when it expires,
it’s going to send a cumulative ACK for the range of packets received in the interval of the
timer. If the receiver has obtained N packets, then the acknowledgement range might be N+1.
A crucial factor is that the ACK timer will now not begin after the expiration of the primary
timer, but after the receiver has received a packet. The timer at the sender side must be
greater than the ACK timer.
6. Sliding Window Protocol Program

#include<stdio.h>
int main()
{
int w,i,f,frames[50];
printf("Enter window size: ");
scanf("%d",&w);
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);
printf("\nEnter %d frames: ",f);
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);

printf("\nWith sliding window protocol the frames will be sent in the following manner (assuming no
corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for acknowledgement sent by the
receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by sender\n\n");
}
else
printf("%d ",frames[i]);
}

if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by sender\n");

return 0;
}

Output

Enter window size: 3


Enter number of frames to transmit: 5
Enter 5 frames: 12 5 89 4 6

With sliding window protocol the frames will be sent in the following manner (assuming no corruption
of frames)
After sending 3 frames at each stage sender waits for acknowledgement sent by the receiver

12 5 89
Acknowledgement of above frames sent is received by sender
46
Acknowledgement of above frames sent is received by sender
7. Sliding window protocol for Goback N

#include<bits/stdc++.h>
#include<ctime>
#definell long long int
using namespace std;
void transmission(ll&i, ll& N, ll&tf, ll&tt) {
while (i<= tf) {
int z = 0;
for (int k = i; k <i + N && k <= tf; k++) {
cout<< "Sending Frame " << k << "..." <<endl;
tt++;
}
for (int k = i; k <i + N && k <= tf; k++) {
int f = rand() % 2;
if (!f) {
cout<< "Acknowledgment for Frame " << k << "..." <<endl;
z++;
} else {
cout<< "Timeout!! Frame Number : " << k << " Not Received" <<endl;
cout<< "Retransmitting Window..." <<endl;
break;
}
}
cout<< "\n";
i = i + z;
}
}

int main() {
lltf, N, tt = 0;
srand(time(NULL));
cout<< "Enter the Total number of frames : ";
cin>>tf;
cout<< "Enter the Window Size : ";
cin>>N;
lli = 1;
transmission(i, N, tf, tt);
cout<< "Total number of frames which were sent and resent are : " <<tt<<
endl;
return 0;
}

OUTPUT:

Enter the Total number of frames : 12


Enter the Window Size : 4
Sending Frame 1…
Sending Frame 2…
Sending Frame 3…
Sending Frame 4…
Timeout!! Frame Number : 1 Not Received
Retransmitting Window…

Sending Frame 1…
Sending Frame 2…
Sending Frame 3…
Sending Frame 4…
Acknowledgment for Frame 1…
Timeout!! Frame Number : 2 Not Received
Retransmitting Window…

Sending Frame 2…
Sending Frame 3…
Sending Frame 4…
Sending Frame 5…
Timeout!! Frame Number : 2 Not Received
Retransmitting Window…

Sending Frame 2…
Sending Frame 3…
Sending Frame 4…
Sending Frame 5…
Acknowledgment for Frame 2…
Acknowledgment for Frame 3…
Acknowledgment for Frame 4…
Timeout!! Frame Number : 5 Not Received
Retransmitting Window…

Sending Frame 5…
Sending Frame 6…
Sending Frame 7…
Sending Frame 8…
Timeout!! Frame Number : 5 Not Received
Retransmitting Window…

Sending Frame 5…
Sending Frame 6…
Sending Frame 7…
Sending Frame 8…
Acknowledgment for Frame 5…
Timeout!! Frame Number : 6 Not Received
Retransmitting Window…

Sending Frame 6…
Sending Frame 7…
Sending Frame 8…
Sending Frame 9…
Acknowledgment for Frame 6…
Timeout!! Frame Number : 7 Not Received
Retransmitting Window…

Sending Frame 7…
Sending Frame 8…
Sending Frame 9…
Sending Frame 10…
Acknowledgment for Frame 7…
Acknowledgment for Frame 8…
Acknowledgment for Frame 9…
Acknowledgment for Frame 10…

Sending Frame 11…


Sending Frame 12…
Timeout!! Frame Number : 11 Not Received
Retransmitting Window…

Sending Frame 11…


Sending Frame 12…
Timeout!! Frame Number : 11 Not Received
Retransmitting Window…

Sending Frame 11…


Sending Frame 12…
Acknowledgment for Frame 11…
Acknowledgment for Frame 12…

Total number of frames transmitted(sent + resent) are : 38


8. Write a Program to implement Stop and Wait Protocol.
8.1.. Write a Program to implement Sliding window protocol for Selective repeat.
implement
9. Write a program for congestion control using leaky bucket algorithm

Leaky Bucket

Problem Statement

Write
ite a program for congestion control using Leaky bucket algorithm.

Theory

The congesting control algorithms are basically divided into two groups: open loop and closed
loop. Open loop solutions attempt to solve the problem by good design, in essence, to make m sure
it does not occur in the first place. Once the system is up and running, midcourse corrections are
not made. Open loop algorithms are further divided into ones that act at source versus ones that
act at the destination.
lutions are based on the concept of a feedback loop if there is any
In contrast, closed loop solutions
congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback
and implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of
congestion by making local observation, such as the time needed for acknowledgment to come
back.
The presence of congestion means that the load is (temporarily) gr eater than the resources (in
greater
part of the system) can handle. For subnets that use virtual circuits internally, these methods can
be used at the network layer.
Another open loop method to help manage congestion is forcing the packet to be transmitted at a
ore predictable rate. This approach to congestion management is widely used in ATM
more
networks and is called traffic shaping.
The other method is the leaky bucket algorithm. Each host is connected to the network by an
interface containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue
when it is full, the packet is discarded. In other words, if one or more process are already queued,
the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single
server queuing system with constant service time.
The host is allowed to put one packet per clock tick onto the network. This mechanism turns an
uneven flow of packet from the user process inside the host into an even flow of packet onto the
network, smoothing out bursts and greatly reducing the chances of congestion.
Program:

#include<iostream.h>
#include<dos.h>
#include<stdlib.h>
#definebucketSize 512
void bktInput(int a,int b) {
if(a>bucketSize)
cout<<"\n\t\tBucket overflow";
else {
delay(500);
while(a>b){
cout<<"\n\t\t"<<b<<" bytes outputted.";
a-=b;
delay(500);
}
if (a>0) cout<<"\n\t\tLast "<<a<<" bytes sent\t";
cout<<"\n\t\tBucket output successful";
}
}
void main() {
int op, pktSize;
randomize();
cout<<"Enter output rate : "; cin>>op;
for(int i=1;i<=5;i++){
delay(random(1000));
pktSize=random(1000);
cout<<"\nPacket no "<<i<<"\tPacket size = "<<pktSize;
bktInput(pktSize,op);
}
}

Output

Enter output rate : 100


Packet no 0 Packet size = 3
Bucket output successful
Last 3 bytes sent
Packet no 1 Packet size = 33
Bucket output successful
Last 33 bytes sent
Packet no 2 Packet size = 117
Bucket output successful
100 bytes outputted.
Last 17 bytes sent
Packet no 3 Packet size = 95
Bucket output successful
Last 95 bytes sent
Packet no 4 Packet size = 949
Bucket overflow
10. Write a Program to implement Dijkstra‘s algorithm to compute the Shortest path through a graph.

Definition

The Dijkstra’s algorithm finds the shortest path from a particular node, called the source node to
every other node in a connected graph. It produces a shortest path tree with the source node as
the root. It is profoundly used in computer networks to generate optimal routes with the aim of
minimizing routing costs.

Dijkstra’s Algorithm

Input − A graph representing the network; and a source node, s


Output − A shortest path tree, spt[], with s as the root node.

The Dijikstra’s algorithm is a greedy algorithm to find the shortest path from the source vertex of the
graph to the root node of the graph.

Algorithm

Step 1 : Create a set shortPath to store vertices that come in the way of the shortest path tree.
Step 2 : Initialize all distance values as INFINITE and assign distance values as 0 for source
vertex so that it is picked first.
Step 3 : Loop until all vertices of the graph are in the shortPath.
Step 3.1 : Take a new vertex that is not visited and is nearest.
Step 3.2 : Add this vertex to shortPath.
Step 3.3 : For all adjacent vertices of this vertex update distances. Now check every adjacent
vertex of V, if sum of distance of u and weight of edge is elss the update it.

Program

#include <limits.h>
#include <stdio.h>
#define V 9
int minDistance(int dist[], bool sptSet[])
{
int min = INT_MAX, min_index;
for (int v = 0; v < V; v++)
if (sptSet[v] == false &&dist[v] <= min)
min = dist[v], min_index = v;
return min_index;
}
int printSolution(int dist[], int n)
{
printf("Vertex Distance from Source
");
for (int i = 0; i< V; i++)
printf("%d \t %d
", i, dist[i]);
}
void dijkstra(int graph[V][V], int src)
{
int dist[V];
bool sptSet[V];
for (int i = 0; i< V; i++)
dist[i] = INT_MAX, sptSet[i] = false;
dist[src] = 0;
for (int count = 0; count < V - 1; count++)
{
int u = minDistance(dist, sptSet);
sptSet[u] = true;
for (int v = 0; v < V; v++)
if (!sptSet[v] && graph[u][v] &&dist[u] != INT_MAX &&dist[u] + graph[u][v] <dist[v])
dist[v] = dist[u] + graph[u][v];
}
printSolution(dist, V);
}
int main() {
int graph[V][V] = { { 0, 6, 0, 0, 0, 0, 0, 8, 0 },
{ 6, 0, 8, 0, 0, 0, 0, 13, 0 },
{ 0, 8, 0, 7, 0, 6, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 6, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 13, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 }
};
dijkstra(graph, 0);
return 0;
}

Output

Vertex Distance from Source


00
16
2 14
3 21
4 21
5 11
69
78
8 15
Example

The working of the algorithm can be best understood using an example. Consider the following
graph having nodes marked from A to G, connected by weighted edges as follows −

The initializations will be as follows −


 dist[7]={0,∞,∞,∞,∞,∞,∞}
 Q={A,B,C,D,E,F,G}
 S𝑆= ∅
Pass 1 − We choose node A from Q since it has the lowest dist[] value of 0 and put it in S. The
neighbouring nodes of A are B and C. We update dist[] values corresponding to B and C
according to the algorithm. So the values of the data structures become −
 dist[7]={0,5,6,∞,∞,∞,∞}
 Q={B,C,D,E,F,G}
 S={A}
The distances and shortest paths after this pass are shown in the following graph. The green
node denotes the node already added to S −

Pass 2 − We choose node B from Q since it has the lowest dist[] value of 5 and put it in S. The
neighbouring nodes of B are C, D and E. We update dist[] values corresponding to C, D and E
according to the algorithm. So the values of the data structures become −
 dist[7]={0,5,6,12,13,∞,∞}
 Q={C,D,E,F,G}
 S={A,B}
The distances and shortest paths after this pass are −
Pass 3 − We choose node C from Q since it has the lowest dist[] value of 6 and put it in S. The
neighbouring nodes of C are D and F. We update dist[] values corresponding to D and F. So the
values of the data structures become −
 dist[7]={0,5,6,8,13,10,∞}
 Q={D,E,F,G}
 S={A,B,C}
The distances and shortest paths after this pass are −

Pass 4 − We choose node D from Q since it has the lowest dist[] value of 8 and put it in S. The
neighbouring nodes of D are E, F and G. We update dist[] values corresponding to E, F and G.
So the values of the data structures become −
 dist[7]={0,5,6,8,10,10,18}
 Q={E,F,G}
 S={A,B,C,D}
The distances and shortest paths after this pass are −
Pass 5 − We can choose either node E or node F from Q since both of them have the
lowest dist[] value of 10. We select any one of them, say E, and put it in S. The
neighbouringnodes of D is G. We update dist[] values corresponding to G. So the values of the
data structures become −
 dist[7]={0,5,6,8,10,10,13}
 Q={F,G}
 S={A,B,C,D,E}
The distances and shortest paths after this pass are −

Pass 6 − We choose node F from Q since it has the lowest dist[] value of 10 and put it in S. The
neighbouringnodes of F is G. The dist[] value corresponding to G is less than that through F. So
it remains same. The values of the data structures become −
 dist[7]={0,5,6,8,10,10,13}
 Q={G}
 S={A,B,C,D,E,F}
The distances and shortest paths after this pass are −

Pass 7 − There is just one node in Q. We remove it from Q put it in S. The dist[] array needs no
change. Now, Q becomes empty, S contains all the nodes and so we come to the end of the
algorithm. We eliminate all the edges or routes that are not in the path of any route. So the
shortest path tree from source node A to all other nodes are as follows −
11. Write a Program to implement Distance vector routing algorithm by obtaining routing
table at each node (Take an example subnet graph with weights indicating delay between
nodes).

Distance Vector Routing

Problem Statement

Write a program for distance vector algorithm to find suitable path for transmission.

Theory

Routing algorithm is a part of network layer software which is responsible for deciding which output
line an incoming packet should be transmitted on. If the subnet uses datagram internally, this
decision must be made anew for every arriving data packet since the best route may have changed
since last time. If the subnet uses virtual circuits internally, routing decisions are made only when a
new established route is being set up. The latter case is sometimes called session routing, because a
rout remains in force for an entire user session (e.g., login session at a terminal or a file).
Routing algorithms can be grouped into two major classes: adaptive and nonadaptive. Nonadaptive
algorithms do not base their routing decisions on measurement or estimates of current traffic and
topology. Instead, the choice of route to use to get from I to J (for all I and J) is compute in advance,
offline, and downloaded to the routers when the network ids booted. This procedure is sometime
called static routing.
Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology,
and usually the traffic as well. Adaptive algorithms differ in where they get information (e.g., locally,
from adjacent routers, or from all routers), when they change the routes (e.g., every T sec, when the
load changes, or when the topology changes), and what metric is used for optimization (e.g.,
distance, number of hops, or estimated transit time).
Two algorithms in particular, distance vector routing and link state routing are the most popular.
Distance vector routing algorithms operate by having each router maintain a table (i.e., vector) giving
the best known distance to each destination and which line to get there. These tables are updated by
exchanging information with the neighbors.
The distance vector routing algorithm is sometimes called by other names, including the distributed
Bellman-Ford routing algorithm and the Ford-Fulkerson algorithm, after the researchers who
developed it (Bellman, 1957; and Ford and Fulkerson, 1962). It was the original ARPANET routing
algorithm and was also used in the Internet under the RIP and in early versions of DECnet and
Novell’s IPX. AppleTalk and Cisco routers use improved distance vector protocols.
In distance vector routing, each router maintains a routing table indexed by, and containing one entry
for, each router in subnet. This entry contains two parts: the preferred out going line to use for that
destination, and an estimate of the time or distance to that destination. The metric used might be
number of hops, time delay in milliseconds, total number of packets queued along the path, or
something similar.
The router is assumed to know the “distance” to each of its neighbor. If the metric is hops, the
distance is just one hop. If the metric is queue length, the router simply examines each queue. If the
metric is delay, the router can measure it directly with special ECHO packets hat the receiver just
time stamps and sends back as fast as possible.
The Count to Infinity Problem.
Distance vector routing algorithm reacts rapidly to good news, but leisurely to bad news. Consider a
router whose best route to destination X is large. If on the next exchange neighbor A suddenly
reports ashort delay to X, the router just switches over to using the line to A to send traffic to X. In
one vector exchange, the good news is processed.
To see how fast good news propagates, consider the five node (linear) subnet of following
followi figure,
where the delay metric is the number of hops. Suppose A is down initially and all the other routers
know this. In other words, they have all recorded the delay to A as infinity.

Many ad hoc solutions to the count to infinity problem have been been proposed in the literature, each one
more complicated and less useful than the one before it. The split horizon algorithm works the same
way as distance vector routing, except that the distance to X is not reported on line that packets for X
are sent on (actually, it is reported as infinity). In the initial state of right figure, for example, C tells
D the truth about distance to A but C tells B that its distance to A is infinite. Similarly, D tells the
truth to E but lies to C.

Program

#include <stdlib.h>
#include <time.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#defineFSize 3
typedef struct packet{int SeqNum; char Data[FSize+1];}packet;
struct packet *readdata, *transdata;
int divide(char *msg) {
int msglen, NoOfPacket, i, j;
msglen = strlen(msg);
NoOfPacket = msglen/FSize;
if ((msglen%FSize)!=0) NoOfPacket++;
readdata = (struct packet *)malloc(sizeof(packet) * NoOfPacket);
for(i = 0; i<NoOfPacket; i++) {
readdata[i].SeqNum = i + 1;
for (j = 0; (j <FSize) && (*msg != '\0');
' j++, msg++)
readdata[i].Data[j] = *msg;
readdata[i].Data[j] = '\0';
}
printf("\nThe
nThe Message has been divided as follows\n");
follows
printf("\nPacket No. Data\n\n");
n");
for (i = 0; i<NoOfPacket; i++)
printf(" %2d %s\n",
n", readdata[i].SeqNum,
readdata[i].Data);
return NoOfPacket;
}
void shuffle(int NoOfPacket) {
int *Status;
int i, j, trans;
randomize();
Status=(int * )calloc(NoOfPacket, sizeof(int));
transdata = (struct packet *)malloc(sizeof(packet) * NoOfPacket);
for (i = 0; i<NoOfPacket;) {
trans = rand()%NoOfPacket;
if (Status[trans]!=1) {
transdata[i].SeqNum = readdata[trans].SeqNum;
strcpy(transdata[i].Data, readdata[trans].Data);
i++; Status[trans] = 1;
}
}
free(Status);
}
void sortframes(int NoOfPacket) {
packet temp;
int i, j;
for (i = 0; i<NoOfPacket; i++)
for (j = 0; j <NoOfPacket – i-1; j++)
if (transdata[j].SeqNum>transdata[j + 1].SeqNum) {
temp.SeqNum = transdata[j].SeqNum;
strcpy(temp.Data, transdata[j].Data);
transdata[j].SeqNum = transdata[j + 1].SeqNum;
strcpy(transdata[j].Data, transdata[j + 1].Data);
transdata[j + 1].SeqNum = temp.SeqNum;
strcpy(transdata[j + 1].Data, temp.Data);
}
}
void receive(int NoOfPacket) {
int i;
printf("\nPackets received in the following order\n");
for (i = 0; i<NoOfPacket; i++) printf("%4d", transdata[i].SeqNum);
sortframes(NoOfPacket);
printf("\n\nPackets in order after sorting..\n");
for (i = 0; i<NoOfPacket; i++) printf("%4d", transdata[i].SeqNum);
printf("\n\nMessage received is :\n");
for (i = 0; i<NoOfPacket; i++) printf("%s", transdata[i].Data);
}

void main()
{
char *msg;
int NoOfPacket;
clrscr();
printf("\nEnter The message to be Transmitted :\n");
scanf("%[^\n]", msg);
NoOfPacket = divide(msg);
shuffle(NoOfPacket);
receive(NoOfPacket);
free(readdata);
free(transdata);
getch();
}

Output

Enter The messgae to be Transmitted :


hi, it was nice meeting u on sunday
The Message has been divided as follows
Packet No. Data
1 hi,
2 it
3 wa
4sn
5 ice
6 me
7 eti
8 ng
9uo
10 n s
11 und
12 ay
Packets received in the following order
4 2 6 3 5 1 8 9 11 7 12 10
Packets in order after sorting..
1 2 3 4 5 6 7 8 9 10 11 12
Message received is :
hi, it was nice meeting u on sunday
12. Write a Program to implement Broadcast tree by taking subnet of hosts

/* PROGRAM TO IMPLEMENT BROADCAST ROUTING ALGORITHM*/

#include
int a[10][10],n;
main()
{
int i,j,root;
clrscr();
printf(“Enter no.of nodes:”);
scanf(“%d”,&n);
printf(“Enter adjacent matrix\n”);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
printf(“Enter connecting of %d–>%d::”,i,j);
scanf(“%d”,&a[i][j]);
}
printf(“Enter root node:”);
scanf(“%d”,&root);
adj(root);
}
adj(int k)
{
int i,j;
printf(“Adjacent node of root node::\n”);
printf(“%d\n\n”,k);
for(j=1;j<=n;j++)
{
if(a[k][j]==1 || a[j][k]==1)
printf(“%d\t”,j);
}
printf(“\n”);
for(i=1;i<=n;i++)
{
if((a[k][j]==0) && (a[i][k]==0) && (i!=k))
printf(“%d”,i);
}
}

OUTPUT

Enter no.of nodes:5


Enter adjacent matrix
Enter connecting of 1–>1::0
Enter connecting of 1–>2::1
Enter connecting of 1–>3::1
Enter connecting of 1–>4::0
Enter connecting of 1–>5::0
Enter connecting of 2–>1::1
Enter connecting of 2–>2::0
Enter connecting of 2–>3::1
Enter connecting of 2–>4::1
Enter connecting of 2–>5::0
Enter connecting of 3–>1::1
Enter connecting of 3–>2::1
Enter connecting of 3–>3::0
Enter connecting of 3–>4::0
Enter connecting of 3–>5::0
Enter connecting of 4–>1::0
Enter connecting of 4–>2::1
Enter connecting of 4–>3::0
Enter connecting of 4–>4::0
Enter connecting of 4–>5::1
Enter connecting of 5–>1::0
Enter connecting of 5–>2::0
Enter connecting of 5–>3::0
Enter connecting of 5–>4::1
Enter connecting of 5–>5::0

Enter root node:2

Adjacent node of root node::

134

5
Wireshark
13. What is Wireshark?

Wireshark is a network packet analyzer. A network packet analyzer presents captured packet
data in as much detail as possible.

You could think of a network packet analyzer as a measuring device for examining what’s
happening inside a network cable, just like an electrician uses a voltmeter for examining what’s
happening inside an electric cable (but at a higher level, of course).

In the past, such tools were either very expensive, proprietary, or both. However, with the advent
of Wireshark, that has changed. Wireshark is available for free, is open source, and is one of the
best packet analyzers available today.

Features

The following
llowing 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
packet capture 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.
Searchh for packets on many criteria.
Colorize packet display based on filters.
Create various statistics.
i. Capturing your traffic with Wireshark

After starting Wireshark, do the following:

1. Select Capture | Interfaces


2. Select the interface on which packets need to be captured. This will usually be the
interface where the Packet/s column is constantly changing, which would indicate
the presence of live traffic). If you have multiple network interface cards (i.e. LAN
card and Wi-Fi adapter) you may need to check with your IT administrator to
determine the right interface.
3. Click the Start button to start the capture.
4. Recreate the problem. The capture dialog should show the number of packets
increasing. Try to avoid running any other internet applications while capturing,
closing other browsers, Instant messengers etc.
5. Once the problem which is to be analyzed has been reproduced, click on Stop. It
may take a few seconds for Wireshark to display the packets captured.
6. Save the packet trace in the default format. Click on the File menu option and
select Save As. By default Wireshark will save the packet trace in libpcap format. This
is a filename with a.pcap extension.

ii. Starting Wire shark

The following methods can be used to start capturing packets with Wireshark:

You can double-click on an interface in the welcome screen.



You can select an interface in the welcome screen, then select Capture → Start or

click the first toolbar button.
 You can get more detailed information about available interfaces using Section 4.5,
“The “Capture Options” Dialog Box” (Capture → Options…).
 If you already know the name of the capture interface you can start Wireshark from
the command line:
$ wireshark -i eth0 -k

Viewing Packets You Have Captured

Once you have captured some packets or you have opened a previously saved capture file, you
can view the packets that are displayed in the packet list pane by simply clicking on a packet in
the packet list pane, which will bring up the selected packet in the tree view and byte view panes.

You can then expand any part of the tree to view detailed information about each protocol in
each packet. Clicking on an item in the tree will highlight the corresponding bytes in the byte
view. An example with a TCP packet selected is shown in Figure 6.1, “Wireshark with a TCP
packet selected for viewing”. It also has the Acknowledgment number in the TCP header
selected, which shows up in the byte view as the selected bytes.
IV. Analysis and Statistics & Filters.

.9, “Statistics menu items”


The Wireshark Statistics menu contains the fields shown in Table 3.9,
IPv4 Statistics

Internet Protocol version 4 (IPv4) is a core protocol for the internet layer. It uses 32-bit addresses
and allows packets routing from one source host to the next one.

The Statistics → IPv4 menu provides the packet counter by submenus:

 All Addresses. Divides data by IP address.


 Destination and Ports. Divides data by IP address, and further by IP protocol type, such
as TCP, UDP, and others. It also shows port number.
 IP Protocol Types. Divides data by IP protocol type.
 Source and Destination addresses. Divides data by source and destination IP address.

You can see similar statistics in the Statistics → Conversations and Statistics → Endpoints menus.

Filtering while capturing

Wireshark supports limiting the packet capture to packets that match a capture filter. Wireshark
capture filters are written in libpcap filter language. Below is a brief overview of the libpcap filter
language’s syntax. Complete documentation can be found at the pcap-filter man page. You can find
many Capture Filter examples at https://gitlab.com/wireshark/wireshark/wikis/CaptureFilters.

You enter the capture filter into the “Filter” field of the Wireshark “Capture Options” dialog box, as
shown in Figure 4.3, “The “Capture Options” input tab”.

A capture filter takes the form of a series of primitive expressions connected by conjunctions
(and/or) and optionally preceded by not:

[not] primitive [and|or [not] primitive ...]

An example is shown in Example 4.1, “A capture filter for telnet that captures traffic to and from a
particular host”.

Reference :Wireshark User’s GuideVersion 4.1.0


14. How to run Nmap scan

What is Nmap?

Nmap, short for Network Mapper, is a network discovery and security auditing tool. It is known for
its simple and easy to remember flags that provide powerful scanning options. Nmap is widely used
by network administrators to scan for:

 Open ports and services


 Discover services along with their versions
 Guess the operating system running on a target machine
 Get accurate packet routes till the target machine
 Monitoring hosts

Nmap Scan Types

A variety of scans can be performed using Nmap. Below are the types of scans:

TCP SCAN

A TCP scan is generally used to check and complete a three-way handshake between you and a
chosen target system. A TCP scan is generally very noisy and can be detected with almost little to no
effort. This is “noisy” because the services can log the sender IP address and might trigger Intrusion
Detection Systems.

UDP SCAN

UDP scans are used to check whether there is any UDP port up and listening for incoming requests
on the target machine. Unlike TCP, UDP has no mechanism to respond with a positive
acknowledgment, so there is always a chance for a false positive in the scan results. However, UDP
scans are used to reveal Trojan horses that might be running on UDP ports or even reveal hidden
RPC services. This type of scan tends to be quite slow because machines, in general, tend to slow
down their responses to this kind of traffic as a precautionary measure.

SYN SCAN

This is another form of TCP scan. The difference is unlike a normal TCP scan, nmap itself crafts a syn
packet, which is the first packet that is sent to establish a TCP connection. What is important to
note here is that the connection is never formed, rather the responses to these specially crafted
packets are analyzed by Nmap to produce scan results.

ACK SCAN

ACK scans are used to determine whether a particular port is filtered or not. This proves to be
extremely helpful when trying to probe for firewalls and their existing set of rules. Simple packet
filtering will allow established connections (packets with the ACK bit set), whereas a more
sophisticated stateful firewall might not.
FIN SCAN

Also a stealthy scan, like the SYN scan, but sends a TCP FIN packet instead. Most but not all
computers will send an RST packet (reset packet) back if they get this input, so the FIN scan can
show false positives and negatives, but it may get under the radar of some IDS programs and other
countermeasures.

NULL SCAN

Null scans are extremely stealthy scan and what they do is as the name suggests — they set all the
header fields to null. Generally, this is not a valid packet and a few targets will not know how to deal
with such a packet. Such targets are generally some version of windows and scanning them with
NULL packets may end up producing unreliable results. On the other hand, when a system is not
running windows this can be used as an effective way to get through.

XMAS SCAN

Just like null scans, these are also stealthy in nature. Computers running windows will not respond
to Xmas scans due to the way their TCP stack is implemented. The scan derives its name from the
set of flags that are turned on within the packet that is sent out for scanning. XMAS scans are used
to manipulate the PSH, URG and FIN flags that can be found in the TCP header.

RPC SCAN

RPC scans are used to discover machines that respond to Remote Procedure Call services (RPC). RPC
allows commands to be run on a certain machine remotely, under a certain set of connections. RPC
service can run on an array of different ports, hence, it becomes hard to infer from a normal scan
whether RPC services are running or not. It is generally a good idea to run an RPC scan from time to
time to find out where you have these services running.

IDLE SCAN

IDLE scan is the stealthiest of all scans discussed in this nmap tutorial, as the packets are bounced
off an external host. Control over the host is generally not necessary, but the host needs to meet a
specific set of conditions. It is one of the more controversial options in Nmap since it only has a use
for malicious attacks.

Nmap Commands

In this section of Nmap Tutorial, I’ll be listing down the various commands you can use in Nmap
along with their flag and usage description with an example on how to use it.

Scanning Techniques

Flag Use Example

-sS TCP syn port scan nmap -sS 192.168.1.1


-sT TCP connect port scan nmap -sT 192.168.1.1

–sU UDP port scan nmap –sU 192.168.1.1

–sA TCP ack port scan nmap –sA 192.168.1.1

Flag Use Example


-Pn only port scan nmap -Pn192.168.1.1
-sn only host discover nmap -sn192.168.1.1
-PR arp discovery on a local network nmap -PR192.168.1.1
-n disable DNS resolution nmap -n 192.168.1.1

Port Specification

Flag Use Example


-p specify a port or port range nmap -p 1-30 192.168.1.1
-p- scan all ports nmap -p- 192.168.1.1
-F fast port scan nmap -F 192.168.1.1
Service Version and OS Detection

Flag Use Example


-sV detect the version of services running nmap -sV 192.168.1.1
-A aggressive scan nmap -A 192.168.1.1
-O detect operating system of the target nmap -O 192.168.1.1

Timing and Performance

Flag Use Example


-T0 paranoid IDS evasion nmap -T0 192.168.1.1
-T1 sneaky IDS evasion nmap -T1 192.168.1.1
-T2 polite IDS evasion nmap -T2 192.168.1.1
-T3 normal IDS evasion nmap -T3 192.168.1.1
-T4 aggressive speed scan nmap -T4 192.168.1.1
-T5 insane speed scan nmap -T5 192.168.1.1

NSE Scripts

Flag Use Example


-sC default script scan nmap -sC 192.168.1.1
–script banner banner grabbing nmap –script banner 192.168.1.1

IDS Evasion

Flag Use Example


-f use fragmented IP packets nmap -f 192.168.1.1
-D decoy scans nmap -D 192.168.1.1
-g use a given source port number nmap -g 22 192.168.1.1

Nmap is to keep the most common usage simple, while retaining the flexibility for custom and
advanced scans. This is accomplished with the command-line interface by offering dozens of
options, but choosing sane defaults when they are not specified. A newbie can start out with a
command as simple as nmap <target>. Meanwhile, advanced users sometimes specify so many
options that their terminal line wraps around.

A similar balance must be struck with command output. The most important results should stick out
even to the occasional user who hasn't even read the man page. Yet the output should be
comprehensive and concise enough to suit professional penetration testers who run Nmap against
thousands of machines daily. Users smart enough to read this book or the Nmap source code
benefit from greater control of the scanner and insights into what Nmap output really means.

This tutorial demonstrates some common Nmap port scanning scenarios and explains the output.
Rather than attempt to be comprehensive, the goal is simply to acquaint new users well enough to
understand the rest of this chapter.

The simplest Nmap command is just nmap by itself. This prints a cheat sheet of common Nmap
options and syntax. A more interesting command is nmap <target>, which does the following:

1. Converts <target> from a hostname into an IPv4 address using DNS. If an IP address is
specified instead of a hostname this lookup is skipped.
2. Pings the host, by default with an ICMP echo request packet and a TCP ACK packet to port
80, to determine whether it is up and running. If not, Nmap reports that fact and exits. I
could have specified -Pn to skip this test. See Chapter 3, Host Discovery (“Ping Scanning”).
3. Converts the target IP address back to the name using a reverse-DNS query. Because of the
way DNS works, the reverse name may not be the same as the <target> specified on the
command-line. This query can be skipped with the -n option to improve speed and
stealthiness.
4. Launches a TCP port scan of the most popular 1,000 ports listed in nmap-services. A SYN
stealth scan is usually used, but connect scan is substituted instead for non-root Unix users
who lack the privileges necessary to send raw packets.
5. Prints the results to standard output in normal human-readable format, and exits. Other
output formats and locations (files) can be specified, as described in Chapter 13, Nmap
Output Formats. Example 4.2 displays the results when scanme.nmap.org is used
as <target>.

How To Run a Ping Scan

One of the most basic functions of Nmap is to identify active hosts on your network. Nmap does
this by using a ping scan. This identifies all of the IP addresses that are currently online without
sending any packets to these hosts.

To run a ping scan, run the following command:

# nmap -sp 192.100.1.1/24

How To Run A Host Scan

A more powerful way to scan your networks is to use Nmap to perform a host scan. Unlike a ping
scan, a host scan actively sends ARP request packets to all the hosts connected to your network.
Each host then responds to this packet with another ARP packet containing its status and MAC
address.

To run a host scan, use the following command:

# nmap -sp<target IP range>


# namp -sL<IP address>
15. Operating System Detection using Nmap

OS detection
Nmap is one of the most popular tools used for the enumeration of a targeted host. Nmap can use
scans that provide the OS, version, and service detection for individual or multiple devices.
Detection scans are critical to the enumeration process when conducting penetration testing of a
network. It is important to know where vulnerable machines are located on the network so they
can be fixed or replaced before they are attacked. Many attackers will use these scans to figure out
what payloads would be most effective on a victim's device. The OS scan works by using the TCP/IP
stack fingerprinting method. The services scan works by using the Nmap-service-probes database to
enumerate details of services running on a targeted host.
Detect OS and services
This is the command to scan and search for the OS (and the OS version) on a host. This command
will provide valuable information for the enumeration phase of your network security assessment
(if you only want to detect the operating system, type nmap -O 192.168.0.9):
nmap -A 192.168.0.9
16. Do the following using NS2 Simulator

i. NS2 Simulator-Introduction
ii. Simulate to Find the Number of Packets Dropped
iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
iv. Simulate to Find the Number of Packets Dropped due to Congestion
v. Simulate to Compare Data Rate& Throughput.

NS2 Simulator-Introduction

What is NS2
NS2 stands for Network Simulator Version 2. It is an open-source event-driven simulator designed
specifically for research in computer communication networks.

Components of ns-2:

 Nam.
 Ns2.
 Post processing like simple trace analysis, often also in AWK, perl or OTCL.
 Pre-processing like traffic and also topology generators

Features of NS2
1. It is a discrete event simulator for networking research.

2. It provides substantial support to simulate bunch of protocols like TCP, FTP, UDP, https and DSR.

3. It simulates wired and wireless network.

4. It is primarily Unix based.

5. Uses TCL as its scripting language.

6. Otcl: Object oriented support

7. Tclcl: C++ and otcl linkage

8. Discrete event scheduler

Basic Architecture
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).
While the C++ defines the internal mechanism (i.e., a backend) of the simulation objects, the OTcl
sets up simulation by assembling and configuring the objects as well as scheduling discrete events.
The C++ and the OTcl are linked together using TclCL
NS simulation script and explains what each line does. Example is an OTcl script that creates the
simple network configuration and runs the simulation scenario in Figure.

This network consists of 4 nodes (n0, n1, n2, n3) as shown in above figure. The duplex links between
n0 and n2, and n1 and n2 have 2 Mbps of bandwidth and 10 ms of delay. The duplex link between n2
and n3 has 1.7 Mbps of bandwidth and 20 ms of delay. Each node uses a DropTail queue, of which
the maximum size is 10. A "tcp" agent is attached to n0, and a connection is established to a tcp
"sink" agent attached to n3. As default, the maximum size of a packet that a "tcp" agent can generate
is 1KByte. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees
the received packets.
ackets. A "udp" agent that is attached to n1 is connected to a "null" agent attached to
n3. A "null" agent just frees the packets received. A "ftp" and a "cbr" traffic generator are attached to
"tcp" and "udp" agents respectively, and the "cbr" is configur ed to generate 1 KByte packets at the
configured
rate of 1 Mbps. The "cbr" is set to start at 0.1 sec and stop at 4.5 sec, and "ftp" is set to start at 1.0 sec
and stop at 4.0 sec.
A Simple NS Simulation Script- ns-simple.tcl
The following is the explanation of the script above. In general, an NS script starts with making a
Simulator object instance.

 set ns [new Simulator]: generates an NS simulator object instance, and assigns it to


variable ns (italics is used for variables and values in this section). What this line does is the
following:

o Initialize the packet format (ignore this for now)


o Create a scheduler (default is calendar scheduler)
o Select the default address format (ignore this for now)

The "Simulator" object has member functions that do the following:


o Create compound objects such as nodes and links (described later)
o Connect network component objects created (ex. attach-agent)
o Set network component parameters (mostly for compound objects)
o Create connections between agents (ex. make connection between a "tcp" and "sink")
o Specify NAM display options
o Etc.

Most of member functions are for simulation setup (referred to as plumbing functions in the
Overview section) and scheduling, however some of them are for the NAM display. The
"Simulator" object member function implementations are located in the "ns-2/tcl/lib/ns-
lib.tcl" file.

 $ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This
member function of "Simulator" object is for the NAM display, and has no effect on the
actual simulation.

 $ns namtrace-all file-descriptor: This member function tells the simulator to record
simulation traces in NAM input format. It also gives the file name that the trace will be
written to later by the command $ns flush-trace. Similarly, the member function trace-all is
for recording the simulation trace in a general format.

 proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In
this function, post-simulation processes are specified.

 set n0 [$ns node]: The member function node creates a node. A node in NS is compound
object made of address and port classifiers (described in a later section). Users can create a
node by separately creating an address and a port classifier objects and connecting them
together. However, this member function of Simulator object makes the job easier. To see
how a node is created, look at the files: "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-
node.tcl".

 $ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of
specified bandwidth and delay, and connects the two specified nodes. In NS, the output
queue of a node is implemented as a part of a link, therefore users should specify the queue-
type when creating links. In the above simulation script, DropTail queue is used. If the reader
wants to use a RED queue, simply replace the word DropTail with RED. The NS
implementation of a link is shown in a later section. Like a node, a link is a compound object,
and users can create its sub-objects and connect them and the nodes. Link source codes can
be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl" files. One thing to note is
that you can insert error modules in a link component to simulate a lossy link (actually users
can make and insert any network objects). Refer to the NS documentation to find out how to
do this.

 $ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links
that connect node1 and node2 to the number specified. At this point, the authors do not know
how many of these kinds of member functions of Simulator objects are available and what
they are. Please take a look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS
documentation for more information.
 $ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display.
To see the effects of these lines, users can comment these lines out and try the simulation.

Now that the basic network setup is done, the next thing to do is to setup traffic agents such as TCP
and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents respectively.

 set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users
can create any agent or traffic sources in this way. Agents and traffic sources are in fact basic
objects (not compound objects), mostly implemented in C++ and linked to OTcl. Therefore,
there are no specific Simulator object member functions that create these object instances. To
create agents or traffic sources, a user should know the class names these objects
(Agent/TCP, Agnet/TCPSink, Application/FTP and so on). This information can be found in
the NS documentation or partly in this documentation. But one shortcut is to look at the "ns-
2/tcl/libs/ns-default.tcl" file. This file contains the default configurable parameter value
settings for available network objects. Therefore, it works as a good indicator of what kind of
network objects are available in NS and what are the configurable parameters.

 $ns attach-agent node agent: The attach-agent member function attaches an agent object
created to a node object. Actually, what this function does is call the attach member function
of specified node, which attaches the given agent to itself. Therefore, a user can do the same
thing by, for example, $n0 attach $tcp. Similarly, each agent object has a member
function attach-agent that attaches a traffic source object to itself.

 $ns connect agent1 agent2: After two agents that will communicate with each other are
created, the next thing is to establish a logical network connection between them. This line
establishes a network connection by setting the destination address to each others' network
and port address pair.

Assuming that all the network configuration is done, the next thing to do is write a simulation
scenario (i.e. simulation scheduling). The Simulator object has many scheduling member functions.
However, the one that is mostly used is the following:

 $ns at time "string": This member function of a Simulator object makes the scheduler
(scheduler_ is the variable that points the scheduler object created by [new Scheduler]
command at the beginning of the script) to schedule the execution of the specified string at
given simulation time. For example, $ns at 0.1 "$cbr start" will make the scheduler call
a start member function of the CBR traffic source object, which starts the CBR to transmit
data. In NS, usually a traffic source does not transmit actual data, but it notifies the
underlying agent that it has some amount of data to transmit, and the agent, just knowing how
much of the data to transfer, creates packets and sends them.

After all network configuration, scheduling and post-simulation procedure specifications are done,
the only thing left is to run the simulation. This is done by $ns run.
Basic Network commands

Learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute. Capture ping
and traceroute PDUs using a network protocol analyzer and examine

Basic Network commands

ipconfig

C:\>ipconfig

Connection-specific dns suffix

A connection specific DNS suffix is a DNS suffix that is related to a particular network interface. It can be used in
addition to or instead of the Primary DNS suffix when performing DNS queries or DNS dynamic registrations

Link local address ipv6

IPv6 link-local addresses are addresses that can be used to communicate with nodes (hosts and routers) on an
attached link. Packets with those addresses are not forwarded by routers. At least, they should not be. There have
been cases where routers would happily forward packets with a link-local source address.

ipv4 address
The IPv4 address is a 32-bit number that uniquely identifies a network interface on a machine. An IPv4 address
is typically written in decimal digits, formatted as four 8-bit fields that are separated by periods. Each 8-bit field
represents a byte of the IPv4 address.

Subnet mask

The subnet mask is used by the TCP/IP protocol to determine whether a host is on the local subnet or on a
remote network. In TCP/IP, the parts of the IP address that are used as the network and host addresses aren't fixed.

Default gateway
In the networking world, a default gateway is an IP address that traffic gets sent to when it's bound for a
destination outside the current network. On most home and small business networks—where you have a single
router and several connected devices—the router's private IP address is the default gateway.

C:\>ipconfig/all

C:\>ipconfig: The ipconfig command displays information about the host (the computer
your sitting at)computer TCP/IP configuration.

C:\>ipconfig /all: This command displays detailed configuration information about your
TCP/IP connection including Router, Gateway, DNS, DHCP, and type of Ethernet
adapter in your system.

C:\>Ipconfig /renew: Using this command will renew all your IP addresses that you are
currently (leasing) borrowing from the DHCP server. This command is a quick problem
solver if you are having connection issues, but does not work if you have been configured
with a static IP address.

C:\>Ipconifg /release: This command allows you to drop the IP lease from the DHCP
server.

C:\>ipconfig /flushdns: This command is only needed if you’re having trouble with your
networks DNS configuration. The best time to use this command is after network
configuration frustration sets in, and you really need the computer to reply with flushed.

Nslookup

C:\>nslookup
www.jntuk.edu.in

Ctrl+C to come out

C:\>nslookup: Nslookup is used for diagnosing DNS problems. If you can access a
resource by specifying an IP address but not it’s DNS you have a DNS problem.

Ping
C:\>ping: Ping is the most basic TCP/IP command, and it’s the same as placing a phone call
to your best friend. You pick up your telephone and dial a number, expecting your best friend
to reply with “Hello” on the other end. Computers make phone calls to each other over a
network by using a Ping command. The Ping commands main purpose is to place a phone
call to another computer on the network, and request an answer. Ping has 2 options it can use
to place a phone call to another computer on the network. It can use the computers name or
IP address.

C:\>ping jntuk.edu.in
C:\>ping 78.47.226.171
C:\>pathping: Pathping is unique to Window’s, and is basically a combination of the Ping
and Tracert commands. Pathping traces the route to the destination address then launches a
25 second test of each router along the way, gathering statistics on the rate of data loss along
each hop.

C:\>route: The route command displays the computers routing table. A typical
computer, with a single network interface, connected to a LAN, with a router is fairly
simple and generally doesn’t pose any network problems. But if you’re having trouble
accessing other computers on your network, you can use the route command to make sure the
entries in the routing table are correct.

tracert

C:\>tracert: The tracert command displays a list of all the routers that a packet has to go
through to get from the computer where tracert is run to any other computer on the
internet.

C:\>tracert
Netstat

The netstat command generates displays that show network status and protocol statistics. You can
display the status of TCP and UDP endpoints in table format, routing table information, and interface
information. The most frequently used options for determining network status are: s , r , and i

C:/>netstat

C:/>netstat -?
Displays protocol statistics and current TCP/IP network connections.

C:\>nbtstat –a: This command helps solve problems with NetBIOS name resolution.
(Nbt stands for NetBIOS over TCP/IP)
C:\>netdiag: Netdiag is a network testing utility that performs a variety of network diagnostic
tests, allowing you to pinpoint problems in your network. Netdiag isn’t installed by default,
but can be installed from the Windows XP CD after saying no to the install. Navigate to the
CD ROM drive letter and open the support\tools folder on the XP
CD and click the setup.exe icon in the support\tools folder.

C:\>netstat: Netstat displays a variety of statistics about a computers active TCP/IP


connections. This tool is most useful when you’re having trouble with TCP/IP applications
such as HTTP, and FTP.

NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [interval]

-a Displays all connections and listening ports.


-b Displays the executable involved in creating each connection or
listening port. In some cases well-known executables host
multiple independent components, and in these cases the
sequence of components involved in creating the connection
or listening port is displayed. In this case the executable
name is in [] at the bottom, on top is the component it called,
and so forth until TCP/IP was reached. Note that this option
can be time-consuming and will fail unless you have sufficient
permissions.
-e Displays Ethernet statistics. This may be combined with the -s
option.
-f Displays Fully Qualified Domain Names (FQDN) for foreign
addresses.
-n Displays addresses and port numbers in numerical form.
-o Displays the owning process ID associated with each connection.
-p proto Shows connections for the protocol specified by proto; proto
may be any of: TCP, UDP, TCPv6, or UDPv6. If used with the -s
option to display per-protocol statistics, proto may be any of:
IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, or UDPv6.
-q Displays all connections, listening ports, and bound
nonlistening TCP ports. Bound nonlistening ports may or may not
be associated with an active connection.
-r Displays the routing table.
-s Displays per-protocol statistics. By default, statistics are
shown for IP, IPv6, ICMP, ICMPv6, TCP, TCPv6, UDP, and UDPv6;
the -p option may be used to specify a subset of the default.
-t Displays the current connection offload state.
-x Displays NetworkDirect connections, listeners, and shared
endpoints.
-y Displays the TCP connection template for all connections.
Cannot be combined with the other options.
interval Redisplays selected statistics, pausing interval seconds
between each display. Press CTRL+C to stop redisplaying
statistics. If omitted, netstat will print the current
configuration information once.
C:\>arp –a: ARP is short form of address resolution protocol, It will show the IP address of
your computer along with the IP address and MAC address of your router.

C:\>hostname: This is the simplest of all TCP/IP commands. It simply displays the name of
your computer.

What is the tcpdump command?

tcpdump is a command line utility that allows to capture the live TCP/IP packets going through an network
interface and can also be saved to a pcap file for offline analysis using Wireshark tool. It is a very well known tool for
IP packet capture in Linux

https://www.winpcap.org/

You might also like