0% found this document useful (0 votes)
8 views150 pages

IT5511 - 2022506101 Record

This document is a practical record for the IT5511 Computer Networks Laboratory submitted by Anselm Flavian P. at the Madras Institute of Technology. It includes a bonafide certificate, a list of experiments conducted, and detailed descriptions of various networking commands and socket programming applications using TCP and UDP protocols. The document serves as a comprehensive record of practical work and experiments performed during the course.
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)
8 views150 pages

IT5511 - 2022506101 Record

This document is a practical record for the IT5511 Computer Networks Laboratory submitted by Anselm Flavian P. at the Madras Institute of Technology. It includes a bonafide certificate, a list of experiments conducted, and detailed descriptions of various networking commands and socket programming applications using TCP and UDP protocols. The document serves as a comprehensive record of practical work and experiments performed during the course.
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
You are on page 1/ 150

IT5511

COMPUTER NETWORKS LABORATORY

A PRACTICAL RECORD

Submitted by
Anselm Flavian P. (2022506101)
B.Tech (5/8)

DEPARTMENT OF INFORMATION TECHNOLOGY


MADRAS INSTITUTE OF TECHNOLOGY
ANNA UNIVERSITY
CHENNAI - 600044

1
BONAFIDE CERTIFICATE

Name : Anselm Flavian P.

Reg. No : 2022506101

Subject : IT5511 COMPUTER NETWORKS LABORATORY


Department : Information Technology

Certified to the Bonafide record of practical work done by Mr.Anselm Flavian


P in the IT5511 Computer Networks Laboratory during the period

Date: Dr. Vallisree

STAFF-IN-CHARGE

Submitted for the Practical Examination held on:

Internal Examiner External


Examiner
Sno Date Topic Pno Signature

2
1 5/8/24 STUDY OF BASIC NETWORK 4
COMMANDS

2 12/8/24 SOCKET PROGRAMMING USING TCP – 14


ECHO AND CLIENT

3 24/8/24 SOCKET PROGRAMMING USING UDP – 30


ECHO AND CLIENT

4 31/8/24 HTTP PROTOCOL – GET AND POST 44

5 2/9/24 FILE TRANSFER PROTOCOL 64

6 2/9/24 DOMAIN NAME SERVER 78

7 9/9/24 SIMPLE MAIL TRANSFER PROTOCOL 84

8 POST OFFICE PROTOCOL 96

9 PING COMMAND 102

10 7/10/24 STUDY OF NS2 108

11 7/10/24 NETWORK TOPOLOGY USING NS2 122

12 7/10/24 WIRED NETWORK USING TCP 126

13 14/10/24 WIRELESS NETWORK USING UDP 130

14 21/10/24 NETWORK PERFORMANCE USING 138


XGRAPH

15 4/11/24 RIP AND OSPF 144

16 4/11/24 SLAAC AND DHCP 148

INDEX

3
EXP NO:01 STUDY OF BASIC NETWORK COMMANDS
DATE: 5/8/24

Aim:

To get introduced on basic commands related to Networking on Windows.

Commands and output:

1) Ipconfig:

Displays all current TCP/IP network configuration values and refreshes


Dynamic Host Configuration Protocol (DHCP) and Domain Name System
(DNS) settings. Used without parameters, ipconfig displays the IP address,
subnet mask, and default gateway for all adapters.

4
2) Ping command:

The Ping command is used to check the destination IP address to be reached and
record the results. The ping command displays whether the destination
responded and how long it took to receive a reply. If there is an error in the
delivery to the destination, the ping command displays an error message.

3) Traceroute command:

Traceroute command (tracert) is a utility designed for displaying the time it


takes for a packet of information to travel between a local computer and a
destination IP address or domain. After running a traceroute command, the
results displayed are a list of the 'hops' that data packets take along their path to
the designated IP address or domain.

5
4) Pathping command:

The pathping command is a route tracing tool that combines features of the ping
and tracert commands with additional information that neither of those tools
provides. The pathping command sends packets to each router on the way to a
final destination over a period of time, and then computes results based on the
packets returned from each hop. Since the command shows the degree of packet
loss at any given router or link, it is easy to determine which routers or links
might be causing network problem.

5) Arp command:

The address resolution protocol (arp) is a protocol used by the Internet Protocol
(IP), specifically IPv4, to map IP network addresses to the hardware addresses
used by a data link protocol. The protocol operates below the network layer as a
part of the interface between the OSI network and OSI link layer. It is used
when IPv4 is used over Ethernet. The term address resolution refers to the
process of finding an address of a computer in a network. The address is
"resolved" using a protocol in which a piece of information is sent by a client
process executing on the local computer to a server process executing on a
remote computer. The information received by the server allows the server to
uniquely identify the network system for which the address was required and
therefore to provide the required address. The address resolution procedure is
completed when the client receives a response from the server containing the
required address.

6
6) Hostname command:

Display the hostname of the machine the command is being run on.

7) Netstat command:

The netstat command is used to display the TCP/IP network protocol statistics
and information.

7
8) Route command:

Command to manually configure the routes in the routing table.

8
9) Nslookup command:

MS-DOS utility that enables a user to look up an IP address of a domain or host


on a network.

9
10) Nbstat command:

Displays NetBIOS over TCP/IP (NetBT) protocol statistics, NetBIOS name


tables for both the local computer and remote computers, and the NetBIOS
name cache. Nbtstat allows a refresh of the NetBIOS name cache and the names
registered with Windows Internet Name Service (WINS).

11) Netsh:

Netsh command is powerful utility to view and configure almost all of network
adapters. When passed without arguments it lands inside a interactive shell.

10
12) Getmac command:

The getmac command provides an easy way to find the MAC address of your
device. Prints more than one MAC address device has multiple network
adapters.

11
13) Net command:

The net command allows user to manage many different aspects of a network
and its settings such as network shares, users and print jobs etc..

14) Systeminfo command:

Systeminfo command collects all the important details of a system including


processor details, model of the system and network interfaces and puts them in a
readable format.

12
15) Ipconfig /flushdns:

This command is only needed if you’re having trouble with your networks DNS
configuration.

13
EXP NO:02 SOCKET PROGRAMMING USING TCP – ECHO AND
DATE: 12/8/24 CHAT CLIENT

Aim:

To create echo and chat application by implementing sockets using TCP


protocol in java programs.

1) Echo server and client:

Algorithm:

Server side:

1. Create the server socket and begin listening.


2. Call the accept() method to get new connections.
3. Create input and output streams for the returned socket.
4. Conduct the conversation based on the agreed protocol.
5. Close the client streams and socket.
6. Go back to step 2 or continue to step 7.
7. Close the server socket.

Client side:

1. Create the client socket connection.


2. Acquire read and write streams to the socket.

