Lab Manual r20 Cnm...
Lab Manual r20 Cnm...
1. Study of Network devices in detail and connect the computers in Local Area Network.
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.
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
As show in figure we teach how the ip addresses are classified and when they are used.
On the host computer, follow these steps to share the Internet connection:
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:
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:
-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.
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.
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.
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
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
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 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
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.
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:
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;
Encoded data is
1010010
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>
// 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;
}
c_l = p_n + n;
j = k = 0;
// 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.
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.
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;
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
Ex: -
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
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:
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
1.Cumulative ACK
2.Independent ACK
#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
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:
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…
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
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
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
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 −
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).
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
#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
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:
The following methods can be used to start capturing packets with Wireshark:
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.
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.
You can see similar statistics in the Statistics → Conversations and Statistics → Endpoints menus.
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:
An example is shown in Example 4.1, “A capture filter for telnet that captures traffic to and from a
particular host”.
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:
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
Port Specification
NSE Scripts
IDS Evasion
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>.
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.
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.
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.
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.
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
ipconfig
C:\>ipconfig
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
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
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.
NETSTAT [-a] [-b] [-e] [-f] [-n] [-o] [-p proto] [-r] [-s] [-x] [-t] [interval]
C:\>hostname: This is the simplest of all TCP/IP commands. It simply displays the name of
your computer.
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/