0% found this document useful (0 votes)
22 views82 pages

Computer Networks Lab Overview BCS-653

The document is a lab file for the Computer Networks course (BCS-653) at Pranveer Singh Institute of Technology, outlining the course objectives, outcomes, and program educational objectives. It includes a syllabus, lab plan, and specific experiments related to subnetting and TCP socket applications. The document emphasizes the importance of practical skills in computer networking for students in the Department of Artificial Intelligence.

Uploaded by

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

Computer Networks Lab Overview BCS-653

The document is a lab file for the Computer Networks course (BCS-653) at Pranveer Singh Institute of Technology, outlining the course objectives, outcomes, and program educational objectives. It includes a syllabus, lab plan, and specific experiments related to subnetting and TCP socket applications. The document emphasizes the importance of practical skills in computer networking for students in the Department of Artificial Intelligence.

Uploaded by

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

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR

DEPARTMENT OF ARTIFICIAL INTELLIGENCE

Even Semester 2024-25

B. Tech.- Third Year

Semester- VI

Lab File
Computer Networks

(BCS653)

Submitted To : Submitted By :
Faculty Name : Name :
Designation : Roll No. :
Section :
INDEX
S No Lab Experiment Date of Date of Marks Faculty
Experiment Submission Signature
PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

Table of Contents

• PEOs, POs, PSOs of the Department

• Course Objective and Outcomes

• List of Experiments

• Index

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

Vision Statement of the Institute


To achieve excellence in professional education and create an ecosystem for the
holistic development of all stakeholders.

Mission Statement of the Institute


To provide an environment of effective learning and innovation transforming students
into dynamic, responsible and productive professionals in their respective fields, who
are capable of adapting to the changing needs of the industry and society.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.)

Vision Statement of the Department


To be a recognized department of Computer Science & Engineering that produces
versatile computer engineers, capable of adapting to the changing needs of computer
and related industry.

Mission Statements of the Department


1. To provide broad based quality education with knowledge and attitude to
succeed in Computer Science & Engineering careers.
2. To prepare students for emerging trends in computer and related industry.
3. To develop competence in students by providing them skills and aptitude to
foster culture of continuous and life-long learning.
4. To develop practicing engineers who investigate research, design and find
workable solutions to complex engineering problems with awareness &
concern for society as well as environment.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

Program Educational Objectives (PEOs)

PEOs Description
The graduates will be efficient leading professionals with the knowledge
PEO1 of Computer Science & Engineering discipline that enables them to
pursue higher education and/or successful careers in various domains.
Graduates will possess capability of designing successful innovative
PEO2 solutions to real life problems that are technically sound,
economically viable and socially acceptable.
Graduates will be competent team leaders, effective communicators and
PEO3 capable of working in multidisciplinary teams following ethical values.
The graduates will be capable of adapting to new
PEO4 technologies/tools, constantly upgrading their knowledge and skills
with an attitude for lifelong learning.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.)

Program Outcomes
POs Graduate Attributes Description
PO1 Engineering Apply the knowledge of mathematics, science
Knowledge and Computer Science & Engineering
fundamentals to the solution of complex
engineering problems.
PO2 Problem Analysis Identify, formulate, review research literature,
and analyze complex Computer Science &
Engineering problems reaching substantiated
conclusions using principles of mathematics,
natural sciences, and engineering
PO3 Design/Development of Design solutions for Computer Science &
Solutions Engineering and allied fields related complex
engineering problems and design system
components or processes that meet the specified
needs with appropriate consideration for the
public health and safety, and the cultural, societal,
and environmental considerations.

PO4 Investigation Use research-based knowledge of Computer


Science & Engineering and research methods
including design of experiments, analysis and
interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5 Modern Tool Usage Create, select, and apply appropriate techniques,
resources, and modern engineering and IT tools
including prediction and modeling to complex
Computer Science & Engineering activities with an
understanding of the limitations.
PO6 The Engineering and Apply reasoning informed by the contextual
Society knowledge to assess societal, health, safety, legal and
cultural issues and the consequent responsibilities
relevant to the professional engineering practice in
the field of Computer Science & Engineering.

PO7 Environment and Understand the impact of the professional


Sustainability Computer Science & Engineering solutions in
societal and environmental contexts, and
demonstrate the knowledge of, and need for
sustainable development

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

PO8 Ethics Apply ethical principles and commit to


professional ethics and responsibilities and
norms of the Computer Science &
Engineering practice
PO9 Individual and Function effectively as an individual, and as
Team Work a member or leader in diverse teams, and in
multidisciplinary settings.
PO10 Communication Communicate effectively on complex
Computer Science & Engineering
activities with the engineering community
and with society at large, such as, being
able to comprehend and write effective
reports and design documentation, make
effective presentations, and give and
receive clear instructions.
PO11 Project Demonstrate knowledge and understanding
Management and of the Computer Science & Engineering and
Finance management principles and apply these to
one’s own work, as a member and leader in a
team, to manage projects and in
multidisciplinary environments.
PO12 Life-long Learning Recognize the need for and have the
preparation and ability to engage in
independent and life-long learning in the
broadest context of technological
change.

Program Specific Outcomes (PSOs)

PSOs Description
Use algorithms, data structures/management, software design, concepts of
PSO1
programming languages and computer organization and architecture.
PSO2 Understand the processes that support the delivery and management of
information systems within a specific application environment.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

Syllabus
Following table outline the syllabus for Computer Networks Lab (KCS-653) as
prescribed by Dr. A.P.J. Abdul Kalam Technical University, Uttar Pradesh, Lucknow.
The Syllabus can also seen on the university website:
[Link]
0a nd%20CSE%20Syllabus%20%203rd%20Year%[Link]

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

LAB PLAN

SUBJECT NAME: COMPUTER NETWORKS LAB

SUBJECT CODE: BCS-653


Lab Schedule: As per the timetable

i) Course Objective:
The objective of this lab is to give the idea about phases of compiler and analyze how
the code generation & optimization works in a translator.

ii) Course Outcomes

*Level of Bloom’s Level to *Level of Bloom’s Level to be


Taxonomy be met Taxonomy Met
L1: Remember 1 L2: Understand 2
L3: Apply 3 L4: Analyze 4
L5: Evaluate 5 L6: Create 6

CO Number Course Outcomes

Illustrate [L2: Understand] conceptual terms and various


BCS-653.1 components and devices of computer networks.

Apply [L3: Apply] the knowledge of Networks for configuring the


BCS-653.2 performance of the computer network.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


PSIT-Pranveer Singh Institute of Technology
Kanpur- Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.) India

CO-PO & CO-PSO Correlation Matrix

Mapping of Course Outcomes with Program Outcomes and Program


Specific Outcomes

Program Outcomes PSO

COs 1 2 3 4 5 6 7 8 9 10 11 12 1 2

BCS-653.1 3 3 - - - - - - - - - - - -
BCS-653.2
- 3 - - 3 - - - - - - - 3 -
AVG
3 3 - - 3 - - - - - - - 3 -

Justification of CO-PO Mapping

BCS-653.2 PSO1: BCS-653.2 is substantially mapped with PSO1 as the students


with PSO1 will use the knowledge obtained in the undergraduate programme to
maintain and configure the network.

Justification of CO-PO Mapping

PO1: BCS-653.1 is substantially mapped with PO1 as the students


will understand the different components of Networks and the tools
involved with the knowledge they possessed during the
BCS- undergraduate programme.
653.1
with PO1 PO2: BCS-653.1 is substantially mapped with PO2 as the students
and PO2 will be able to analyze the complex problems of Computer
Networks and may approach with innovative solutions with the
knowledge they possessed during the undergraduate programme.
PO2: BCS-653.2 is substantially mapped with PO2 as the students
BCS- will be able to configure the performance of the Network with the
653.2 analysis they have done.
with PO2
PO5: BCS-653.2 is substantially mapped with PO5 as the students
and PO5
will use the modern tools to configure and evaluate the performance
of a network.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE BCS-653


EXPERIMENT 7:
IMPLEMENTATION OF
SUBNETTING.

OBJECTIVE:
Write a program to implement subnetting and find the subnet masks.

Algorithm :

Step1: Get the input from the user by using scanner method.
Step 2:Read the input by using nextLine() and store it.
Step 3: Split the string based on string by using split(“\\”)
Step4 :Convert it into binary.
Step 5: calculating the network mask by using math and logarithmic
Step 6: get the first address by ANDding the last n bits with 0.
Step7 : get the last address by ANDding the last n bits with 1.

Program

import [Link]; class


Subnet{ public static void main(String
args[]){ Scanner sc = new
Scanner([Link]);
[Link](“Enter the ip address: “);
String ip = [Link]();
String split_ip[] = [Link](“\\.”); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip String bip = “”; for(int i=0;i<4;i++)
{ split_bip[i] = appendZeros([Link]([Link](split_ip[i]))); // “18” =>
18 => 10010 => 00010010 bip
+= split_bip[i]; }
[Link](“IP in binary is “+bip);
[Link](“Enter the number of addresses: “); int n = [Link](); //Calculation of
mask int bits = (int)[Link]([Link](n)/[Link](2)); /*eg if address = 120, log 120/log
2 gives
log to the base 2 => 6.9068, ceil gives us upper integer */ [Link](“Number of
bits required for address = “+bits); int mask = 32-bits; [Link](“The bits for
subnet mask is = “+mask);

//Calculation of first address and last address int fbip[]


= new int[32];
for(int i=0; i<32;i++) fbip[i] = (int)[Link](i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i–)//Get first address by ANDing last n bits with 0 fbip[i] &= 0;
String fip[] = {“”,””,””,””}; for(int i=0;i<32;i++)
fip[i/8] = new
String(fip[i/8]+fbip[i]);
[Link](“First address is = “);
for(int i=0;i<4;i++){
[Link]([Link](fip[i],2));
if(i!=3) [Link](“.”); }
[Link](); int lbip[] = new
int[32];

for(int i=0; i<32;i++) lbip[i] = (int)[Link](i)-48; //convert cahracter 0,1 to integer 0,1
for(int i=31;i>31-bits;i–)//Get last address by ORing last n bits with 1 lbip[i] |= 1;
String lip[] = {“”,””,””,””}; for(int i=0;i<32;i++)
lip[i/8] = new
String(lip[i/8]+lbip[i]);
[Link](“Last address is = “); for(int i=0;i<4;i+
+){
[Link]([Link](lip[i],2));
if(i!=3) [Link](“.”); }
[Link]();
} static String appendZeros(String s)
{ String temp = new String(“00000000”);
return [Link]([Link]())+ s;
}
}