Source Code:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class Server1 {

public static void main(String[] args) {

14
1. Output:

Server:

Client:

15
try {

ServerSocket serverSocket = new ServerSocket(6666);

System.out.println("Server listening on port 6666");

Socket clientSocket = serverSocket.accept();

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));

while(true){

String msg = in.readLine();

if (msg.equalsIgnoreCase("end")){

System.out.println("Connection terminated by client");

break;

System.out.println("Client : " + msg);

serverSocket.close();

} catch (Exception e) {

System.out.println(e.getMessage());

Client

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

16
17
import java.net.Socket;

public class Cient1 {

public static void main(String[] args) {

try{

Socket socket = new Socket("localhost", 6666);

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

while(true){

System.out.print("Enter message: ");

String msg = in.readLine();

out.println(msg);

if(msg.equalsIgnoreCase("end")){

System.out.println("Terminating connection!");

break;

in.close();

out.close();

}catch(Exception e) {

System.out.println(e.getMessage());

}}

18
2. Output:

Server:

Client:

19
2) Chat server and client:

Algorithm:

Server side:

1. Start
2. Declare the variables for the socket.
3. Specify the family,protocol,ip address and port number.
4. Create a socket using socket() function.
5. Bind IP address and port number.
6. Listen and accept the client's request for connection.
7. Read the client's message.
8. Display the client's message.
9. Close the socket.
10.Stop .

Client side:

1. Start
2. Declare the variables for the socket.
3. Specify the family,protocol,ip address and port number.
4. Create a socket using socket() function.
5. Call the connect() function.
6. Read the input message.
7. Send the input message to the server.
8. Display the server's echo.

Source Code:

Server side:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.InetAddress;

import java.net.ServerSocket;

import java.net.Socket;

20
21
public class ChatServer {

public static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(333);

System.out.println("Server listening on port 3333");

Socket clientSocket = serverSocket.accept();

// System.out.println(clientSocket.getPort());

BufferedReader in = new BufferedReader(new


InputStreamReader(clientSocket.getInputStream()));

BufferedReader input = new BufferedReader(new


InputStreamReader(System.in));

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),


true);

String message = "", reply = "";

while(true){

System.out.print("Server: ");

message = input.readLine();

if(message.equalsIgnoreCase("end")){

System.out.println("Terminating connection");

break;

out.println(message);

reply = in.readLine();

if(reply.equalsIgnoreCase("end")){

22
23
out.close();

in.close();

serverSocket.close();

System.out.println("Client disconnects!");

break;

System.out.println("Client: " + reply);

out.println(reply);

}catch(Exception e){

System.out.println(e.getMessage());

Client side:

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class ChatClient {

public static void main(String[] args) {

try {

24
25
Socket socket = new Socket("localhost", 333);

System.out.println("Connection established with server!");

BufferedReader in = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

BufferedReader input = new BufferedReader(new


InputStreamReader(System.in));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

String msg = "", reply = "";

while(true){

msg=in.readLine();

if(msg.equalsIgnoreCase("end")){

System.out.println("Server disconnected!");

break;

System.out.println("Server: " + msg);

System.out.print("Client: ");

reply = input.readLine();

if(reply.equalsIgnoreCase("end")){

System.out.println("Terminating connection");

break;

else{

26
27
out.println(reply);

out.flush();

}catch (Exception e){

System.out.println(e.getMessage());

Result:

Hence, Echo and Chat application were created and executed successfully with
TCP protocol using Java.

28
1. Output:

Server side:

Client side:

29
EXP NO:03 SOCKET PROGRAMMING USING UDP – ECHO AND
DATE: 24/8/24 CHAT CLIENT

Aim:

To create echo and chat application by implementing sockets using UDP


protocol in java programs.

1) Echo server and client:

Algorithm:

Server side:

1. Start.
2. Declare the variables for the socket.
3. Specify the family, protocol, IP address and port number.
4. Create a socket using socket() function.
5. Bind the IP address and port number.
6. Listen and acccept the client’s request for the connection.
7. Read and display the client’s message.
8. Stop.

Client side:

1. Start.
2. Declare the variables for the socket.
3. Specify the family, protocol, IP address and port number.
4. Create a socket using socket() function.
5. Call the connect function.
6. Read the input message.
7. Send the input message to the server.
8. Display the message.
9. Close the socket.
10.Stop.

30
31
Source code:

Server side:

import java.io.*;

import java.net.*;

public class UDPServer {

public static void main(String[] args) throws IOException{

DatagramSocket server = new DatagramSocket(4444);

byte[] buf = new byte[1024];

DatagramPacket packet = new DatagramPacket(buf, buf.length);

System.out.println("[INFO] : Server started");

while (true) {

server.receive(packet);

String str = new String(packet.getData(), 0, packet.getLength());

if (str.equals("terminate")) {

System.out.println("[INFO] : Client terminated connection");

break;

System.out.println("[CLIENT] : " + str);

server.close();

Client side:

import java.io.*;

32
33
import java.net.*;

public class UDPClient {

public static void main(String[] args) throws IOException {

DatagramSocket client = new DatagramSocket(); InetAddress add =


InetAddress.getByName("localhost");

byte[] buf;

BufferedReader dis = new BufferedReader(new


InputStreamReader(System.in));

System.out.println("[INFO] : Client started\n[INFO] : Enter 'terminate' to


end connection");

while (true) {

System.out.print("[SYSTEM] > Enter message:");

String str = dis.readLine();

buf = str.getBytes();

if (str.equalsIgnoreCase("terminate")) {

System.out.println("[INFO] : Connection terminated");

client.send(new DatagramPacket(buf, str.length(), add, 4444));

break;

client.send(new DatagramPacket(buf, str.length(), add, 4444));

client.close();

34
Output:

Server side:

Client side:

35
2) Chat server and client:

Algorithm:

Server side:

1. Start.
2. Create a server socket.
3. Create a datagram packet with buffer to receive data.
4. Get the data through socket.
5. Convert the byte array to string and print it.
6. Similarly get input from server and send message.
7. Repeat the above steps until the clent sends ‘bye’, if so print terminated…
8. Stop.

Client side:

1. Start.
2. Set IP address and port number.
3. Get input from client.
4. Convert it to byte array.
5. Create a packet using the IP address and port.
6. Create the message.
7. Send the packet through the socket.
8. Create another packet with buffer to receive data from server.
9. Convert the byte array accepted into string array and display it.
10.Repeat the above steps until the user enters ‘bye’, if so break out.
11.Stop

Source code:

Server side:

import java.io.*; import java.net.*;

public class UDPChatServer {

public static void main(String[] args) throws IOException {

int c_port = 4444, s_port = 5555;

36
37
DatagramSocket server = new DatagramSocket(s_port);

byte[] buf = new byte[1024];

DatagramPacket packet = new DatagramPacket(buf, buf.length);

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

InetAddress ia = InetAddress.getLocalHost();

System.out.println("[INFO] : Server started\n[INFO] : Enter 'terminate' to


end connection");

while (true) {

server.receive(packet);

String str = new String(packet.getData(), 0, packet.getLength());

if (str.equalsIgnoreCase("terminate")) {

System.out.println("[INFO] : Client terminated connection"); break;

System.out.println("[CLIENT] : " + str);

System.out.print("[SYSTEM] > Enter message:");

buf = br.readLine().getBytes();

server.send(new DatagramPacket(buf, buf.length, ia, c_port));

server.close();

Client side:

import java.io.*; import java.net.*;

public class UDPChatClient {

38
39
public static void main(String[] args) throws IOException {

final int c_port = 4444, s_port = 5555;

DatagramSocket client = new DatagramSocket(c_port);

InetAddress add = InetAddress.getByName("localhost");

byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, buf.length);

BufferedReader dis = new BufferedReader(new


InputStreamReader(System.in));

System.out.println("[INFO] : Client started \n[INFO] : Enter 'terminate' to


end connection");

while (true) {

System.out.print("[SYSTEM] > Enter message:");

String msg = dis.readLine();

buf = msg.getBytes();

if (msg.equalsIgnoreCase("terminate")) {

System.out.println("[INFO] : Connection Terminated");

client.send(new DatagramPacket(buf,buf.length, add, s_port));

break;

client.send(new DatagramPacket(buf, buf.length, add, s_port));

client.receive(dp);

String str2 = new String(dp.getData(), 0, dp.getLength());

if (str2.equalsIgnoreCase("terminate")){

System.out.println("[INFO] : Server terminated connection"); break;

40
41
System.out.println("[SERVER] : " + str2);

client.close();

Result:

Hence, Echo and Chat application were created and executed successfully with
UDP protocol using Java.

42
Output:

Server side:

Client side:

43
EXP NO:04 HTTP PROTOCOL – GET AND POST
DATE: 31/8/24

Aim:

To create programs to implement HTTP protocol using get and post methods in
java.

1) HTTP GET server and client:

Algorithm:

Server side:

1. Start
2. Declare the variable for the server socket
3. Create a socket using socket() function
4. Listen and accept the client’s request for connection
5. Read the client’s message’
6. Display the message
7. Establish get HTTP connection for URL accepted.
8. Set other properties to USER_AGENT
9. Get the response code, if the response code is OK, then perform step 10
else go to step 14
10.Accept the message from the URL present in it by using HTTP
connection in a buffer

Client side:

1. Start
2. Create a client socket with post 6789
3. Declare the variable for the socket
4. Accept the URL from the user’
5. Write the URL using the dataoutput stream in the socket to be read by
answer
6. Read the message and by server
7. Close the server

Source code:

GET Server:

44
45
import javax.xml.crypto.Data;

import java.io.*;

import java.net.HttpURLConnection;

import java.net.ServerSocket;

import java.net.Socket;

import java.net.URL;

import java.nio.Buffer;

public class HTTPGetServer {

private static final String USER_AGENT = "Edge";

static String sendGET(String GET_URL) throws Exception{

URL URLobj = new URL(GET_URL);

HttpURLConnection con = (HttpURLConnection)


URLobj.openConnection();

con.setRequestMethod("GET");

con.setRequestProperty("User-Agent", USER_AGENT);

int responseCode = con.getResponseCode();

System.out.println("Response code " + responseCode);

if(responseCode == HttpURLConnection.HTTP_OK){

BufferedReader in = new BufferedReader(new


InputStreamReader(con.getInputStream()));

String input;

StringBuffer response = new StringBuffer();

while((input = in.readLine())!=null){

response.append(input);

46
}
47
System.out.println(response.toString());

in.close();

return response.toString();

else{

System.out.println("Request failed!");

return null;

public static void main(String[] args) throws Exception {

ServerSocket ss = new ServerSocket(8080);

while(true){

Socket con = ss.accept();

BufferedReader in = new BufferedReader(new


InputStreamReader(con.getInputStream()));

DataOutputStream out = new


DataOutputStream(con.getOutputStream());

String cs = in.readLine() + "\n";

System.out.println("Requested URL: " + cs);

String GET_URL = cs;

out.writeBytes(sendGET(GET_URL) + "\n");

System.out.println("GET Request successful");

break;

48
ss.close();

49
}

GET Client:

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.InputStreamReader;

import java.net.Socket;

public class HTTPGetClient {

public static void main(String[] args) throws IOException {

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));

Socket socket = new Socket("localhost", 8080);

DataOutputStream out = new


DataOutputStream(socket.getOutputStream());

BufferedReader ins = new BufferedReader(new


InputStreamReader(socket.getInputStream()));

System.out.println("Enter URL: ");

String sentence = in.readLine();

out.writeBytes(sentence + "\n");

String ms = in.readLine();

System.out.println("GET Response: " + ms);

50
Output:

Server side:

Client side:

socket.close();
51
}

2) HTTP POST server and client:

Algorithm:

Server side:

1. Start
2. Declare the variables for the server socket
3. Create a socket using socket() function
4. Listen and accept the client’s request for connection
5. Read the client’s message
6. Display the client’s message
7. Establish post HTTP connection for the URL accepted
8. Set the other properties such as request method and request property to
GET and USER_AGENT respectively.
9. Get the response code, if the response code is OK, do the following else
print message(error) and quit.
10.Accept the message from the URL present in it by using the HTTP
connection in a buffer
11.Convert the buffered message to string format
12.Print this converted string message
13.Send this message back to the client
14.End

Client side:

1. Start
2. Create a client socket using socket() function’
3. Declare the variables for the client socket
4. Accept the past URL from the user
5. Write the URL using the dataoutputstream in the socket to be read by the
server
6. Read the message sent by the server
7. Close the socket
8. End

52
Source code:

53
POST Server:

import java.io.*;

import java.net.*;

public class HTTPPostServer {

private static final String USER_AGENT = "Edge";

static String sendPOST(String POST_URL) throws IOException {

URL obj = new URL(POST_URL);

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

con.setRequestMethod("POST");

con.setRequestProperty("User-Agent", USER_AGENT);

con.setRequestProperty("Content-Type", "application/json; utf-8");

con.setRequestProperty("Accept", "application/json");

con.setDoOutput(true);

String jsoninput = "{"

+ "\"title\": \"foo\","

+ "\"body\": \"bar\","

+ "\"userId\": 1"

+ "}";

try (OutputStream os = con.getOutputStream()) {

54
byte[] input = jsoninput.getBytes("utf-8");

55
os.write(input, 0, input.length);

int responseCode = con.getResponseCode();

System.out.println("[INFO] : Response Code : " + responseCode);

if (responseCode == HttpURLConnection.HTTP_OK) {

try (BufferedReader in = new BufferedReader(new


InputStreamReader(con.getInputStream()))) {

StringBuilder response = new StringBuilder();

String inputLine;

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

return response.toString();

} else {

System.out.println("[ERROR] : POST Request failed with response


code " + responseCode);

return null;

public static void main(String[] args) throws Exception {

try (ServerSocket ss = new ServerSocket(6789)) {

while (true) {

try (Socket consoc = ss.accept();

56
BufferedReader ifc = new BufferedReader(new
InputStreamReader(consoc.getInputStream()));

57
DataOutputStream otc = new
DataOutputStream(consoc.getOutputStream())) {

String requestLine = ifc.readLine();

System.out.println("[INFO] : Requested URL : " + requestLine);

// Extract URL from the request line

// Assuming the URL is the first line in the request; adjust if


necessary

String POST_URL = requestLine.trim();

String response = sendPOST(POST_URL);

if (response != null) {

otc.writeBytes(response + '\n');

System.out.println("[INFO] : POST Request successful");

} else {

otc.writeBytes("POST Request failed\n");

} catch (IOException e) {

System.out.println("[ERROR] : Error handling request: " +


e.getMessage());

58
}

59
}

HttpPost Client:

import javax.xml.crypto.Data;

import java.io.BufferedReader;

import java.io.DataOutputStream;

import java.io.IOException;

import java.io.*;

import java.net.*;

public class HTTPPostClient {

public static void main(String[] args) throws IOException {

BufferedReader ifu = new BufferedReader(new


InputStreamReader(System.in));

Socket csocket = new Socket("localhost", 6789);

DataOutputStream ots = new


DataOutputStream(csocket.getOutputStream());

BufferedReader ifs = new BufferedReader(new


InputStreamReader(csocket.getInputStream()));

System.out.println("Enter URL:");

String sentence = ifu.readLine();

ots.writeBytes(sentence + "\n");

String ms = ifs.readLine();

60
System.out.println("POST Response: " + ms);

61
csocket.close();

Result:

Hence, programs implementing HTTP get and post protocol were created and
executed successfully.

62
Output:

Server side:

Client side:

63
EXP NO:05 FILE TRANSFER PROTOCOL
DATE: 2/9/24

Aim:
To create java program that implements FTP by facilitating file transfer
between a server and client.

Algorithm:

Server side:
1. Start the program.
2. Create the server socket.
3. Call the I/O stream.
4. Print the file has been sent.
5. Send the intimation to the client.
6. Stop the program

Client side:
1. Start the program.
2. Create the client packet.
3. After transferring the packet statementis displayed.
4. Stop the program.

Source code:

Server side:

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.net.*;

public class FTPServer {

Socket s;

ServerSocket ss;

DataInputStream din;

64
65
DataOutputStream dout;

String filename;

File fileObj;

public FTPServer() throws Exception{

ss = new ServerSocket(6060);

s = ss.accept();

System.out.println("Server started at " + ss.getInetAddress());

System.out.println("Socket connected to server from " +


s.getInetAddress());

din = new DataInputStream(s.getInputStream());

dout = new DataOutputStream(s.getOutputStream());

public void startTransfer() throws Exception{

int readByte;

FileInputStream fStream = new FileInputStream(filename);

System.out.println("Requested file transfer to " + s.getInetAddress() + "


starting");

while((readByte = fStream.read()) != -1){

dout.writeUTF(String.valueOf(readByte));

dout.writeUTF("-1");

fStream.close();

66
67
public void sendFile() throws Exception{

filename = din.readUTF();

System.out.println("Requested File name: " + filename);

fileObj = new File(filename);

if(fileObj.exists()){

dout.writeUTF("1");

if((din.readUTF()).equals("1")) {

this.startTransfer();

else {

System.out.println("Request file unavailable");

dout.writeUTF("0");

public static void main(String[] args) throws Exception {

FTPServer instance = new FTPServer();

instance.sendFile();

instance.s.close();

instance.ss.close();

System.out.println("Socket disconnected and server closed");

68
69
Client side:

import javax.xml.crypto.Data;

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.File;

import java.io.FileOutputStream;

import java.net.Socket;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.util.Scanner;

public class FTPClient {

Socket s;

DataInputStream din;

DataOutputStream dout;

String filename;

public FTPClient() throws Exception{

s = new Socket("127.0.0.1", 6060);

System.out.println("Socket connected at " + s.getInetAddress());

din = new DataInputStream(s.getInputStream());

dout = new DataOutputStream(s.getOutputStream());

public void getFile() throws Exception{

String fileIn;

70
71
Scanner in = new Scanner(System.in);

System.out.println("Enter filename to download: ");

filename = in.nextLine();

dout.writeUTF(filename);

Path file = Paths.get(filename);

filename = file.getFileName().toString();

System.out.println("Filename is " + filename);

String confirmation = din.readUTF();

// System.out.println(confirmation);

if(confirmation.equals("1")){

System.out.println("The requested file is available at " +


s.getInetAddress());

File fileobj = new File(filename);

if(fileobj.exists()){

System.out.println("The requested file already exists ");

System.out.println("Do you want to replace the file (y/n): ");

String ch = in.nextLine();

if(ch.equalsIgnoreCase("n")){

System.out.println("Do your want to rename the received file


(y/n)");

ch = in.nextLine();

dout.writeUTF("1");

if(ch.equalsIgnoreCase("n")){

72
73
System.out.println("File already exists. No further operations
done");

in.close();

return;

System.out.println("Enter file name: ");

filename = in.nextLine();

dout.writeUTF("1");

System.out.println("File transfer starting from " + s.getInetAddress());

FileOutputStream fout = new FileOutputStream(filename);

StringBuilder output = new StringBuilder();

while(!(fileIn = din.readUTF()).equals("-1")) {

output.append(Integer.parseInt(fileIn));

fout.write(Integer.parseInt(fileIn));

System.out.println("Data received: " + output);

System.out.println("File Transfer completed");

fout.close();

else{

System.out.println("The requested file not found");

74
75
in.close();

public static void main(String[] args) throws Exception {

FTPClient instance = new FTPClient();

instance.getFile();

instance.s.close();

System.out.println("Socket closed");

Result:

Hence, FTP was implemented using java and file transfer from server to client
was performed.

76
Output:

Server side:

Client side:

77
EXP NO:06 DOMAIN NAME SERVER
DATE: 2/9/24

Aim:

To create java program that implements DNS by facilitating name/IP resolution


between a server and client.

Algorithm:

1. Start the program


2. Enter the system name (dns) after the connection with the server is
established.
3. Call the subroutine resolver and pass the system name to the resolver.
4. Open the host files in the DNS server.
5. Check the system name with the name stored in the host file until the end
of the file.
6. If the name matches, then fetch the corresponding IP address and display
the IP address. Go to step8.
7. If the match is not found, then display the message as system is not
logged on.
8. Stop the process.

Source code:

Server side:

import java.net.*;

import java.util.Arrays;

class DNSServer{

public static void main(String[] args) throws Exception

DatagramSocket server = new DatagramSocket(1309);

System.out.println("[INFO] : Server started and waiting for requests");

78
79
byte[] sendbyte = new byte[1024];

byte[] receivebyte = new byte[1024];

DatagramPacket receiver = new DatagramPacket(receivebyte,


receivebyte.length);

server.receive(receiver);

String str = new String(receiver.getData());

System.out.println(receiver);

String s = str.trim();

System.out.println("[INFO] : Request recieved to resolve "+s);

InetAddress addr = receiver.getAddress();

int port = receiver.getPort();

InetAddress IP = InetAddress.getByName(s);

System.out.println(Arrays.toString(IP.getAddress()));

sendbyte = IP.toString().getBytes();

DatagramPacket sender;

sender = new DatagramPacket(sendbyte, sendbyte.length, addr, port);

server.send(sender);

server.close();

Client side:

import java.io.*;

import java.net.*;

class DNSClient {

80
81
public static void main(String args[]) throws Exception

{ DatagramSocket client = new DatagramSocket();

InetAddress addr = InetAddress.getByName("127.0.0.1");

byte[] sendbyte = new byte[1024];

byte[] receivebyte = new byte[1024];

BufferedReader in = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("[SYSTEM] > Enter Domain name to resolve :");

sendbyte = in.readLine().getBytes();

DatagramPacket sender = new DatagramPacket(sendbyte, sendbyte.length,


addr, 1309);

client.send(sender);

DatagramPacket receiver = new DatagramPacket(receivebyte,


receivebyte.length);

client.receive(receiver);

String s = new String(receiver.getData());

if(s.isEmpty()) System.out.println("[SERVER] : The requested domain


doesn't exist");

else System.out.println("[SERVER] : The input resolves to :" + s.trim());

client.close();

Result:

Hence, DNS was implemented using java from server to client was performed.

82
Output:

83
EXP NO:07 SIMPLE MAIL TRANSFER PROTOCOL
DATE: 9/9/24

Aim:
To create java program that implements SMTP by facilitating SMTP protocol
from a mail server.

Algorithm:
1. Start
2. Set Senders Mail Address and Password.
3. Get System Properties and put host,port,ssl enable to the property object.
4. Ask the Receivers Mail Address.
5. Get the Session object for the processed password authentication purpose.
6. Create a default Mime Message object to receive the message from the
1. user/sender.
7. Ask the User the Subject and the Message to send it to the reciver.
8. Send the Message and Display the Result.
9. STOP

Source code:

1) Without Attachment

package org.example;

import jakarta.mail.*;

import jakarta.mail.internet.AddressException;

import jakarta.mail.internet.InternetAddress;

import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

import java.util.Scanner;

public class SMTPServer {

84
85
public static void main(String[] args) {

Scanner in = new Scanner(System.in);

String sender = "SMTPJava1";

String senderMail = "[email protected]";

String pass = "qrsahhmpdfgfcghv";

String to = "[email protected]";

String host = "smtp.gmail.com";

Properties SessionProperties = new Properties();

SessionProperties.put("mail.smtp.auth", "true");

SessionProperties.put("mail.smtp.starttls.enable", "true");

SessionProperties.put("mail.smtp.host", host);

SessionProperties.put("mail.smtp.port", 587);

Session CurrentSession = Session.getInstance(SessionProperties,

new jakarta.mail.Authenticator(){

protected PasswordAuthentication getPasswordAuthentication()


{

return new PasswordAuthentication(senderMail, pass);

});

try{

Message m = new MimeMessage(CurrentSession);

m.setFrom(new InternetAddress(senderMail));

86
Output:

87
m.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));

System.out.println("Enter subject: ");

String sub = in.nextLine();

System.out.println("Enter body: ");

String body = in.nextLine();

m.setSubject(sub);

m.setContent(body, "text/html");

Transport.send(m);

System.out.println("Message was sent successfully");

} catch (MessagingException e) {

throw new RuntimeException(e);

2) With Attachment

package org.example;

import jakarta.activation.DataHandler;

import jakarta.activation.DataSource;

import jakarta.activation.FileDataSource;

import jakarta.mail.*;

import jakarta.mail.internet.InternetAddress;

import jakarta.mail.internet.MimeBodyPart;

import jakarta.mail.internet.MimeMessage;

88
89
import jakarta.mail.internet.MimeMultipart;

import java.util.Properties;

import java.util.Scanner;

public class SMTPMulServer {

public static void main(String[] args) {

String user = "SMTPJava1";

String fromMail = "[email protected]";

String pass = "qrsahhmpdfgfcghv";

String to [email protected]";

String host = "smtp.gmail.com";

Scanner in = new Scanner(System.in);

Properties SessionProperties = new Properties();

SessionProperties.put("mail.smtp.auth", "true");

SessionProperties.put("mail.smtp.starttls.enable", "true");

SessionProperties.put("mail.smtp.host", host);

SessionProperties.put("mail.smtp.port", 587);

Session session = Session.getInstance(SessionProperties, new


jakarta.mail.Authenticator(){

protected PasswordAuthentication getPasswordAuthentication(){

return new PasswordAuthentication(fromMail, pass);

90
91
});

try{

Message m = new MimeMessage(session);

m.setFrom(new InternetAddress(fromMail));

m.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));

System.out.println("Enter subject: ");

String sub = in.nextLine();

System.out.println("Enter body: ");

String body = in.nextLine();

System.out.println("Do you want to add an attachment? (y/n) ");

String c = in.nextLine();

if(c.equalsIgnoreCase("y")){

System.out.println("Enter filename to attach: ");

String filename = in.nextLine();

DataSource FileSource = new FileDataSource(filename);

MimeBodyPart partOne = new MimeBodyPart();

partOne.setText(body);

MimeBodyPart partTwo = new MimeBodyPart();

partTwo.setDataHandler(new DataHandler(FileSource));

partTwo.setFileName(filename);

Multipart MessageBody = new MimeMultipart();

MessageBody.addBodyPart(partOne);

92
93
MessageBody.addBodyPart(partTwo);

m.setContent(MessageBody);

else{

m.setContent(body, "test/html");

m.setSubject(sub);

Transport.send(m);

System.out.println("Message was sent successfully");

}catch(Exception e){

e.printStackTrace();

Result:

Hence, SMTP was implemented using java from client to mail serve

94
Output:

95
EXP NO:8 POST OFFICE PROTOCOL
DATE: 16/9/24

Aim:
To create java program that implements POP3 from a client to POP3 compatible
mail server.
Algorithm:
1. Start
2. Set up properties for Mail Session.
3. Create a Javax.mail Authenticator Object.
4. Create a Mail Session.
5. Get POP3 store provider and connect to the store of the mail.
6. Get folder and open INBOX folder in the store.
7. Retrieve message from folder.
8. Stop listening until user enter “STOP” .
9. STOP
Source code:
package org.example;

import jakarta.mail.*;

import java.io.IOException;
import java.util.Properties;
import java.util.Scanner;

public class POP3Server {


public static void main(String[] args) throws MessagingException,
IOException {
Scanner in = new Scanner(System.in);
String username = "[email protected]";
System.out.println("Enter password: ");

96
97
String password = in.nextLine();
Properties SessionProperties = new Properties();

SessionProperties.put("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
SessionProperties.put("mail.pop3.socketFactory.fallback", "false");
SessionProperties.put("mail.pop3.socketFactory.port", "995");
SessionProperties.put("mail.pop3.port", "995");
SessionProperties.put("mail.pop3.host", "pop.gmail.com");
SessionProperties.put("mail.pop3.user", username);
SessionProperties.put("mail.store.protocol", "pop3");

Session session = Session.getDefaultInstance(SessionProperties,


new jakarta.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication(username, password);
}
}
);

Store MailServerStore = session.getStore("pop3");


MailServerStore.connect("pop.gmail.com", username, password);
Folder Inbox = MailServerStore.getFolder("INBOX");
Inbox.open(Folder.READ_ONLY);
Message[] MailMessages = Inbox.getMessages();
for(Message mail : MailMessages){
mail.writeTo(System.out);

98
99
System.out.println("Do you want to continue? (y/n)");
String c= in.nextLine();
if(c.equalsIgnoreCase("n")){
System.out.println("Mails read successfully");
break;
}
}
Inbox.close();
MailServerStore.close();
in.close();
}
}

Result:
Hence, POP3 was implemented using java from a client to mail server.

100
Output:
Server side:

Client side:

101
EXP NO:9 PING COMMAND
DATE:

Aim:
To write a java program to implement ping command in raw sockets.

Algorithm:
1. Create a RAW socket in the client program.
2. Get the name of the host whose IP address is to resolve using ICMP.
3. Pass this name to the ICMP server through this socket.
4. The server will respond with the IP address of the host.
5. Receive the response and print it.

Source code:

Server side:

import java.io.*;
import java.net.*;
import java.util.*;
class PingServer
{
public static void main(String[] args)
{
try
{
ServerSocket ss=new ServerSocket(2156);
Socket s=ss.accept();
if(s.isConnected())
System.out.println("Connected ...");
System.out.println("Listening ...");
DataInputStream dis=new DataInputStream(s.getInputStream());
DataOutputStream dos=new DataOutputStream(s.getOutputStream());
int no=0;
String ip="";
if((dis.readUTF()).equals("P"))
{
System.out.println("Getting No. Of Packets ...");
no=dis.readInt();
}
if((dis.readUTF()).equals("A"))
{

102
103
System.out.println("Getting the Address ...");
ip=dis.readUTF();
}
Process p=Runtime.getRuntime().exec("ping -n "+no+" "+ip);
System.out.println("Running ping -n "+no+" "+ip);
BufferedReader br=new BufferedReader(new
InputStreamReader(p.getInputStream()));

String ipline=br.readLine();
while(ipline != null )
{
dos.writeUTF(ipline);
ipline=br.readLine();
}
dis.close();
dos.close();
}catch(Exception e)
{
// x.printStackTrace();
}
}
}

Client side:

import java.io.*;
import java.net.*;
import java.util.*;
public class PingClient
{
public static void main(String[] args) throws Exception
{
try
{
Socket s=new Socket("localhost",2156);
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
if(s.isConnected())
System.out.println("Connected !!");
Scanner in=new Scanner(System.in);
DataInputStream is=new DataInputStream(s.getInputStream());
DataOutputStream os=new DataOutputStream(s.getOutputStream());
System.out.println("How many Packets You want to send ? ");

104
105
int no=in.nextInt();
System.out.println("Address to be pinged :");
String ip=br.readLine();
os.writeUTF("P");
os.writeInt(no);
os.writeUTF("A");
os.writeUTF(ip);
String pingline=is.readUTF();
while(pingline != null )
{
System.out.println(pingline);
pingline=is.readUTF();
}
os.flush();
os.close();
is.close();
}catch(Exception x){

}
}

Result:

Hence, ping command was implemented using raw sockets in a Java program

106
Output:

Output:

107
CYCLE – 2
EXP NO:1 STUDY OF NS2
DATE: 7/10/24

Aim:

To study network simulator version 2 (ns2).

Program:

variables.tcl

set a 10

set b 15

puts $a

puts "the value of a = $a"

puts "the value of b = $b"

expressions.tcl

set a 10

set b 15

set c [expr $a + $b]

puts "the value of c = $c"

set d [expr [expr $b - $a] * $c]

puts "the value of d = $d"

108
Output:

109
procedure.tcl

proc display {} {

puts "this is the testing message" }

display

proc add {x y} {

set z [expr $x + $y]

puts "the value of $x + $y = $z" }

add 10 20

proc print { k } {

for {set i 0} {$i < $k} {incr i} {

puts "node_($i)"

puts "n$i" } }

print 10

110
Output:

111
control.tcl

set x 10

while { $x > 0 } {

puts $x

set x [expr $x - 1]

Arrays.tcl

proc add_matrices {n m} {

global matrix1 matrix2 result

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

# Add corresponding elements from both matrices

set sum [expr $matrix1($i,$j) + $matrix2($i,$j)]

set result($i,$j) $sum

set n 2

set m 2

set matrix1(0,0) 1

112
Output:

113
set matrix1(0,1) 2

set matrix1(1,0) 3

set matrix1(1,1) 4

set matrix2(0,0) 5

set matrix2(0,1) 6

set matrix2(1,0) 7

set matrix2(1,1) 8

add_matrices $n $m

puts "Matrix 1:"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$matrix1($i,$j) "

puts ""

puts "\nMatrix 2:"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$matrix2($i,$j) "

114
115
puts ""

puts "\nResultant Matrix (Matrix1 + Matrix2):"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$result($i,$j) "

puts ""

proc add_matrices {n m} {

global matrix1 matrix2 result

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

# Add corresponding elements from both matrices

set sum [expr $matrix1($i,$j) + $matrix2($i,$j)]

set result($i,$j) $sum

set n 2

set m 2

116
117
set matrix1(0,0) 1

set matrix1(0,1) 2

set matrix1(1,0) 3

set matrix1(1,1) 4

set matrix2(0,0) 5

set matrix2(0,1) 6

set matrix2(1,0) 7

set matrix2(1,1) 8

add_matrices $n $m

puts "Matrix 1:"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$matrix1($i,$j) "

puts ""

puts "\nMatrix 2:"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$matrix2($i,$j) "

118
Output:

119
}

puts ""

puts "\nResultant Matrix (Matrix1 + Matrix2):"

for {set i 0} {$i < $n} {incr i} {

for {set j 0} {$j < $m} {incr j} {

puts -nonewline "$result($i,$j) "

puts ""

File.tcl

set test [open file1.txt w]

puts $test "Testing message"

Result:

Hence study on network simulator version 2 is done.

120
Output:

121
EXP NO:2 NETWORK TOPOLOGY USING NS-2
DATE: 7/10/24

Aim:
To generate a network topological node with suitable link characteristic using
network simulator version 2.

Procedure:
1. Create a simulator object which is an event scheduler using set ns [new
Simulator]
2. Turn on tracing by opening the NAM trace file in writing mode and trace
all the packets
3. Define a finish procedure to execute the NAM on the trace file
4. Create 6 topological nodes and assign corresponding variables
5. Create link between node n0 n1, n1 n2, n2 n3, n3 n4, n3 n5 which is a
duplex
6. link with queue as RED
7. Set queue limit to node n2 and n3 with 10 count
8. Provide orientation to the nodes linked with each other to be displayed on
the
9. NAM trace file
9. Create a TCP agent and attach tcp with the node n0
10.Create a traffic sink and attach sink with node n5
11.Then connect both the agents , tcp and the traffic sink
12.Set up a CBR over a TCP Connection by attaching cbr with tcp
13.Schedule events for CBR agent to start and stop
14.Call the finish procedure after 5 seconds of simulation time
15.Print CBR packet size and interval on the terminal
16.Finally run the network simulator using the command $ns run

Program:

set ns [new Simulator]

set tr [open out.tr w]

$ns trace-all $tr

set namtr [open out.nam w]

$ns namtrace-all $namtr

set n0 [$ns node]

122
123
set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

$ns duplex-link $n0 $n1 10Mb 5ms DropTail

$ns duplex-link $n2 $n0 10Mb 5ms DropTail

$ns duplex-link $n3 $n0 10mb 5ms DropTail

$ns duplex-link-op $n0 $n1 orient right

$ns duplex-link-op $n0 $n2 orient left-up

$ns duplex-link-op $n0 $n3 orient left-down

$ns at 10.0 "$ns halt"

$ns run

Result:

Hence a network topological node with suitable link has been created using ns2.

124
Output:

125
EXP NO:3 WIRED NETWORK USING TCP
DATE: 7/10/24

Aim:
To generate a wired network using TCP in ns2 .

Algorithm:
1. START
2. Declare a new Simulator ns and nam nf.
3. Define a procedure finish to execute the namfile.
4. 4.Set the colors for Nodes.
5. Create five Nodes n0,n1,n2,n3,n4 and links with each other.
6. Set the Orientation of the nodes with respect to the nodes with respect to
the nodes they are linked with.
7. Set up a TCP Agent and Create Application, FTP
8. Start the Traffic and stop at 1 second and call the finish procedure.
9. Run the Simulator
10.STOP

Program:
set ns [new Simulator]
set tracefile [open out1.nam w]
$ns namtrace-all $tracefile
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
$ns duplex-link $n0 $n1 6MB 60ms DropTail
$ns duplex-link $n1 $n2 2MB 50ms DropTail
$ns duplex-link $n2 $n3 10MB 20ms DropTail
$ns duplex-link $n3 $n4 1MB 100ms DropTail
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
$ftp set packet-size_ 1000
proc finish {} {

126
127
global ns tracefile
$ns flush-trace
close $tracefile
exec nam out1.nam &amp;
exit 0
}
$ns at 0.1 "$ftp start";
$ns at 5.0 "$ftp stop";
$ns at 5.5 "finish";
$ns run

Result:

Hence, wired network using TCP is simulated in ns2

128
Output:

129
EXP NO:4 WIRELESS NETWORK USING UDP
DATE: 14/10/24

Aim:
To create a wireless topological network simulation using UDP in ns2.

Algorithm:
1. START
2. Initialize Necessary variables for Wireless Connection.
3. Create Tracing and Animation Files.
4. Set Temporary and Load the values of the Variables.
5. Create nodes and mark their Location.
6. Create Channel (i.e) Communication Path for the nodes.
7. Specify mobility codes if anu of the nodes are moving.
8. Set CBR Traffic.
9. Run the simulator.
10.STOP

Program:
set val(chan) Channel/WirelessChannel ;
set val(prop) Propagation/TwoRayGround ;
set val(netif) Phy/WirelessPhy;
set val(mac) Mac/802_11;

set val(ifq) Queue/DropTail/PriQueue


set val(ll) LL;
set val(ant) Antenna/OmniAntenna;
set val(ifqlen) 50;

set val(nn) 6;

set val(rp) AODV;

set val(x) 500 ;# in metres


set val(y) 500 ;
#creation of Simulator
set ns [new Simulator]
#creation of Trace and namfile
set tracefile [open wireless.tr w]
$ns trace-all $tracefile
#Creation of Network Animation file
set namfile [open wireless.nam w]

130
131
$ns namtrace-all-wireless $namfile $val(x) $val(y)
#create topography
set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)
set channel1 [new $val(chan)]
set channel2 [new $val(chan)]
set channel3 [new $val(chan)]
#configure the node
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-topoInstance $topo \
-agentTrace ON \
-macTrace ON \
-routerTrace ON \
-movementTrace ON \
-channel $channel1

set n0 [$ns node]


set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n0 random-motion 0
$n1 random-motion 0
$n2 random-motion 0
$n3 random-motion 0
$n4 random-motion 0
$n5 random-motion 0
$ns initial_node_pos $n0 20
$ns initial_node_pos $n1 20
$ns initial_node_pos $n2 20
$ns initial_node_pos $n3 20
$ns initial_node_pos $n4 20
$ns initial_node_pos $n5 50
#initial coordinates of the nodes

132
133
$n0 set X_ 10.0
$n0 set Y_ 20.0
$n0 set Z_ 0.0

$n1 set X_ 210.0


$n1 set Y_ 230.0
$n1 set Z_ 0.0

$n2 set X_ 100.0


$n2 set Y_ 200.0
$n2 set Z_ 0.0

$n3 set X_ 150.0


$n3 set Y_ 230.0
$n3 set Z_ 0.0

$n4 set X_ 430.0


$n4 set Y_ 320.0
$n4 set Z_ 0.0

$n5 set X_ 270.0


$n5 set Y_ 120.0
$n5 set Z_ 0.0

$ns at 1.0 "$n1 setdest 400.0 350.0 20.0"


$ns at 1.0 "$n0 setdest 100.0 200.0 10.0"
$ns at 1.0 "$n2 setdest 150.0 100.0 15.0"
$ns at 1.0 "$n3 setdest 450.0 400.0 25.0"
$ns at 1.0 "$n4 setdest 300.0 130.0 5.0"
$ns at 1.0 "$n5 setdest 190.0 440.0 15.0"
$ns at 20.0 "$n5 setdest 100.0 200.0 30.0"
set udp [new Agent/UDP]
set null [new Agent/Null]
$ns attach-agent $n2 $udp
$ns attach-agent $n3 $null
$ns connect $udp $null
set cbr [new Application/Traffic/CBR]
$cbr set packetSize 1024
$cbr attach-agent $udp
$ns at 1.0 "$cbr start"
$ns at 30.0 "finish"
proc finish {} {
global ns tracefile namfile

134
135
$ns flush-trace
close $tracefile
close $namfile
exit 0
}
puts "Starting Simulation"
$ns run

Result:
Hence wireless network is simulated using UDP in ns2.

136
Output:

137
EXP NO:5 PERFORMACE ANALYSIS USING XGRAPH
DATE: 21/10/24

Aim:
To analyze performance of TCP and UDP using Xgraph

Algorithm:
1. START
2. Create a new simulator ns and open out.nam as nf.
3. Create five nodes and establish Link with appropriate Nodes.
4. Declare a Procedure attach-expoo-traffic and define it to simulate a UDP
traffic.
5. Create sink agents and attach it with nodes.
6. Declare and Define Finish Procedure to be called at the End.
7. Decalre a Procedure record to Track the Bytes that are received by the
traffic Links.
8. Calculate the bandwidth and write it to the file.
9. Reset the Bytes value on the Traffic sinks.
10.Reschedule the Procedures by calling each defined functions in the
appropriate order.
11.Run the Simulator.
12.STOP

Program:
set ns [new Simulator]
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
$ns duplex-link $n0 $n3 1Mb 100ms DropTail
$ns duplex-link $n1 $n3 1Mb 100ms DropTail
$ns duplex-link $n2 $n3 1Mb 100ms DropTail
$ns duplex-link $n3 $n4 1Mb 100ms DropTail
proc attach-expoo-traffic { node sink size burst idle rate } {
#Get an instance of the simulator
set ns [Simulator instance]
#Create a UDP agent and attach it to the node
set source [new Agent/UDP]
$ns attach-agent $node $source
#Create an Expoo traffic agent and set its configuration parameters
set traffic [new Application/Traffic/Exponential]

138
139
$traffic set packetSize_ $size
$traffic set burst_time_ $burst
$traffic set idle_time_ $idle
$traffic set rate_ $rate

# Attach traffic source to the traffic generator


$traffic attach-agent $source
#Connect the source and the sink
$ns connect $source $sink
return $traffic
}
set sink0 [new Agent/LossMonitor]
set sink1 [new Agent/LossMonitor]
set sink2 [new Agent/LossMonitor]
$ns attach-agent $n4 $sink0
$ns attach-agent $n4 $sink1
$ns attach-agent $n4 $sink2
set source0 [attach-expoo-traffic $n0 $sink0 200 2s 1s 100k]
set source1 [attach-expoo-traffic $n1 $sink1 200 2s 1s 200k]
set source2 [attach-expoo-traffic $n2 $sink2 200 2s 1s 300k]
set f0 [open out0.tr w]
set f1 [open out1.tr w]
set f2 [open out2.tr w]
proc finish {} {
global f0 f1 f2
#Close the output files
close $f0
close $f1
close $f2
#Call xgraph to display the results
exit 0
}
proc record {} {
global sink0 sink1 sink2 f0 f1 f2
#Get an instance of the simulator
set ns [Simulator instance]
#Set the time after which the procedure should be called again
set time 0.5
#How many bytes have been received by the traffic sinks?
set bw0 [$sink0 set bytes_]
set bw1 [$sink1 set bytes_]
set bw2 [$sink2 set bytes_]
#Get the current time

140
141
set now [$ns now]
#Calculate the bandwidth (in MBit/s) and write it to the files
puts $f0 "$now [expr $bw0/$time*8/1000000]"
puts $f1 "$now [expr $bw1/$time*8/1000000]"
puts $f2 "$now [expr $bw2/$time*8/1000000]"
#Reset the bytes_ values on the traffic sinks
$sink0 set bytes_ 0
$sink1 set bytes_ 0
$sink2 set bytes_ 0

#Re-schedule the procedure


$ns at [expr $now+$time] "record"
}
$ns at 0.0 "record"
$ns at 10.0 "$source0 start"
$ns at 10.0 "$source1 start"
$ns at 10.0 "$source2 start"
$ns at 50.0 "$source0 stop"
$ns at 50.0 "$source1 stop"
$ns at 50.0 "$source2 stop"
$ns at 60.0 "finish"
$ns run

Result:
Hence performance analysis is executed using xgraph in NS-2.

142
Output:

RIP

Logical View

Simulation Table

143
EXP NO:6 RIP AND OSPF
DATE: 4/11/24

Aim:
To simulate the working of RIP and OSPF routing protocols in Cisco Packet
Tracer.

Procedure:
RIP:
1. Download the Cisco Packet Tracer and Login,then open a new Window.
2. Select two End Devices(2 PC’S) and Drag them from the menu.
3. Select two Network Devices(PT routers) and two Switches (PT Switch)
and Drag them from the menu.
4. Connect All of them as shown in the output.
5. Name the two networks as A and B and assign them a particular IP
address.
6. Configure the two End Devices using the IP address assigned.
7. Similarly assign the IP address between the two connected Routers.
8. Send the Packet PC0 to Router0 and Similarly between PC1 to Router1.
9. Now try to send the packet between PC0and PC1,if it fails go to step 10.
10.Configure the Routers and add all the IP address to the RIP of Routers
and save them.
11.Now send the packets from PC0 to PC1 and from Router0 to Router1.
12.The Packets are being successfully sent.

OSPF:
1. 1.Login Cisco Packet Tracer and Open a new Window.
2. 2.Drag in two PC’S from the End Devices.
3. 3.Drag in Three Routers and Connect all the Devices.
4. 4.Name the networks with appropriate IP address.
5. 5.Configure the PC’S to their respective networks.
6. 6.Connect the Routers in their appropriate Networks.
7. Now use the OSPF to make all the networks visible to each other.
8. See the Serial Routers are Connected it and Configure them. Use the
Command line Interpreter to activate the OSPF.
9. Enable and Configure the terminal in the CLI.
10.Now Connect the Router to the Networks it is Connected.
11.The OSPF is activated hence making all the networks visible to each
other.
12.Now send a Packet from PC0 to PC1 and Vice versa, the Routers choose
the path to deliver the packet.

144
OSPF

Logical View

Simulation Table

145
Result:
Hence Open Shortest Path First (OSPF) is simulated and the packet is
successfully sent from the PC0 to PC1 and vice versa

146
Output:
DHCP:

Logical View

Automatic Configuration of IPv4 address

147
EXP NO:7 DHCP AND SLAAC
DATE: 4/11/24

Aim:

To study about SLAAC and DHCP.

Procedure:

SLAAC:

1. START
2. Login into the Cisco Packet Tracer and open a New Window.
3. Drag and Drop Router from the menu bar.
4. Drag and Drop two switches from the menu bar.
5. Drag and Drop the End Devices from the menu bar such as a PC/laptop.
6. Connect all the end devices with the switch .
7. Configure the router for the two switches and the switches also.
8. Set up the Ipv6 address for the End systems connected.
9. Stop

DHCP:

1. Start
2. Login into Cisco Packet Tracer and open a new Window.
3. 3.Drag and Drop a Router from the menu bar.
4. Drag and Drop two Switches from the menu bar.
5. Drag end devices, three laptops and one PC System from the menu bar.
6. Connect the end devices to the switches using a fast ethernet cable .
7. Connect the Switches to the Router using the Fast Ethernet cable.
8. Using the Command line for the Router and configure the router first for
the two fast ethernet cable connections.
9. Configure the IP address of end devices and set the configuration to
DHCP.
10.DHCP is thus Configured.
11.Stop

148
SLAAC
Logical View

Automatic Configuration of IPv6 Address

149
Result:

Hence SLAAC and DHCP is studied, and packets are sent successfully.

150

You might also like