Output:

Enter the ip address: [Link]


IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The bits for subnet mask is = 29
First address is = [Link] Last
address is = [Link]
EXPERIMENT
8: APPLICATIONS USING TCP SOCKETS LIKE,
(A) ECHO CLIENT AND ECHO SERVER
(B) CHAT
(C) FILE TRANSFER

a. Echo client and echo server

OBJECTIVE
To write a java program for applications using TCP Sockets Links

Algorithm
1. Start the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it
will send NACK signal to client.
6. Stop the program

Program :
//echo [Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class
echoclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream
usr_inp=null;
DataInputStream din=new DataInputStream([Link]);
DataOutputStream dout=null;
try
{
c=new Socket("[Link]",5678);
usr_inp=new DataInputStream([Link]());
dout=new DataOutputStream([Link]());
}
catch(IOException e)
{
}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
while((unip=[Link]())!=null)
{
[Link](""+unip);
[Link]("\n");
[Link]("\n the echoed
message");
[Link](usr_inp.readLine());
[Link]("\n enter your message");
}
[Link](0);
}
[Link]();
usr_inp.close();
[Link]();
}
}

//[Link]
import [Link].*;
import [Link].*;
public class
echoserver
{
public static void main(String args[])throws Exception
{
ServerSocket
m=null; Socket
c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream([Link]);
DataOutputStream dout=null;
try
{
m=new ServerSocket(5678);
c=[Link]();
usr_inp=new DataInputStream([Link]());
dout=new DataOutputStream([Link]());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null)
{
String
unip;
while(true)
{
[Link]("\nMessage from
Client..."); String m1=(usr_inp.readLine());
[Link](m1);
[Link](""+m1)
; [Link]("\n");
}
}
[Link]();
usr_inp.close();
[Link]();
}
}

Output :
Refer to Experiment 17.

b. Chat

Algorithm:

Server
Step1: Start the program and create server and client sockets.
Step2: Use input streams to get the message from user.
Step3: Use output streams to send message to the client.
Step4: Wait for client to display this message and write a new one to be displayed by the
server.
Step5: Display message given at client using input streams read from socket.
Step6: Stop the program.

Client
Step1: Start the program and create a client socket that connects to the required host and port.
Step2: Use input streams read message given by server and print it.
Step3: Use input streams; get the message from user to be given to the server.
Step4: Use output streams to write message to the server.
Step5: Stop the program.

//[Link]
import [Link].*;
import [Link].*;
public class
talkclient
{
public static void main(String args[])throws Exception
{
Socket c=null;
DataInputStream
usr_inp=null;
DataInputStream din=new DataInputStream([Link]);
DataOutputStream dout=null;
try
{
c=new Socket("[Link]",1234);
usr_inp=new DataInputStream([Link]());
dout=new DataOutputStream([Link]());
}
catch(IOException e)
{}
if(c!=null || usr_inp!=null || dout!=null)
{
String unip;
[Link]("\nEnter the message for
server:"); while((unip=[Link]())!=null)
{
[Link](""+unip); [Link]("\
n"); [Link]("reply");
[Link](usr_inp.readLine());
[Link]("\n enter your
message:");
}
[Link](0);
}
[Link]();
usr_inp.close();
[Link]();
}
}

//[Link]
import [Link].*;
import [Link].*;
public class
talkserver
{
public static void main(String args[])throws Exception
{
ServerSocket
m=null; Socket
c=null;
DataInputStream usr_inp=null;
DataInputStream din=new DataInputStream([Link]);
DataOutputStream dout=null;
try
{
m=new ServerSocket(1234);
c=[Link]();
usr_inp=new DataInputStream([Link]());
dout=new DataOutputStream([Link]());
}
catch(IOException e)
{}
if(c!=null||usr_inp!=null)
{
String
unip;
while(true)
{
[Link]("\nmessage from
client:"); String m1=usr_inp.readLine();
[Link](m1);
[Link]("enter your message:");
unip=[Link]();
[Link](""+unip); [Link]("\
n");
}
}
[Link]();
usr_inp.close();
[Link]();
}
}

OUTPUT:
Refer to Experiment 17.

c. File Transfer

Algorithm:

Server
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the
port. Step3: Accept the client connection
Step4: Get the file name and stored into the BufferedReader.
Step5: Create a new object class file and realine.
Step6: If file is exists then FileReader read the content until EOF is reached.
Step7: Stop the program.

Client
Step1: Import java packages and create class file server.
Step2: Create a new server socket and bind it to the
port. Step3: Now connection is established.
Step4: The object of a BufferReader class is used for storing data content which has
been retrieved from socket object.
Step5: The content of file is displayed in the client window and the connection is closed.
Step6: Stop the program.

Program
//File Client
import [Link].*;
import
[Link].*; import
[Link].*; class
Clientfile
{ public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader([Link]));
Socket clsct=new Socket("[Link]",139);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Enter the file name:");
String str=[Link](); [Link](str+'\
n'); [Link]("Enter the new file
name:"); String str2=[Link]();
String str1,ss;
FileWriter f=new
FileWriter(str2); char buffer[];
while(true)
{ str1=[Link]();
if([Link]("-1")) break;
[Link](str1);
buffer=new
char[[Link]()];
[Link](0,[Link](),buffer,0);
[Link](buffer);
}
[Link]();
[Link]();
}
catch (Exception e)
{
[Link](e);
}
}
}
Server
import [Link].*;
import
[Link].*; import
[Link].*; class
Serverfile
{ public static void main(String args[])
{
Try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Socket obj1=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
String str=[Link]();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=[Link]())!=null)
{ [Link](s)
; [Link](s+'\
n');
}
[Link]();
[Link]("-1\
n");
}}
catch(Exception e)
{ [Link](e);}
}
}

Output:
File content
Computer
networks jhfcgsauf
jbsdava
jbvuesagv

client end:
Enter the file name:[Link]

Server response:
Computer
networks jhfcgsauf
jbsdava
jbvuesagv
client end:
Enter the new file name:
[Link] Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Destination file
Computer
networks jhfcgsauf
jbsdava
jbvuesagv
EXPERIMENT 9:
APPLICATIONS USING TCP AND UDP SOCKETS LIKE ,
A. DNS
B. SNMP
C. FILE TRANSFER

a. DNS

OBJECTIVE
To write a java program for DNS application program

Algorithm [Link]
the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6. Stop the program

Program

// UDP DNS

Server

Udpdnsserver
java import [Link].*; import
[Link].*; public
class udpdnsserver
{ private static int indexOf(String[] array, String
str)
{
str = [Link]();
for (int i=0; i < [Link]; i++)
{ if (array[i].equals(str))
return i;
} return 1; } public static void main(String arg[])throws
IOException {
String[] hosts = {"[Link]", "[Link]","[Link]", "[Link]"};
String[] ip = {"[Link]", "[Link]","[Link]", "[Link]"};
[Link]("Press Ctrl + C to Quit"); while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362); byte[]
senddata = new byte[1021];
byte[] receivedata = new byte[1021];
DatagramPacket recvpack = new DatagramPacket
(receivedata, [Link]); [Link](recvpack);
String sen = new String([Link]());
InetAddress ipaddress = [Link](); int
port =
[Link]();
String capsent;
[Link]("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent =
ip[indexOf (hosts, sen)]; else capsent = "Host
Not Found"; senddata = [Link]();
DatagramPacket pack = new DatagramPacket
(senddata, [Link],ipaddress,port);
[Link](pack);
[Link]();
}
}
}

//UDP DNS Client


Udpdnsclient .java
import [Link].*;
import [Link].*;
public class
udpdnsclient
{ public static void main(String args[])throws
IOException {
BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
DatagramSocket clientsocket = new DatagramSocket();
InetAddress ipaddress; if ([Link] == 0)
ipaddress = [Link]();
else
ipaddress =
[Link](args[0]); byte[]
senddata = new byte[1024]; byte[]
receivedata = new byte[1024]; int portaddr =
1362;
[Link]("Enter the hostname : ");
String sentence =
[Link](); Senddata =
[Link]();
DatagramPacket pack = new DatagramPacket(senddata,[Link], ipaddress,portaddr);
[Link](pack);
DatagramPacket recvpack =new
DatagramPacket(receivedata,[Link]); [Link](recvpack);
String modified = new String([Link]()); [Link]("IP
Address: " + modified); [Link]();
}
}

OUTPUT

Server
$ javac [Link] $ java udpdnsserver Press Ctrl + C to Quit Request for host
[Link] Request for host [Link] Request for host [Link]
Client
$ javac [Link] $ java udpdnsclient Enter the hostname : [Link] IP Address:
[Link] $ java udpdnsclient Enter the hostname : [Link] IP Address:
[Link] $ java udpdnsclient Enter the hostname : [Link] IP Address: Host Not
Found

b. SNMP

OBJECTIVE
To write a java program for SNMP application program

Algorithm [Link]
the program.
2. Get the frame size from the user
3. To create the frame based on the user request.
4. To send frames to server from the client side.
5. If your frames reach the server it will send ACK signal to client otherwise it will
send NACK signal to client.
6. Stop the program

Program import
[Link];
import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link];
import [Link];
import [Link];
import [Link];
public class SNMPManager {
Snmp snmp = null;
String address = null;
* Constructor *
@param add
*/
public SNMPManager(String add)
{ address = add;
public static void main(String[] args) throws IOException {
/**
* Port 161 is used for Read and Other operations
* Port 162 is used for the trap generation */
SNMPManager client = new SNMPManager("udp:[Link]/161"); [Link]();
/**
* OID - .[Link].[Link].0 => SysDec
* OID - .[Link].[Link].0 => SysName
* => MIB explorer will be usefull here, as discussed in previous article */
String sysDescr = [Link](new OID(".[Link].[Link].0"));
[Link](sysDescr);
}
/**
* get any answers because the communication is asynchronous * and the listen()
method listens for answers.
* @throws IOException
*/
private void start() throws IOException {
TransportMapping transport = new DefaultUdpTransportMapping(); snmp =
new
Snmp(transport); // Do
not forget this line!
[Link]();
}
/**
* Method which takes a single OID and returns the response from the agent as a String.
* @param oid
* @return
* @throws IOException
*/
public String getAsString(OID oid) throws IOException
{ ResponseEvent event = get(new OID[] { oid }); return
[Link]().get(0).getVariable().toString(); }
/**
* This method is capable of handling multiple OIDs
* @param oids
* @return
* @throws IOException
*/
public ResponseEvent get(OID oids[]) throws IOException
{ PDU pdu = new PDU(); for (OID oid : oids) {
[Link](new VariableBinding(oid));
}
[Link]([Link]);
ResponseEvent event = [Link](pdu, getTarget(), null); if(event
!= null) { return event;
}
throw new RuntimeException("GET timed out");
}
/**
* This method returns a Target, which contains information about * where the
data should be fetched and how.
* @return
*/
private Target getTarget() {
Address targetAddress = [Link](address); CommunityTarget
target = new CommunityTarget(); [Link](new
OctetString("public")); [Link](targetAddress); [Link](2);
[Link](1500);
[Link](SnmpConstants.version2c); return target;
}
}

OUT PUT
Hardware: x86 Family 6 Model 23 Stepping 10 AT/AT COMPATIBLE – Software:
Windows 2000 Version 5.1 (Build 2600 Multiprocessor Free)

b. File Transfer

OBJECTIVE
To write a java program for FTP using TCP and UDP Sockets Liks

Program
File Client
import [Link].*;
import
[Link].*;
import
[Link].*; class
Clientfile
{ public static void main(String args[]) {
Try
{
BufferedReader in=new BufferedReader(new
InputStreamReader([Link])); Socket clsct=new Socket("[Link]",139);
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
[Link]("Enter the file name:"); String
str=[Link](); [Link](str+'\n');
[Link]("Enter the new file name:");
String str2=[Link]();
String str1,ss;
FileWriter f=new FileWriter(str2); char
buffer[]; while(true)
{ str1=[Link]();
if([Link]("1")) break;
[Link](str1); buffer=new
char[[Link]()];
[Link](0,[Link](),buffer,0)
; [Link](buffer);
}
[Link]();
[Link]();
} catch (Exception
e)
{
[Link](e);
}
}
}

Server import
[Link].*; import
[Link].*;
import
[Link].*; class
Serverfile
{ public static void main(String args[])
{ Try
{
ServerSocket obj=new ServerSocket(139); while(true)
{
Socket obj1=[Link]();
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new
DataOutputStream([Link]()); String str=[Link]();
FileReader f=new FileReader(str);
BufferedReader b=new
BufferedReader(f); String s;
while((s=[Link]())!=null) {
[Link](s); [Link](s+'\
n');
}
[Link]();
[Link]("-1\
n");
} } catch(Exception
e) {
[Link](e);}
}
}
Output
File content
Computer
networks jhfcgsauf
jbsdava jbvuesagv
client
Enter the file name:
[Link]
server Computer
networks jhfcgsauf
jbsdava
jbvuesagv client
Enter the new file name:
[Link]
Computer networks
jhfcgsauf jbsdava
jbvuesagv
Destination file
Computer
networks jhfcgsauf
jbsdava
jbvuesagv
EXPERIMENT 10:
STUDY OF NETWORK SIMULATOR (NS) AND SIMULATION OF CONGESTION CONTROL
ALGORITHMS USING NS.

OBJECTIVE:
To Study of Network simulator (NS) and Simulation of Congestion Control Algorithms using
NS.

NET WORK SIMULATOR (NS2)


NS overview
• Ns programming: A Quick start
• Case study I: A simple Wireless network
• Case study II: Create a new agent in Ns
• Ns Status
• Periodical release (ns-2.26, Feb 2003)
• Platform support
• FreeBSD, Linux, Solaris, Windows and Mac

NS Functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS

Wireless
Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilitie NS
(Network Simulators) Most of the commercial simulators are GUI driven, while some
Network simulators are CLI driven. The network model / configuration describes the state of
the network (nodes,routers, switches, links) and the events (data transmissions, packet error
etc.). An important output of simulations are the trace files. Trace files log every packet,
every event that occurred in the simulation and are used for analysis. Network simulators can
also provide other tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending "events" is
stored, and those events are processed in order, with some events triggering future events—
such as the event of the arrival of a packet at one node triggering the event of the arrival of
that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high,
thenestimation of the average occupancy is challenging because of high variance. To estimate
the likelihood of a buffer overflow in a network, the time required for an accurate answer can
be extremely large. Specialized techniques such as "control variates" and "importance
sampling" have been developed to speed simulation.

Examples of network simulators


There are many both free/open-source and proprietary network simulators. Examples of
notable network simulation software are, ordered after how often they are mentioned in
research papers: 1. NS (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators


Network simulators serve a variety of needs. Compared to the cost and time involved in
setting up an entire test bed containing multiple networked computers, routers and data links,
network simulators are relatively fast and inexpensive. They allow engineers, researchers to
test scenarios that might be particularly difficult or expensive to emulate using real hardware
- for instance simulating a scenario with several nodes or experimenting with a new protocol
in the network.
Network simulators are particularly useful in allowing researchers to test new networking
protocols or changes to existing protocols in a controlled and reproducible environment. A
typical network simulator encompasses a wide range of networking technologies and can help
the users to build complex networks from basic building blocks such as a variety of nodes and
links. With the help of simulators, one can design hierarchical networks using various types
of nodes like computers, hubs, bridges, routers, switches, links, mobile units etc.
Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc. and Local
Area Network (LAN) technologies like Ethernet, token rings etc., can all be simulated with a
typical simulator and the user can test, analyze various standard results apart from devising
some novel protocol or strategy for routing etc. Network simulators are also widely used to
simulate battlefield networks in Network-centric warfare. There are a wide variety of network
simulators, ranging from the very simple to the very complex. Minimally, a network
simulator must enable a user to represent a network topology, specifying the nodes on the
network, the links between those nodes and the traffic between the nodes. More complicated
systems may allow the user to specify everything about the protocols used to handle traffic in
a network. Graphical applications allow users to easily visualize the workings of their
simulated environment. Text-based applications may provide a less intuitive interface, but
may permit more advanced forms of customization.

Packet loss
Occurs when one or more packets of data travelling across a computer networkfail to reach
their destination. Packet loss is distinguished as one of the three main error types encountered
in digital communications; the other two being bit errorand spurious packets caused due to
noise.
Packets can be lost in a network because they may be dropped when a queue in the network
node overflows. The amount of packet loss during the steady state is another important
property of a congestion control scheme. The larger the value of packet loss, the more
difficult it is for transportlayer protocols to maintain high bandwidths, the sensitivity to loss
of individual packets, as well as to frequency and patterns of loss among longer packet
sequences is strongly dependent on the application itself.
Throughput
This is the main performance measure characteristic, and most widely used.
Incommunicationnetworks, such asEthernetorpacket radio, throughputor network
throughputis the average rate of successfulmessage delivery over a communication channel.
The throughput is usually measured inbitsper second (bit/s orbps), andsometimes indata
packetsper second or data packets pertime slotThis measure how soon the receiver is able to
get a certain amount of data send by the sender. It is determined as the ratio of the total data
received to the end to end delay. Throughput is an important factor which directly impacts the
network performance.

Delay
Delay is the time elapsed while a packet travels from one point e.g., source premise or
network ingress to destination premise or network degrees. The larger the valueof delay, the
more difficult it is for transport layer protocols to maintain highbandwidths. We will calculate
end to end delay.

Queue Length
A queuing system in networks can be described as packets arriving for service, waiting for
service if it is not immediate, and if having waited for service, leaving thesystem after being
served. Thus queue length is very important characteristic to determine that how well the
active queue management of the congestion control algorithm has been working.
EXPERIMENT 11:
PERFORM A CASE STUDY ABOUT THE DIFFERENT ROUTING ALGORITHMS
TO SELECT THE NETWORK PATH WITH ITS OPTIMUM AND ECONOMICAL
DURING DATA TRANSFER.
I. LINK STATE ROUTING
II. FLOODING

III. DISTANCE VECTOR

OBJECTIVE:
To study the link state routing flooding and distance vectorrouting.

I) LINK STATE ROUTING

Link State routing


Routing is the process of selecting best paths in a network. In the past, the term routing was
also used to mean forwarding network traffic among networks. However this latter function is
much better described as simply forwarding. Routing is performed for many kinds of
networks, including the telephone network (circuit switching), electronic data networks (such
as the Internet), and transportation networks. This article is concerned primarily with routing
in electronic data networks using packet switching technology .In packet switching networks,
routing directs packet forwarding (the transit of logically addressed network packets from
their source toward their ultimate destination) through intermediate nodes. Intermediate nodes
are typically network hardware devices such as routers, bridges, gateways, firewalls, or
switches. General-purpose computers can also forward packets and perform routing, though
they are not specialized hardware and may suffer from limited performance. The routing
process usually directs forwarding on the basis of routing tables which maintain a record of
the routes to various network destinations. Thus, constructing routing tables, which are held
in the router's memory, is very important for efficient routing. Most routing algorithms use
only one network path at a time.
Multipath routing techniques enable the use of multiple alternative paths. In case of
overlapping/equal routes, the following elements are considered in order to decide which
routes get installed into the routing table (sorted by priority):
1. Prefix-Length: where longer subnet masks are preferred (independent of whether it
is within a routing protocol or over different routing protocol)
2. Metric: where a lower metric/cost is preferred (only valid within one and the
same routing protocol)
3. Administrative distance: where a lower distance is preferred (only valid between
different routing protocols) Routing, in a more narrow sense of the term, is often
contrasted with bridging in its assumption that network addresses are structured and that
similar
addresses imply proximity within the network. Structured addresses allow a single routing table
entry to represent the route to a group of devices. In large networks, structured addressing
(routing, in the narrow sense) outperforms unstructured addressing (bridging). Routing has
become the dominant form of addressing on the Internet. Bridging is still widely used within
localized environments.

II) FLOODING
Flooding is a simple routing algorithm in which every incoming packet is sent through every
outgoing link except the one it arrived on Flooding is used in bridging and in systems such as
Usenet and peer-to-peer file sharing and as part of some routing protocols, including OSPF,
DVMRP, and those used in ad-hoc wireless [Link] are generally two types of
flooding available, Uncontrolled Flooding and Controlled [Link] Flooding is
the fatal law of flooding. All nodes have neighbours and route packets indefinitely. More than
two neighbours create a broadcast storm.
Controlled Flooding has its own two algorithms to make it reliable, SNCF (Sequence Number
Controlled Flooding) and RPF (Reverse Path Flooding). In SNCF, the node attaches its own
address and sequence number to the packet, since every node has a memory of addresses and
sequence numbers. If it receives a packet in memory, it drops it immediately while in RPF,
the node will only send the packet forward. If it is received from the next node, it sends it
back to the sender.

Algorithm
There are several variants of flooding algorithm. Most work roughly as follows:
1. Each node acts as both a transmitter and a receiver.
2. Each node tries to forward every message to every one of its neighbours except the source
node. This results in every message eventually being delivered to all reachable parts of
the network. Algorithms may need to be more complex than this, since, in some case,
precautions have to be taken to avoid wasted duplicate deliveries and infinite loops, and to
allow messages to eventually expire from the system. A variant of flooding called
selective flooding partially addresses these issues by only sending packets to routers in the
same direction. In selective flooding the routers don't send every incoming packet on
every line but only on those lines which are going approximately in the right direction.

Advantages
Packet can be delivered, it will (probably multiple times). Since flooding naturally utilizes every
path through the network, it will also use the shortest path. This algorithm is very simple to
implement.

Disadvantages
Flooding can be costly in terms of wasted bandwidth. While a message may only have one
destination it has to be sent to every host. In the case of a ping flood or a denial of service
attack, it can be harmful to the reliability of a computer [Link] can become
duplicated in the network further increasing the load on the networks bandwidth as well as
requiring an increase in processing complexity to disregard duplicate [Link]
packets may circulate forever, unless certain precautions are taken. Use a hop count or a time
to live count and include it with each packet. This value should take into account the number
of nodes that a packet may have to pass through on the way to its [Link] each node
keep track of every packet seen and only forward each packet once Enforce a network
topology without loops.

III) DISTANCE VECTOR ROUTING PROTOCOL USING NS2

In computer communication theory relating to packet-switched networks, a distance vector


routing protocol is one of the two major classes of routing protocols, the other major class
being the link-state protocol. Distance-vector routing protocols use the Bellman–Ford
algorithm, Ford–Fulkerson algorithm, or DUAL FSM (in the case of Cisco Systems
protocols) to calculate paths.
A distance-vector routing protocol requires that a router informs its neighbours of topology
changes periodically. Compared to link-state protocols, which require a router to inform all
the nodes in a network of topology changes, distance-vector routing protocols have less
computational complexity and message overhead. The term distance vector refers to the fact
that the protocol manipulates vectors (arrays) of distances to other nodes in the network. The
vector distance algorithm was the original ARPANET routing algorithm and was also used in
the internet under the name of RIP (Routing Information Protocol). Examples of
distancevector routing protocols include RIPv1 and RIPv2 and IGRP.

Method
Routers using distance-vector protocol do not have knowledge of the entire path to a
destination.
Instead they use two methods:
1. Direction in which router or exit interface a packet should be forwarded.
2. Distance from its destination
Distance-vector protocols are based on calculating the direction and distance to any link in a
network.
"Direction" usually means the next hop address and the exit interface. "Distance" is a measure
of the cost to reach a certain node. The least cost route between any two nodes is the route
with minimum distance. Each node maintains a vector (table) of minimum distance to every
node. The cost of reaching a destination is calculated using various route metrics. RIP uses
the hop count of the destination whereas IGRP takes into account other information such as
node delay and available bandwidth. Updates are performed periodically in a distance-vector
protocol where all or part of a router's routing table is sent to all its neighbors that are
configured to use the same distance-vector routing protocol. RIP supports cross-platform
distance vector routing whereas IGRP is a Cisco Systems proprietary distance vector routing
protocol. Once a router has this information it is able to amend its own routing table to reflect
the changes and then inform its neighbors of the changes. This process has been described as
routing by rumor‘ because routers are relying on the information they receive from other
routers and cannot determine if the information is actually valid and true. There are a number
of features which can be used to help with instability and inaccurate routing information. EGP
and BGP are not pure distance-vector routing protocols because a distance-vector protocol
calculates routes based only on link costs whereas in BGP, for example, the local route
preference value takes priorityover the link cost.

Count-to-infinity problem
The Bellman–Ford algorithm does not prevent routing loops from happening and suffers from
the count to infinity problem. The core of the count-to-infinity problem is that if A tells B that
it has a path somewhere, there is no way for B to know if the path has B as a part of it. To see
the problem clearly, imagine a subnet connected like A–B–C–D–E–F, and let the metric
between the routers be "number of jumps". Now suppose that A is taken offline. In the
vectorupdate-process B notices that the route to A, which was distance 1, is down – B does
not receive the vector update from A. The problem is, B also gets an update from C, and C is
still not aware of the fact that A is down – so it tells B that A is only two jumps from C (C to
B to A), which is false. This slowly propagates through the network until it reaches infinity
(in which case the algorithm corrects itself, due to the relaxation property of Bellman–Ford).
EXPERIMENT 12:
To learn handling and configuration of networking hardware like RJ-45 connector,
CAT6 cable, crimping tool, etc.

RJ45 Connector
RJ45 is a type of connector commonly used for Ethernet networking. It looks similar to a
telephone jack, but is slightly wider. The "RJ" in RJ45 stands for "registered jack," since it is
a standardized networking interface. The "45" simply refers to the number of the interface
standard. Each RJ45 connector has eight pins, which means an RJ45 cable contains eight
separate wires. Four of them are solid colors, while the other four are striped.

RJ45 cables can be wired in two different ways. One version is called T-568A and the other
is T-568B. These wiring standards are listed below:

T-568A T-568B
1. White/Green (Receive +) 1. White/Orange (Transmit +)
2. Green (Receive -) 2. Orange (Transmit -)
3. White/Orange (Transmit +) 3. White/Green (Receive +)
4. Blue 4. Blue
5. White/Blue 5. White/Blue
6. Orange (Transmit -) 6. Green (Receive -)
7. White/Brown 7. White/Brown
8. Brown 8. Brown
The T-568B wiring scheme is by far the most common, though many devices support the
T568A wiring scheme as well. Some networking applications require a crossover Ethernet
cable, which has a T-568A connector on one end and a T-568B connector on the other. This
type of cable is typically used for direct computer-to-computer connections when there is no
router, hub, or switch available.
Cat 6 Cable
Category 6 is an Ethernet cable standard defined by the Electronic Industries Association
(EIA) and Telecommunications Industry Association (TIA). Cat 6 is the sixth generation of
twisted pair Ethernet cabling that is used in home and business networks. Cat 6 cabling is
backward compatible with the Cat 5 and Cat 5e standards that preceded it.. Compared with
Cat 5 and Cat 5e, Cat 6 features more stringent specifications for crosstalk and system noise.
The cable standard also specifies performance of up to 250 MHz compared to 100 MHz for
Cat 5 and Cat 5e. Cat 6 cable can be identified by the printing on the side of the cable sheath.
Working
Category 6 cables support Gigabit Ethernet data rates of 1 gigabit per second. They can
accommodate 10 Gigabit Ethernet connections over a limited distance 164 feet for a single
cable. Cat 6 cable contains four pairs of copper wire and uses all the pairs for signaling in
order to obtain its high level of performance.

Other basic facts about Cat 6 cables include:

• The ends of a Cat 6 cable use the same RJ-45 standard connector as
previous generations of Ethernet cables.
• The cable is identified as Cat 6 by printed text along the insulation sheath.
• An enhanced version of Cat 6 called Cat 6a supports up to 10 Gbps speeds

Limitations of Cat 6

• As with all other types of twisted pair EIA/TIA cabling, individual Cat 6 cable runs
are limited to a maximum recommended length of 328 feet for their nominal
connection speeds. As mentioned previously, Cat 6 cabling supports 10 Gigabit
Ethernet connections, but not at this full distance.

Crimping tool

A crimping tool is a device used to conjoin two pieces of metal by deforming one or both of
them in a way that causes them to hold each other. The result of the tool's work is called a
crimp. A good example of crimping is the process of affixing a connector to the end of a
cable. For instance, network cables and phone cables are created using a crimping tool
(shown below) to join the RJ-45 and RJ-11 connectors to the both ends of either phone or Cat
5 cable.
Working

To use this crimping tool, each wire is first placed into the connector. Once all the wires are
in the jack, the connectors with wires are placed into the crimping tool, and the handles are
squeezed together. Crimping punctures the plastic connector and holds each of the wires,
allowing for data to be transmitted through the connector.
EXPERIMENT 13:
CONFIGURATION OF ROUTER, HUB, SWITCH ETC. (USING REAL DEVICES
OR SIMULATORS)

Configuration of Router, Hub and Switch

A router is a networking device that forwards data packets between computer networks.
Routers perform the traffic directing functions on the Internet. Data sent through the internet,
such as a web page or email, is in the form of data packets. A packet is
typically forwarded from one router to another router through the networks that constitute
an internetwork (e.g. the Internet) until it reaches its destination node.

A router is connected to two or more data lines from different networks. When a data packet
comes in on one of the lines, the router reads the network address information in the packet to
determine the ultimate destination. Then, using information in its routing table or routing
policy, it directs the packet to the next network on its journey.

The most familiar type of routers are home and small office routers that simply forward IP
packets between the home computers and the Internet. An example of a router would be the
owner's cable or DSL router, which connects to the Internet through an Internet service
provider (ISP). More sophisticated routers, such as enterprise routers, connect large business
or ISP networks up to the powerful core routers that forward data at high speed along
the optical fiber lines of the Internet backbone. Though routers are typically dedicated
hardware devices, software-based routers also exist.

Capabilities of a router
A router has a lot more capabilities than other network devices, such as a hub or a switch that
are only able to perform basic network functions. For example, a hub is often used to transfer
data between computers or network devices, but does not analyze or do anything with the
data it is transferring. By contrast, routers can analyze the data being sent over a network,
change
how it is packaged, and send it to another network or over a different network. For example,
routers are commonly used in home networks to share a single Internet connection between
multiple computers.

Router types:

Wireless (Wi-Fi) router : Wireless routers provide Wi-Fi access to smart phones, laptops,
and other devices with Wi-Fi network capabilities. Also, they may
provide standard Ethernet routing for a small number of wired network devices. Some Wi-Fi
routers can act as a combination router and modem, converting an incoming broadband signal
from your ISP.
Brouter : Short for bridge router, a brouter is a networking device that serves as both
a bridge and a router.
Core router : A core router is a router in a computer network that routes data within a
network, but not between networks.
Virtual router : A virtual router is a backup router used in a Virtual Router Redundancy
Protocol (VRRP) setup.

When multiple routers are used in interconnected networks, the routers can exchange
information about destination addresses using a routing protocol. Each router builds up
a routing table listing the preferred routes between any two systems on the interconnected
networks.
A router has two types of network element components organized onto separate planes:

 Control plane: A router maintains a routing table that lists which route should be used to
forward a data packet, and through which physical interface connection. It does this using
internal preconfigured directives, called static routes, or by learning
routes dynamically using a routing protocol. Static and dynamic routes are stored in the
routing table. The control-plane logic then strips non-essential directives from the table
and builds a forwarding information base (FIB) to be used by the forwarding plane.
 Forwarding plane: The router forwards data packets between incoming and outgoing
interface connections. It forwards them to the correct network type using information that
the packet header contains matched to entries in the FIB supplied by the control plane.

Hub
Hub – A hub is basically a multiport repeater. A hub connects multiple wires coming from
different branches, for example, the connector in star topology which connects different
stations. Hubs cannot filter data, so data packets are sent to all connected devices. In other
words, collision domain of all hosts connected through Hub remains one. Also, they do not
have intelligence to find out best path for data packets which leads to inefficiencies and
wastage.
Types of Hub
Active Hub :- These are the hubs which have their own power supply and can clean , boost
and relay the signal along the network. It serves both as a repeater as well as wiring center.
These are used to extend maximum distance between nodes.
Passive Hub :- These are the hubs which collect wiring from nodes and power supply from
active hub. These hubs relay signals onto the network without cleaning and boosting them
and can’t be used to extend distance between nodes.

An Ethernet hub, active hub, network hub, repeater hub, multiport repeater, or simply hub is
a network hardware device for connecting multiple Ethernet devices together and making
them act as a single network segment. It has multiple input/output(I/O) ports, in
which a signal introduced at the input of any port appears at the output of every port except
the original incoming.[1] A hub works at the physical layer (layer 1) of the OSI model. A
repeater hub also participates in collision detection, forwarding a jam signal to all ports if
it detects a collision. In addition to standard 8P8C ("RJ45") ports, some hubs may also
come with a BNC or an Attachment Unit Interface (AUI) connector to allow
connection to legacy 10BASE2 or 10BASE5 network segments.

To pass data through the repeater in a usable fashion from one segment to the next, the
framing and data rate must be the same on each segment. This means that a repeater cannot
connect an
802.3 segment (Ethernet) and an 802.5 segment (Token Ring) or a 10 Mbit/s segment to
100 Mbit/s Ethernet.

Fast Ethernet classes


100 Mbit/s hubs and repeaters come in two different speed grades: Class I delay the signal for
a maximum of 140 bit times (enabling translation/recoding between 100BASE-TX,
100BASE-
FX and 100BASE-T4) and Class II hubs delay the signal for a maximum of 92 bit times
(enabling installation of two hubs in a single collision domain).

Dual-speed hub
In the early days of Fast Ethernet, Ethernet switches were relatively expensive devices. Hubs
suffered from the problem that if there were any 10BASE-T devices connected then the
whole network needed to run at 10 Mbit/s. Therefore, a compromise between a hub and a
switch was developed, known as a dual-speed hub. These devices make use of an internal
two-port switch, bridging the 10 Mbit/s and 100 Mbit/s segments. When a network device
becomes active on any of the physical ports, the device attaches it to either the 10 Mbit/s
segment or the 100 Mbit/s segment, as appropriate. This obviated the need for an all-or-
nothing migration to Fast Ethernet networks. These devices are considered hubs because the
traffic between devices connected at the same speed is not switched.

Gigabit Ethernet hub


Repeater hubs have been defined for Gigabit Ethernet but commercial products have failed to
appear due to the industry's transition to switching.

Uses

1. For inserting a protocol analyzer into a network connection, a hub is an alternative to


a network tap or port mirroring.

2. A hub with both 10BASE-T ports and a 10BASE2 port can be used to connect a
10BASE2 segment to a modern Ethernet-over-twisted-pair network.

3. A hub with both 10BASE-T ports and an AUI port can be used to connect a 10BASE5
segment to a modern network.

Switch

Switching is the most valuable asset of computer networking. Every time in computer
network you access the internet or another computer network outside your immediate
location, or your messages are sent through a maze of transmission media and connection
devices. The mechanism for exchange of information between different computer networks
and network
segments is called switching in Networking. On the other words we can say that any type
signal or data element directing or Switching toward a particular hardware address or
hardware pieces.

Hardware devices that can be used for switching or transferring data from one location to
another that can use multiple layers of the Open Systems Interconnection (OSI) model.
Hardware devices that can used for switching data in single location like collage lab is
Hardware switch or hub but if you want to transfer data between to different location or
remote location then we can use router or gateways.

For example: whenever a telephone call is placed, there are numerous junctions in the
communication path that perform this movement of data from one network onto another
network. One of another example is gateway, that can be used by Internet Service Providers
(ISP) to deliver a signal to another Internet Service Providers (ISP). For exchange of
information between different locations various types of Switching Techniques are used in
Networking.

Types of Switching Techniques


There are basically three types of switching methods are available.

Circuit Switching
Circuit-switching is the real-time connection-oriented system. In Circuit Switching a
dedicated channel (or circuit) is set up for a single connection between the sender and
recipient during the communication session. In telephone communication system, the normal
voice call is the example of Circuit Switching. The telephone service provider maintain a
unbroken link for each telephone [Link] switching is pass through three phases, that are
circuit establishment, data transfer and circuit disconnect.
Packet Switching
The basic example of Packet Switching is the [Link] Packet Switching, data can be
fragmented into suitably-sized pieces in variable length or blocks that are called packets that
can be routed independently by network devices based on the destination address contained
certain “formatted” header within each packet. The packet switched networks allow sender
and recipient without reserving the circuit. Multiple paths are exist between sender and
recipient in a packet switching [Link] does not require a call setup to transfer packets
between sender and recipient.

Connectionless Packet Switching


It is also known as datagram switching. In this type of network each packet routed
individually by network devices based on the destination address contained within each
packet. Due to each packet is routed individually, the result is that each packet is delivered
out-of-order with different paths of transmission, it depend on the networking devices like
(switches and routers) at any given time. After reaching recipient location, the packets are
reassemble to the original form.

Connection-Oriented Packet Switching


It is also known as virtual circuit switching. In this type of Networking packets are send in
sequential order over a defined route.

Message Switching
Message switching does not set up a dedicated channel (or circuit) between the sender
and recipient during the communication session. In Message Switching each message is
treated as an independent
blocks. The intermediate device stores the message for
a time being, after inspects it for errors, intermediate device transmitting the message to the
next node with its routing information.
Because of this reason message switching networks are called store and forward networks in
networking.
EXPERIMENT 14:
RUNNING AND USING SERVICES/COMMANDS LIKE PING, TRACE ROUTE,
NSLOOKUP, ARP, TELNET, FTP, ETC.

Running and using Service Commands

1. Ping

Ping is a basic Internet program that allows a user to verify that a particular IP
address exists and can accept requests.
Ping is used diagnostically to ensure that a host computer the user is trying to reach is
actually operating. Ping works by sending an Internet Control Message Protocol
(ICMP) Echo Request to a specified interface on the network and waiting for a reply.
Ping can be used for troubleshooting to test connectivity and determine response time.

Ping Command Syntax:


ping [-t] [-a] [-n count] [-l size] [-f] [-i TTL] [-v TOS] [-r count] [-s count] [-w
timeout] [-R] [-S srcaddr] [-p] [-4] [-6] target [/?]
Example : ping

[Link]

ping [Link]

2. Traceroute

A traceroute is a function which traces the path from one network to another. It allows
us to diagnose the source of many problems. The tracert command is a Command
Prompt command that's used to show several details about the path that a packet takes
from the computer or device you're on to whatever destination you specify.

Tracert command syntax:tracert [-d] [-h MaxHops] [-w TimeOut] [-4] [-6] target [/?]

Example:
tracert [Link]
tracert
[Link]
3. Command nslookup
The nslookup (which stands for name server lookup) command is a network utility
program used to obtain information about internet servers. It finds name server
information for domains by querying the Domain Name System.

Command nslookup sends a domain name query packet to a designated (or defaulted)
domain name system (DNS) server. Depending on the system you are using, the
default may be the local DNS name server at your service provider, some
intermediate name server, or the root server system for the entire domain name
system hierarchy.

nslookup command syntax:


nslookup [-SubCommand ...] [{ComputerToFind| [-Server]}]
4. ARP(Address Resolution Protocol)
ARP is used with the IP for mapping a 32-bit Internet Protocol address to a MAC
address that is recognized in the local network specified in RFC 826. Once
recognized, the server or networking device returns a response containing the required
address.

ARP command syntax:


ARP -s inet_addr eth_adr [if_addr]
ARP -d inet_addr [if_addr]
ARP -a [inet_addr] [-N if_addr]

Example: arp
-a
arp -s [Link] 00-50-04-62-F7-23
5. TelNet
Telnet is a user command and an underlying TCP/IP protocol for accessing remote
computers. Through Telnet, an administrator or another user can access someone
else's computer remotely. On the Web, HTTP and FTP protocols allow you to request
specific files from remote computers, but not to actually be logged on as a user of that
computer. With Telnet, you log on as a regular user with whatever privileges you may
have been granted to the specific application and data on that computer.

Telnet command syntax:


telnet [/a] [/e <EscapeChar>] [/f <FileName>] [/l <UserName>] [/t {vt100 | vt52 | ansi |
vtnt}] [<Host> [<Port>]] [/?]
6. FTP(File Transfer Protocol)
File Transfer Protocol (FTP) is the commonly used protocol for exchanging files over
the Internet. FTP uses the Internet's TCP/IP protocols to enable data transfer. FTP
uses a client-server architecture, often secured with SSL/TLS. FTP promotes sharing
of files via remote computers with reliable and efficient data transfer.

FTP command syntax:


FTP [-options] [-s:filename] [-w:buffer] [host]

Connect using FTP:


To connect to another computer using FTP at the MS-DOS prompt, command line, or
Linux shell type FTP and press Enter. :
open [Link]

Commands to run at the FTP: prompt

1. append local-file [remote-file] : Append a local file to a file on the remote computer.

2. ascii: Set the file transfer type to ASCII, the default. In ASCII text mode, character-set
and end-of-line characters are converted as necessary.

3. bell: Toggle a bell to ring after each command. By default, the bell is off.

4. binary: Set the file transfer type to binary. Use `Binary' for transferring executable
program files or binary data files e.g. Oracle

5. bye : End the FTP session and exit ftp

6. cd: Change the working directory on the remote host.

7. close : End the FTP session and return to the cmd prompt.

8. debug : Toggle debugging. When debug is on, FTP will display every command.

9. delete remote-file: Delete file on remote host.

10. dir [remote-directory] [local-file]: List a remote directory's files and subdirectories.(or
save the listing to local-file)

11. disconnect: Disconnect from the remote host, retaining the ftp prompt.

12. get remote-file [local-file]: Copy a remote file to the local PC.

13. glob : Toggle the use of wildcard characters in local [Link] default, globbing is on.
14. hash : Toggle printing a hash (#) for each 2K data block transferred. By default, hash
mark printing is off.

15. help [command] Display help for ftp command.

16. lcd [directory] Change the working directory on the local PC. By default, the
working directory is the directory in which ftp was started.

17. literal argument: Send arguments, as-is, to the remote FTP host.

18. ls [remote-directory] [local-file] List a remote directory's files and folders.

19. mdelete remote-files [ ...] Delete files on remote host.

20. mget remote-files [ ...] Copy multiple remote files to the local PC.

21. status Display the current status of FTP connections and toggles.

22. trace Toggles packet tracing; trace displays the route of each packet

23. verbose Toggle verbose mode. By default, verbose is on.

24. ! command Run command on the local PC.


EXPERIMENT 15:
NETWORK PACKET ANALYSIS USING TOOLS LIKE WIRESHARK,
TCPDUMP, ETC.

Network Packet Analysis Tools


A packet analyzer (also known as a packet sniffer) is a computer program or piece
of computer hardware that can intercept and log traffic that passes over a digital
network or part of a network.


Packet capture is the process of intercepting and logging traffic.


As data streams flow across the network, the sniffer captures each packet and, if
needed, decodes the packet's raw data, showing the values of various fields in
the packet, and analyzes its content according to the appropriate RFC or other
specifications.


A packet analyzer used for intercepting traffic on wireless networks is known as a
wireless analyzer or WiFi analyzer.


A packet analyzer can also be referred to as a network analyzer or
protocol analyzerthough these terms also have other meanings.

Tools

1. Wireshark
2. Tcpdump
Wireshark


Wireshark is a free and open-source packet analyzer.


It is used for network troubleshooting, analysis, software and communications
protocol development, and education. Originally named Ethereal, the project was
renamed Wireshark in May 2006 due to trademark issues.


Wireshark is cross-platform, using the Qt widget toolkit in current releases
to implement its user interface, and using pcap to capture packets.


It runs on Linux, macOS, BSD, Solaris, some other Unix-like operating systems,
and Microsoft Windows.

There is also a terminal-based (non-GUI) version called TShark.

• Wireshark, and the other programs distributed with it such as TShark, are
free software, released under the terms of the GNU General Public License.

Functionality


Wireshark is very similar to tcpdump, but has a graphical front-end, plus
some integrated sorting and filtering options.


Wireshark lets the user put network interface controllers into promiscuous mode (if
supported by the network interface controller), so they can see all the traffic visible
on that interface including unicast traffic not sent to that network interface
controller's MAC address.


However, when capturing with a packet analyzer in promiscuous mode on a port on
a network switch, not all traffic through the switch is necessarily sent to the port
where the capture is done, so capturing in promiscuous mode is not necessarily
sufficient to see all network traffic.
• Port mirroring or various network taps extend capture to any point on the
network. Simple passive taps are extremely resistant to tampering.

On GNU/Linux, BSD, and macOS, with libpcap 1.0.0 or later, Wireshark 1.4 and
later can also put wireless network interface controllers into monitor mode.


If a remote machine captures packets and sends the captured packets to a
machine running Wireshark using the TZSP protocol or the protocol used by
OmniPeek, Wireshark dissects those packets, so it can analyze packets captured
on a remote machine at the time that they are captured.

Features

Wireshark is a data capturing program that "understands" the structure (encapsulation) of


different networking protocols.
It can parse and display the fields, along with their meanings as specified by different
networking protocols.
Wireshark uses pcap to capture packets, so it can only capture packets on the types of
networks that pcap supports.


Data can be captured "from the wire" from a live network connection or read from
a file of already-captured packets.

Live data can be read from different types of networks, including Ethernet,
IEEE 802.11, PPP, and loopback.

Captured network data can be browsed via a GUI, or via the terminal (command
line) version of the utility, TShark.

Captured files can be programmatically edited or converted via command-line
switches to the "editcap" program.

Data display can be refined using a display filter.
• Plug-ins can be created for dissecting new protocols.
• VoIP calls in the captured traffic can be detected. If encoded in a compatible
encoding, the media flow can even be played.

Raw USB traffic can be captured.


Wireless connections can also be filtered as long as they traverse the
monitored Ethernet.

Various settings, timers, and filters can be set to provide the facility of filtering
the output of the captured traffic.

Tcpdump


Tcpdump is a common packet analyzer that runs under the command line.

It allows the user to display TCP/IP and other packets being transmitted or
received over a network to which the computer is attached.


Distributed under the BSD license, tcpdump is free software.


Tcpdump works on most Unix-like operating systems: Linux,
Solaris, FreeBSD, DragonFly
BSD, NetBSD, OpenBSD, OpenWrt, macOS, HP-UX 11i, and AIX.


In those systems, tcpdump uses the libpcap library to capture packets.


The port of tcpdump for Windows is called WinDump; it uses WinPcap, the
Windows port of libpcap.
Functionality


Tcpdump prints the contents of network packets. It can read packets from a
network interface card or from a previously created saved packet file.


Tcpdump can write packets to standard output or a file.


It is also possible to use tcpdump for the specific purpose of intercepting
and displaying the communications of another user or computer.


A user with the necessary privileges on a system acting as a router or gateway
through which unencrypted traffic such as Telnet or HTTP passes can use tcpdump to
view login IDs, passwords, the URLs and content of websites being viewed, or any
other unencrypted information.


The user may optionally apply a BPF-based filter to limit the number of packets
seen by tcpdump; this renders the output more usable on networks with a high
volume of traffic.

Priveleges Required


In some Unix-like operating systems, a user must have super user privileges to use
tcpdump because the packet capturing mechanisms on those systems require
elevated privileges. However, the -Z option may be used to drop privileges to a
specific unprivileged user after capturing has been set up.

In other Unix-like operating systems, the packet capturing mechanism can be
configured to allow non-privileged users to use it; if that is done, super user
privileges are not required.
EXPERIMENT 16:
NETWORK SIMULATION USING TOOLS LIKE CISCO PACKET TRACER,
NETSIM, OMNET++, NS2, NS3, ETC.
Network simulation tools

Network Simulator provides an integrated, versatile, easy-to-use GUI-based network designer


tool to design and simulate a network with SNMP, TL1, TFTP, FTP, Telnet and Cisco IOS
device.

List of Network Simulators:

There are different network simulators which offer different features. we have listed
different network simulators and sample program code

• Ns2 (Network Simulator 2).


• Ns3 (Network Simulator 3).
• OPNET.
• OMNeT++.
• NetSim.
• REAL.
• QualNet.
• J-Sim.

Network simulator

A network simulator is software that predicts the behavior of a computer network. Since
communication networks have become too complex for traditional analytical methods to
provide an accurate understanding of system behavior, network simulators are used. In
simulators, the computer network is modeled with devices, links, applications etc. and the
network performance is reported. Simulators come with support for the most popular
technologies and networks in use today such as Wireless LANs, mobile ad hoc networks,
wireless sensor networks, vehicular ad hoc networks, cognitive radio networks, LTE /
LTE- 5G, Internet of Things (IoT) etc.

Simulations

Most of the commercial simulators are GUI driven, while some network simulators are CLI
driven. The network model / configuration describes the network (nodes, routers, switches,
links) and the events (data transmissions, packet error etc.). Output results would include
network level metrics, link metrics, device metrics etc. Further, drill down in terms of
simulations trace files would also be available. Trace files log every packet, every event that
occurred in the simulation and are used for analysis. Most network simulators use discrete
event simulation, in which a list of pending "events" is stored, and those events are processed
in order, with some events triggering future events—such as the event of the arrival of a
packet at one node triggering the event of the arrival of that packet at a downstream node.
Network emulation

Network emulation allows users to introduce real devices and applications into a test network
(simulated) that alters packet flow in such a way as to mimic the behavior of a live network.
Live traffic can pass through the simulator and be affected by objects within the simulation.
The typical methodology is that real packets from a live application are sent to the emulation
server (where the virtual network is simulated). The real packet gets 'modulated' into a
simulation packet. The simulation packet gets demodulated into a real packet after
experiencing effects of loss, errors, delay, jitter etc., thereby transferring these network
effects into the real packet. Thus it is as-if the real packet flowed through a real network but
in reality it flowed through the simulated network.
Emulation is widely used in the design stage for validating communication networks prior
to deployment.

Uses of network simulators

Network simulators provide a cost-effective method for • Network

design validation for enterprises / data centers / sensor networks etc.

• Network R & D (More than 70% of all Network Research paper reference a
network simulator)[citation needed]
• Defense applications such as HF / UHF / VHF Radio based MANET Radios,
Naval communications, Tactical data links etc.
• LTE, LTE-Adv, IOT, VANET simulations
• Education - Lab experimentation and R & D. Most universities use a network simulator
for teaching / R & D since its too expensive to buy hardware equipment
There are a wide variety of network simulators, ranging from the very simple to the very
complex. Minimally, a network simulator must enable a user to

• Model the network topology specifying the nodes on the network and the links
between those nodes
• Model the application flow (traffic) between the nodes
• Providing network performance metrics as output
• Visualization of the packet flow
• Technology / protocol evaluation and device designs
• Logging of packet/events for drill down analyses / debugging

NS2 (Network Simulator 2)

• It is a discrete event simulator that provides substantial support for simulation of


TCP, routing, and multicast protocols over wired and wireless networks.
• It use C++ and OTcl languages.
• Sample ns2 code. In which there are four different nodes are available and two
different routers.

Ns is a discrete event simulator targeted at networking research. Ns provides substantial support


for simulation of TCP, routing, and multicast protocols over wired and wireless (local and
satellite) networks.

Ns began as a variant of the REAL network simulator in 1989 and has evolved substantially over
the past few years. In 1995 ns development was supported by DARPA through the VINT
project at LBL, Xerox PARC, UCB, and USC/ISI. Currently ns development is supported
through DARPA with SAMAN and through NSF with CONSER, both in collaboration with
other researchers including ACIRI. Ns has always included substantal contributions from
other researchers, including wireless code from the UCB Daedelus and CMU Monarch
projects and Sun Microsystems.

NS3 (Network Simulator 3):


In 2006, a team led by Tom Henderson, George Riley, Sally Floyd, and Sumit Roy, applied
for and received funding from the U.S. National Science Foundation (NSF) to build a
replacement for ns-2, called ns-3. This team collaborated with the Planete project of
INRIA at Sophia Antipolis, with Mathieu Lacage as the software lead, and formed a new
open source project. In the process of developing ns-3, it was decided to completely abandon
backwardcompatibility with ns-2. The new simulator would be written from scratch,
using the C++programming language. Development of ns-3 began in July 2006.
Current status of the three versions is:

• Ns3development stopped when ns-2 was founded. It is no longer developed


nor maintained.
• Ns3development stopped around 2010. It is no longer developed nor maintained.
• Ns3is actively being developed and maintained.
• Ns3 uses C++ and Python languages for simulating the script.
• C++ used for implementation of simulation and core model. Ns-3 is built as a library
which may be statically or dynamically linked to a C++ main program. • Python:
C++ wrapped by Python. Python programs to import an “ns3” module • Sample code
for ns3.

Cisco packet tracer

Packet Tracer is a cross-platform visual simulation tool designed by Cisco Systems that
allows users to create network topologies and imitate modern computer networks. The
software allows users to simulate the configuration of Cisco routers and switches using a
simulated command line interface. Packet Tracer makes use of a drag and drop user
interface, allowing users to add and remove simulated network devices as they see fit.
The
software is mainly focused towards Certified Cisco Network Associate Academy students
as an educational tool for helping them learn fundamental CCNA concepts. Previously
students enrolled in a CCNA Academy program could freely download and use the tool
free of charge for educational use.

Overview

Packet Tracer can be run on Linux and Microsoft Windows and also macOS. Similar Android
and iOS apps are also available. Packet Tracer allows users to create simulated network
topologies by dragging and dropping routers, switches and various other types of network
devices. A physical connection between devices is represented by a "cable" item. Packet
Tracer supports an array of simulated Application Layer protocols, as well as basic routing
with RIP, OSPF, EIGRP, BGP, to the extents required by the current CCNA curriculum. As
of version 5.3, Packet Tracer also supports the Border Gateway Protocol.

In addition to simulating certain aspects of computer networks, Packet Tracer can also be
used for collaboration. As of Packet Tracer 5.0, Packet Tracer supports a multi-user system
that enables multiple users to connect multiple topologies together over a computer network.
[6]
Packet Tracer also allows instructors to create activities that students have to complete.
[2]
Packet Tracer is often used in educational settings as a learning aid. Cisco Systems claims
that Packet Tracer is useful for network experimentation.

Role in Education

Packet Tracer allows students to design complex and large networks, which is often not
feasible with physical hardware, due to costs. Packet Tracer is commonly used by CCNA
Academy students, since it is available to them for free. However, due to functional
limitations, it is intended by CISCO to be used only as a learning aid, not a replacement for
Cisco routers and switches. The application itself only has a small number of features found
within the actual hardware running a current Cisco IOS version. Thus, Packet Tracer is
unsuitable for modelling production networks. It has a limited command set, meaning it is not
possible to practice all of the IOS commands that might be required. Packet Tracer can be
useful for understanding abstract networking concepts, such as the Enhanced Interior
Gateway Routing Protocol by animating these elements in a visual form. Packet Tracer is also
useful in education by providing additional components, including an authoring system,
network protocol simulation and improving knowledge an assessment system.
Netsim

1) It has an object-oriented system modeling and simulation (M&S) environment


to support simulation and analysis of voice and data communication scenarios for High
Frequency Global Communication Systems (HFGCS).

2) NetSim use java as a programming language it creates applet and linked into
HTML document for viewable on the java-compatible browser.

Netsim Standard version

1. Easy to use GUI allows users to simply drag and drop devices, links and applications.
2. Results dashboard provides appealing simulation performance reports with tables
& graphs.
3. Inbuilt graphing with extensive formatting (axes, colours, zoom, titles etc).
4. Wide range of technologies including the latest in IOT, WSN, MANET,
Cognitive Radio, 802.11 n / ac, TCP, BIC / CUBIC, Rate adaptation with packet
and event tracing.
5. Online debug capability and ability to "watch" all variables.
6. Run animation in parallel for immediate visual feedback.
EXPERIMENT 17:
SOCKET PROGRAMMING USING UDP AND TCP (DATA &
TIME CLIENT/SERVER, ECHO CLIENT/SERVER, ITERATIVE &
CONCURRENT SERVERS)

(i) Programs using TCP Sockets to implement DATE AND TIME Server & client.

OBJECTIVE: To implement date and time display from client to server using TCP Sockets.

DESCRIPTION: TCP Server gets the system date and time and opens the server socket to read
the client details. Client send its address to the server. Then client receives the date and time
from server to display. TCP socket server client connection is opened for communication.
After the date time is displayed the server client connection is closed with its respective
streams to be closed.

ALGORITHM:

Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Send server‟s date and time to the client.
4. Read client‟s IP address sent by the client.
5. Display the client details.
6. Repeat steps 2-5 until the server is terminated.
7. Close all streams.
8. Close the server socket.
9. Stop.

Client
1. Create a client socket and connect it to the server‟s port number.
2. Retrieve its own IP address using built-in function.
3. Send its address to the server.
4. Display the date & time sent by the server.
5. Close the input and output streams.
6. Close the client socket.
7. Stop.

PROGRAM:
//TCP Date [Link] import [Link].*; import
[Link].*; import [Link].*; class tcpdateserver

{ public static void main(String


arg[])
{
ServerSocket ss = null; Socket cs; PrintStream ps; BufferedReader dis; String
inet;
try
{ ss = new ServerSocket(4444);
[Link]("Press Ctrl+C to quit"); while(true){
cs = [Link]();
ps = new PrintStream([Link]()); Date d = new Date();
[Link](d);
dis = new BufferedReader(new InputStreamReader([Link]())); inet
= [Link]();
[Link]("Client System/IP address is :"+ inet); [Link]();
[Link]();
}
}
catch(IOException e)
{
[Link]("The exception is :" + e);
}
}
}

// TCP Date [Link]


import [Link].*;
import [Link].*; class tcpdateclient
{ public static void main (String
args[])
{
Socket soc; BufferedReader dis; String sdate; PrintStream ps;
try
{
InetAddress ia = [Link](); if ([Link] == 0) soc
= new Socket([Link](),4444); else
soc = new Socket([Link](args[0]),4444); dis =
new BufferedReader(new
InputStreamReader([Link]()));
sdate=[Link]();
[Link]("The date/time on server is : " +sdate); ps = new
PrintStream([Link]()); [Link](ia); [Link]();
catch(IOException e)
{
[Link]("THE EXCEPTION is :" + e); }
}}

OUTPUT
Server: $ javac
[Link] $
java tcpdateserver
Press Ctrl+C to quit
Client System/IP address is : [Link]/[Link] Client
System/IP address is :
[Link]/[Link]
Client:
$javac [Link]
$ java tcpdateclient
The date/time on server is: Wed Jul 06 07:12:03 GMT 2011

Every time when a client connects to the server, server‟s date/time will be returned to
the client for synchronization.

RESULT:
Thus the program for implementing to display date and time from client to server using
TCP Sockets was executed successfully and output verified using various samples.
(ii) Programs using TCP Sockets to implement Echo server & client.

OBJECTIVE: To implementation of echo client server using TCP/IP

DESCRIPTION: TCP Server gets the message and opens the server socket to read the
client details. Client sends its address to the server. Then client receives the message from
server to display.

ALGORITHM
Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection arrives, accept it.
3. Read the data from client.
4. Echo the data back to the client.
5. Repeat steps 4-5 until „bye‟ or „null‟ is read.
6. Close all streams.
7. Close the server socket.
8. Stop.
Client
1. Create a client socket and connect it to the server‟s port number.
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send user data to the server.
5. Display the data echoed by the server.
6. Repeat steps 2-4.
7. Close the input and output streams.
8. Close the client socket.
9. Stop.

PROGRAM:

// TCP Echo [Link]


import [Link].*; import [Link].*; public class
tcpechoserver
{ public static void main(String[] arg) throws
IOException
{
ServerSocket sock = null; BufferedReader fromClient = null;
OutputStreamWriter toClient = null; Socket client = null;
try {
sock = new ServerSocket(4000); [Link]("Server Ready"); client =
[Link](); [Link]("Client Connected"); fromClient =
new BufferedReader(new InputStreamReader([Link]())); toClient = new
OutputStreamWriter([Link]()); String line; while
(true)
{
line = [Link]();
if ( (line == null) || [Link]("bye")) break;
[Link] ("Client [ " + line + " ]"); [Link]("Server [ "+ line +"
]\n"); [Link]();
}
[Link]();
[Link]();
[Link]();
[Link]();
[Link]("Client Disconnected");
} catch (IOException
ioe)
{ [Link](ioe);
}
}
}

//TCP Echo [Link]


import [Link].*; import
[Link].*; public
class tcpechoclient
{ public static void main(String[] args) throws
IOException
{
BufferedReader fromServer = null, fromUser = null; PrintWriter toServer =
null;
Socket sock = null; try
{ if
([Link] == 0)
sock = new Socket([Link](),4000); else
sock = new Socket([Link](args[0]),4000); fromServer = new
BufferedReader(new InputStreamReader([Link]()));
fromUser = new BufferedReader(new
InputStreamReader([Link])); toServer = new
PrintWriter([Link](),true);
String Usrmsg, Srvmsg; [Link]("Type \"bye\" to quit"); while (true)
{
[Link]("Enter msg to server : "); Usrmsg = [Link](); if
(Usrmsg==null || [Link]("bye"))
{ [Link]("bye");
break;
}
else [Link](Usrmsg);
Srvmsg = [Link](); [Link](Srvmsg);
}
[Link]();
[Link]();
[Link](); [Link]();
} catch (IOException
ioe)
{ [Link](ioe);
}

OUTPUT
Server:

$ javac [Link] $ java tcpechoserver


Server Ready Client Connected Client [ hello ]
Client [ how are you ] Client [ i am fine ] Client [
ok ] Client Disconnected Client :
$ javac [Link] $ java tcpechoclient Type "bye" to quit

Enter msg to server : hello Server [ hello ]


Enter msg to server : how are you Server [ how are you ]
Enter msg to server : i am fine Server [ i am fine ]
Enter msg to server : ok Server [ ok ]
Enter msg to server : bye
RESULT
Thus data from client to server is echoed back to the client to check reliability/noise level of
the channel.

(iii) Programs using TCP Sockets to implement chat Server & Client.

OBJECTIVE: To implement a chat server and client in java using TCP sockets.

DESCRIPTION: TCP Clients sends request to server and server will receives the request
and response with acknowledgement. Every time client communicates with server and
receive response from it.

ALGORITHM:

Server
1. Create a server socket and bind it to port.
2. Listen for new connection and when a connection
arrives, accept it.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop Client
1. Create a client socket and connect it to the server‟s port number
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop
PROGRAM:
//[Link] import
[Link].*; import
[Link].*;
class Server {
public static void main(String args[]) { String data = "Networks
Lab"; try {

ServerSocket srvr = new ServerSocket(1234); Socket skt = [Link]();


[Link]("Server has connected!\n");
PrintWriter out = new PrintWriter([Link](),
true); [Link]("Sending string: '" + data + "'\n");
[Link](data);
[Link](); [Link]();
[Link]();
}
catch(Exception e) { [Link]("Whoops! It didn't work!\n");
}
}
}

//[Link]
import [Link].*; import [Link].*; class Client { public static
void main(String args[]) { try {
Socket skt = new Socket("localhost", 1234); BufferedReader in = new
BufferedReader(new
InputStreamReader([Link]()));
[Link]("Received string: '"); while (![Link]()) {} [Link]([Link]());
[Link]("'\n"); [Link]();
}
catch(Exception e) { [Link]("Whoops! It didn't work!\n");
}}}
OUTPUT
Server:

$ javac [Link] $ java Server


Server started Client connected
Cilent
$ javac [Link] $ java Client

RESULT
Thus both the client and server exchange data using TCP socket programming.

(iv) Programs using UDP Sockets to implement Chat server & client.

OBJECTIVE: To implement a chat server and client in java using UDP sockets.

DESCRIPTION: UDP is a connectionless protocol and the socket is created for client and
server to transfer the data. Socket connection is achieved using the port number. Domain
Name System is the naming convention that divides the Internet into logical domains
identified in Internet Protocol version 4 (IPv4) as a 32-bit portion of the total address.

ALGORITHM:

Server
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to client port.
3. Create a datagram packet to receive client message.
4. Wait for client's data and accept it.
5. Read Client's message.
6. Get data from user.
7. Create a datagram packet and send message through server port.
8. Repeat steps 3-7 until the client has something to send.
9. Close the server socket.
10. Stop.
Client
1. Create two ports, server port and client port.
2. Create a datagram socket and bind it to server port.
3. Get data from user.
4. Create a datagram packet and send data with server ip address and
client port.
5. Create a datagram packet to receive server message.
6. Read server's response and display it.
7. Repeat steps 3-6 until there is some text to send.
8. Close the client socket.
9. Stop.

PROGRAM

// UDP Chat [Link]


import [Link].*;
import [Link].*; class udpchatserver
{
public static int clientport = 8040,serverport = 8050; public static void
main(String args[]) throws Exception
{
DatagramSocket SrvSoc = new DatagramSocket(clientport); byte[] SData
= new
byte[1024];
BufferedReader br = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Server Ready");
while (true)
{
byte[] RData = new byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,[Link]);
[Link](RPack);
String Text = new String([Link]()); if ([Link]().length() == 0)
break;
[Link]("\nFrom Client <<< " + Text ); [Link]("Msg to
Cleint : " );
String srvmsg = [Link](); InetAddress IPAddr = [Link]();
SData = [Link]();
DatagramPacket SPack = new
DatagramPacket(SData,[Link],IPAddr, serverport);
[Link](SPack);
}
[Link]("\nClient Quits\n"); [Link]();
}
}

// UDP Chat [Link]


import
[Link].*;
import [Link].*; class udpchatclient
{
public static int clientport = 8040,serverport = 8050; public static
void main(String args[]) throws Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader
([Link])); DatagramSocket CliSoc = new
DatagramSocket(serverport); InetAddress IPAddr; String Text; if
([Link] == 0)
IPAddr = [Link](); else
IPAddr = [Link](args[0]); byte[] SData = new byte[1024];
[Link]("Press Enter without text to quit"); while (true)
{
[Link]("\nEnter text for server : "); Text = [Link]();
SData = [Link]();
DatagramPacket SPack = new DatagramPacket(SData,[Link],
IPAddr, clientport ); [Link](SPack); if
([Link]().length() == 0) break; byte[] RData = new
byte[1024];
DatagramPacket RPack = new DatagramPacket(RData,[Link]);
[Link](RPack);
String Echo = new String([Link]()) ; Echo = [Link]();
[Link]("From Server <<< " + Echo);
}
[Link]();
}
}

OUTPUT
Server

$ javac [Link] $ java udpchatserver Server Ready


From Client <<< are u the SERVER Msg to Cleint : yes
From Client <<< what do u have to serve Msg to Cleint : no eatables
Client Quits

Client

$ javac [Link]$ java udpchatclient Press Enter without text to quit


Enter text for server : are u the SERVER From Server <<< yes
Enter text for server : what do u have to serve From Server <<< no eatables
Enter text for server : Ok

(V) Program using DNS server to resolve a given host name.

OBJECTIVE: To develop a client that contacts a given DNS server to resolve a given
hostname.

DESCRIPTION: Get the host name to be resolve using gethostname()


· Check the host name using nslookup
· Print the IP address, host name, Address length and Address type.
· List the addresses stored in lookup

ALGORITHM:

Step 1. Find the host name by using gethostbyname().


Step 2. The host name is followed by the list of alias names.
Step 3. Pointer points to the array of pointers to the individual address.
Step 4. For each address call the inet_ntop() and print the returned
string.
PROGRAM:

#include<stdio.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<netinet/in.h>
int main(int
argc,char**argv)
{
char h_name; int h_type;

struct hostent *host; struct in_addr h_addr; if(argc!=2)


{ fprintf(stderr,"USAGE:nslookup\n");
} if((host=gethostbyname(argv[1]))==NULL)
{ fprintf(stderr,"(mini)nslookup failed on
%s\n",argv[1]);

h_addr.s_addr=*((unsigned long*)host->h_addr_list[0]); printf("\n


IP ADDRESS=%s\n",inet_ntoa(h_addr));

printf("\n HOST NAME=%s\n",host->h_name); printf("\nADDRESS LENGTH


=%d\n",host->h_length); printf("\nADDRESS TYPE=%d\n",host-
>h_addrtype); printf("\nLIST OF ADDRESS=%s\n",inet_ntoa(h_addr_list[0]));
}
OUTPUT
[it28@localhost ~]$ vi dns.c [it28@localhost ~]$ cc dns.c [it28@localhost ~]$ ./[Link]
[Link] IP
ADDRESS=[Link] HOST
NAME=[Link]
ADDRESS LENGTH =4 ADDRESS
TYPE=2 LIST OF ADDRESS=[Link]
Result
Hence the program to develop a client that contacts a given DNS server to resolve a
given host name is executed successfully.

(VI) Program using UDP socket to implement DNS Server/Client.

OBJECTIVE: To implement a DNS server and client in java using UDP sockets.

DESCRIPTION: DNS stands for domain name system. unique name of the host is identified
with its IP address through server client communication.

ALGORITHM:

Server
1. Create an array of hosts and its ip address in another array
2. Create a datagram socket and bind it to a port
3. Create a datagram packet to receive client request
4. Read the domain name from client to be resolved
5. Lookup the host array for the domain name
6. If found then retrieve corresponding address
7. Create a datagram packet and send ip address to client
8. Repeat steps 3-7 to resolve further requests from clients
9. Close the server socket
10. Stop

Client
1. Create a datagram socket
2. Get domain name from user
3. Create a datagram packet and send domain name to the server
4. Create a datagram packet to receive server message5. Read server's response
6. If ip address then display it else display "Domain does not exist"
7. Close the client socket
8. Stop

PROGRAM
// UDP DNS Server -- [Link] import [Link].*;
import [Link].*; public
class udpdnsserver
{ private static int indexOf(String[] array, String
str)
{
str = [Link]();
for (int i=0; i < [Link]; i++)
{
if (array[i].equals(str)) return i;
} return
- 1;
}

public static void main(String arg[])throws IOException


{
String[] hosts = {"[Link]", "[Link]","[Link]", "[Link]"}; String[] ip =
{"[Link]",
"[Link]","[Link]", "[Link]"};
[Link]("Press Ctrl + C to Quit"); while (true)
{
DatagramSocket serversocket=new DatagramSocket(1362); byte[] senddata =
new byte[1021];
byte[] receivedata = new byte[1021]; DatagramPacket recvpack = new
DatagramPacket(receivedata,

[Link]); [Link](recvpack);
String sen = new String([Link]()); InetAddress ipaddress = [Link]();
int port = [Link]();
String capsent;
[Link]("Request for host " + sen);
if(indexOf (hosts, sen) != -1) capsent = ip[indexOf (hosts, sen)]; else capsent

= "Host Not Found"; senddata = [Link]();

DatagramPacket pack = new


DatagramPacket(senddata,
[Link],ipaddress,port); [Link](pack);

[Link]();
}
}
}

//UDP DNS Client -- [Link]

import [Link].*;
import [Link].*;
public class
udpdnsclient
{ public static void main(String args[])throws
IOException
{
BufferedReader br = new
BufferedReader(new
InputStreamReader([Link])); DatagramSocket clientsocket = new
DatagramSocket();
InetAddress ipaddress; if ([Link] == 0) ipaddress = [Link](); else
ipaddress = [Link](args[0]); byte[] senddata = new
byte[1024];
byte[] receivedata = new byte[1024]; int portaddr = 1362;
[Link]("Enter the hostname : "); String sentence = [Link]();
Senddata = [Link]();
DatagramPacket pack = new DatagramPacket(senddata,[Link],
ipaddress,portaddr); [Link](pack);
DatagramPacket recvpack
=new
DatagramPacket(receivedata,[Link]);
[Link](recvpack);
String modified = new String([Link]()); [Link]("IP
Address: " + modified); [Link](); }}
OUTPUT

Server

$ javac [Link] $ java udpdnsserver Press Ctrl + C to Quit


Request for host [Link] Request for host [Link] Request for host
[Link]

Client

$ javac [Link] $ java


udpdnsclient Enter the hostname :
[Link]
IP Address: [Link] $ java
udpdnsclient Enter the hostname :
[Link]
IP Address: [Link] $ java udpdnsclient
Enter the hostname : [Link]
IP Address: Host Not Found

RESULT:

Thus domain name requests by the client are resolved into their respective logical
address using lookup method.

You might also like