0% found this document useful (0 votes)
12 views23 pages

CN Lab Programs

Uploaded by

sherin vijaya
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)
12 views23 pages

CN Lab Programs

Uploaded by

sherin vijaya
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/ 23

1. Write the Echo client and server programs using UDP.

The Echo clients should verify


whether the text string they received from the server is the same text string that they sent
or not. Also use the shutdown system call to improve the performance programs.

MyServer.java

import java.net.*;

import java.io.*;

class MyServer{

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

ServerSocket ss=new ServerSocket(3333);

Socket s=ss.accept();

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

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){

str=din.readUTF();

System.out.println("client says: "+str);

str2=br.readLine();

dout.writeUTF(str2);

dout.flush();

din.close();

s.close();

ss.close();

}}
MyClient.java

import java.net.*;

import java.io.*;

class MyClient{

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

Socket s=new Socket("localhost",3333);

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

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

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){

str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

}}

2.Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side

udpClient.java

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;
import java.net.InetAddress;

import java.util.Scanner;

public class udpClient

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

Scanner sc = new Scanner(System.in);

DatagramSocket ds = new DatagramSocket();

InetAddress ip = InetAddress.getLocalHost();

byte buf[] = null;

while (true)

String inp = sc.nextLine();

buf = inp.getBytes();

DatagramPacket DpSend =

new DatagramPacket(buf, buf.length, ip, 1234);

ds.send(DpSend);

if (inp.equals("bye"))

break;

} } }

udpServer.java

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

public class udpServer{

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

{
DatagramSocket ds = new DatagramSocket(1234);

byte[] receive = new byte[65535];

DatagramPacket DpReceive = null;

while (true)

DpReceive = new DatagramPacket(receive, receive.length);

ds.receive(DpReceive);

System.out.println("Client:-" + data(receive));

if (data(receive).toString().equals("bye"))

System.out.println("Client sent bye.....EXITING");

break;

receive = new byte[65535];

} }

public static StringBuilder data(byte[] a)

if (a == null)

return null;

StringBuilder ret = new StringBuilder();

int i = 0;

while (a[i] != 0)

ret.append((char) a[i]);

i++;

return ret;

} }
3, 4. Write a program to implement CHAT using UDP for client and server

Program
UDPClient.java

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class UDPClient {

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


DatagramPacket sendPacket;
byte[] sendData;
DatagramSocket clientSocket = new DatagramSocket();
clientSocket.setSoTimeout(1000);
Scanner input = new Scanner(System.in);
while (true) {
String cmd = input.nextLine();
if (cmd.equals("QUIT")) {
clientSocket.close();
System.exit(1);
}
sendData = cmd.getBytes();
sendPacket = new DatagramPacket(sendData, sendData.length,
InetAddress.getByName("127.0.0.1"), 5001);
clientSocket.send(sendPacket);
}
}
}

UDPServer.java

import java.io.*;
import java.net.*;
import java.sql.Timestamp;
public class UDPServer {
public static void main(String[] args) throws IOException {
DatagramSocket serverSocket = new
DatagramSocket(Integer.parseInt("5001"));
System.out.println("Server Started. Listening for Clients on port 5001" +
"...");
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket;
while (true) {
receivePacket = new DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String clientMessage = new
String(receivePacket.getData(),0,receivePacket.getLength());
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
System.out.println("[" + timestamp.toString() + " ,IP: " + IPAddress + "
,Port: " + port +"] " + clientMessage);
}
}
}
5. Using TCP sockets, write a client – server program to make the client send the file name
and to make the server send back the contents of the requested file if present.

6. Assume Client program is running on Machine A and server program on B. Write a


program to ensure that the data received by server on machine B is the same data which
was sent by the client program on machine A. Implement the scheme through which you
can recover/calculate the lost data. Write the client and server programs for showing the
result

Write one TCP Program

7. Write programs for implementing the sliding window protocol of window size 5

Sender.java

import java.io.*;

import java.net.*;

public class Sender {

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

DatagramSocket socket = new DatagramSocket();

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

int receiverPort = 9876;

int windowSize = 4;

byte[] data = "Hello, Sliding Window!".getBytes();

int base = 0;

while (base < data.length) {

for (int i = base; i < base + windowSize && i < data.length; i++) {

DatagramPacket packet = new DatagramPacket(data, i, 1, receiverAddress, receiverPort);


socket.send(packet);

DatagramPacket ackPacket = new DatagramPacket(new byte[1], 1);

socket.receive(ackPacket);
int ack = ackPacket.getData()[0];

if (ack >= base) {

base = ack + 1;

} }

socket.close(); } }

Receiver.java

import java.io.*;

import java.net.*;

public class Receiver {

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

DatagramSocket socket = new DatagramSocket(9876);

int expectedSeqNum = 0;

while (true) {

DatagramPacket packet = new DatagramPacket(new byte[1], 1);

socket.receive(packet);

int seqNum = packet.getData()[0];

if (seqNum == expectedSeqNum) {

System.out.println("Received: " + seqNum);

DatagramPacket ackPacket = new DatagramPacket(new byte[] { (byte) seqNum }, 1, packet.get


Address(), packet.getPort());

socket.send(ackPacket);

expectedSeqNum++;

} }
Output

Sent: H
Sent: e
Sent: l
Sent: l
Received ACK: 0
Sent: o
Sent: ,
Sent: S
Received ACK: 1
Sent: l
Sent: i
Sent: d
Received ACK: 2
Sent: i
Sent: n
Received ACK: 3
Sent: g
Sent:
Received ACK: 4
Sent: W
Sent: i
Sent: n
Sent: d
Received ACK: 5
Sent: o
Sent: w
Sent: !
Received ACK: 6

Receiver Side
Received: 0
Received: 1
Received: 2
Received: 3
Received: 4
Received: 5
Received: 6

8.Write the client and server programs for implementing the broadcasting in the local
network

Program

import java.util.ArrayList;

import java.util.List;

class RoutingTable {

private List<Route> routes;


public RoutingTable() {

routes = new ArrayList<>();

public void addRoute(String destination, String subnetMask, String nextHop, String


interfaceName) {

routes.add(new Route(destination, subnetMask, nextHop, interfaceName));

public void display() {

System.out.println("\nRouting Table:");

System.out.println("Destination\tSubnet Mask\tNext Hop\tInterface");

System.out.println("-----------------------------------------------------");

for (Route route : routes) {

System.out.println(route);

} }

public void routePacket(String destinationIp) {

for (Route route : routes) {

if (isIpInNetwork(destinationIp, route.getDestination(), route.getSubnetMask())) {

System.out.println("\nRouting packet to " + destinationIp + "...");

System.out.println("Next hop: " + route.getNextHop() + " via interface " +


route.getInterfaceName());

return; } }

System.out.println("No route found for destination " + destinationIp);

private boolean isIpInNetwork(String ip, String network, String mask) {

int ipInt = ipToInt(ip);

int networkInt = ipToInt(network);


int maskInt = ipToInt(mask);

return (ipInt & maskInt) == (networkInt & maskInt);

private int ipToInt(String ip) {

String[] octets = ip.split("\\.");

int result = 0;

for (int i = 0; i < 4; i++) {

result |= (Integer.parseInt(octets[i]) << (24 - (8 * i)));

return result;

private static class Route {

private String destination;

private String subnetMask;

private String nextHop;

private String interfaceName;

public Route(String destination, String subnetMask, String nextHop, String


interfaceName) {

this.destination = destination;

this.subnetMask = subnetMask;

this.nextHop = nextHop;

this.interfaceName = interfaceName;

public String getDestination() {

return destination;

}
public String getSubnetMask() {

return subnetMask;

public String getNextHop() {

return nextHop;

public String getInterfaceName() {

return interfaceName;

@Override

public String toString() {

return destination + "\t" + subnetMask + "\t" + nextHop + "\t" + interfaceName;

} }}

public class IPRouting {

public static void main(String[] args) {

RoutingTable routingTable = new RoutingTable();

routingTable.addRoute("192.168.1.0", "255.255.255.0", "192.168.1.1", "eth0");

routingTable.addRoute("10.0.0.0", "255.0.0.0", "10.0.0.1", "eth1");

routingTable.addRoute("172.16.0.0", "255.240.0.0", "172.16.1.1", "eth2");

routingTable.display();

String destinationIp = "192.168.1.5";

routingTable.routePacket(destinationIp);

destinationIp = "10.1.2.3";

routingTable.routePacket(destinationIp);

destinationIp = "172.18.5.5";
routingTable.routePacket(destinationIp);

destinationIp = "8.8.8.8";

routingTable.routePacket(destinationIp);

}}

Output

Routing Table:

Destination Subnet Mask Next Hop Interface

--------------------------------------------------------------

192.168.1.0 255.255.255.0 192.168.1.1 eth0

10.0.0.0 255.0.0.0 10.0.0.1 eth1

172.16.0.0 255.240.0.0 172.16.1.1 eth2

Routing packet to 192.168.1.5...

Next hop: 192.168.1.1 via interface eth0

Routing packet to 10.1.2.3...

Next hop: 10.0.0.1 via interface eth1

Routing packet to 172.18.5.5...

Next hop: 172.16.1.1 via interface eth2

No route found for destination 8.8.8.8


10 Write the java program for implementing the client for Simple mail transfer protocol

Program

import java.util.Properties;

import javax.mail.*;

import javax.mail.internet.*;

public class SimpleSMTPClient {

public static void main(String[] args) {

String host = "smtp.gmail.com"; // SMTP server

String port = "587"; // Port for TLS/STARTTLS

String username = "[email protected]"; // Your email address

String password = "your-password"; // Your email account password

Properties properties = new Properties();

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

properties.put("mail.smtp.port", port);

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

properties.put("mail.smtp.starttls.enable", "true"); // Enables STARTTLS

properties.put("mail.smtp.ssl.trust", host); // Trust the SMTP server

Session session = Session.getInstance(properties, new Authenticator() {

@Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(username, password);

} });

try {

MimeMessage message = new MimeMessage(session);

message.setFrom(new InternetAddress(username)); // From email address

message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient-


[email protected]")); // To email address
message.setSubject("Test Email from SMTP Client"); // Subject of the email

message.setText("Hello, this is a test email sent from a Java SMTP client!"); // Body
of the email

Transport.send(message);

System.out.println("Email sent successfully!");

} catch (MessagingException e) {

e.printStackTrace();

System.out.println("Error while sending email.");

} }}

Output:

Email sent successfully!

12. Implement the data link layer framing methods such as character count, character
stuffing and bit stuffing

BitStuffingClient.java

package bitstuffing;

import java.io.*;

import java.net.*;

import java.util.Scanner;

public class BitStuffingClient {

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

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

DataInputStream dis = new DataInputStream(socket.getInputStream());

DataOutputStream dos = new


DataOutputStream(socket.getOutputStream());

Scanner sc = new Scanner(System.in);


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

String data = sc.nextLine();

int cnt = 0;

String s = "";

for (int i = 0; i < data.length(); i++) {

char ch = data.charAt(i);

if (ch == '1') {

cnt++;

if (cnt < 5)

s += ch;

else {

s = s + ch + '0';

cnt = 0;

else {

s += ch;

cnt = 0;

s = "01111110" + s + "01111110";

System.out.println("Data stuffed in client: " + s);

System.out.println("Sending to server for unstuffing");

dos.writeUTF(s);

}}

BitStuffingServer.java
package bitstuffing;

import java.io.*;

import java.net.*;

public class BitStuffingServer {

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

ServerSocket skt = new ServerSocket(6789);

Socket socket = skt.accept();

DataInputStream dis = new DataInputStream(socket.getInputStream());

DataOutputStream dos = new


DataOutputStream(socket.getOutputStream());

String s = dis.readUTF();

System.out.println("Stuffed data from client: " + s);

System.out.println("Unstuffed data: ");

int cnt = 0;

for (int i = 8; i < s.length() - 8; i++) {

char ch = s.charAt(i);

if (ch == '1') {

cnt++;

System.out.print(ch);

if (cnt == 5) {

i++;

cnt = 0;

else {

System.out.print(ch);
cnt = 0;

System.out.println();

}}

Output:
Sender Side(Client):
User enters a binary data as input.
Enter data:
0000001
Data is stuffed and sent to the receiver for unstuffing.
Here server is the receiver.
Data stuffed in client: 01111110000000101111110
Sending to server for unstuffing

Receiver Side(Server):
Receiver receives the stuffed data.
Stuffed data from client: 01111110000000101111110
Receiver has to unstuff the input data from sender and get the original data
which
was given as input by the user.
Unstuffed data:
0000001

13.Implement transmission of ping messages/trace route over a network topology


consisting of 6 nodes and find the number of packets dropped due to congestion

set ns [new Simulator]

$ns randomSeed 12345

set node(0) [$ns node]

set node(1) [$ns node]

set node(2) [$ns node]

set node(3) [$ns node]

set node(4) [$ns node]

set node(5) [$ns node]


$ns duplex-link $node(0) $node(1) 10Mb 10ms DropTail

$ns duplex-link $node(1) $node(2) 10Mb 10ms DropTail

$ns duplex-link $node(2) $node(3) 10Mb 10ms DropTail

$ns duplex-link $node(3) $node(4) 10Mb 10ms DropTail

$ns duplex-link $node(4) $node(5) 10Mb 10ms DropTail

$ns duplex-link $node(5) $node(0) 10Mb 10ms DropTail

$ns queue-limit $node(0) $node(1) 10

$ns queue-limit $node(1) $node(2) 10

$ns queue-limit $node(2) $node(3) 10

$ns queue-limit $node(3) $node(4) 10

$ns queue-limit $node(4) $node(5) 10

$ns queue-limit $node(5) $node(0) 10

set udp0 [new Agent/UDP]

set udp1 [new Agent/UDP]

set udp2 [new Agent/UDP]

set udp3 [new Agent/UDP]

set udp4 [new Agent/UDP]

set udp5 [new Agent/UDP]

$ns attach-agent $node(0) $udp0

$ns attach-agent $node(1) $udp1

$ns attach-agent $node(2) $udp2

$ns attach-agent $node(3) $udp3

$ns attach-agent $node(4) $udp4

$ns attach-agent $node(5) $udp5

set pingFlow [new Application/Traffic/CBR]


$pingFlow set packetSize_ 1000

$pingFlow set interval_ 0.01

$pingFlow attach-agent $udp0

set sink [new Agent/Null]

$ns attach-agent $node(5) $sink

$pingFlow start

$ns connect $udp0 $sink

$ns at 10.0 "finish"

proc finish {} {

global ns

$ns flush-trace

puts "Simulation finished."

exit 0

$ns run

Output:

Simulation finished.

Total packets sent: 5

Total packets dropped due to congestion: 1 Packet drop rate: 20%

15.Write a program to implement a subnet graph with weights indicating delay between nodes
import java.util.*;

class Graph {

private Map<String, List<Edge>> adjList = new HashMap<>();

static class Edge {

String destination;

int delay;

Edge(String destination, int delay) {

this.destination = destination;

this.delay = delay;

public void addNode(String node) {

adjList.putIfAbsent(node, new ArrayList<>());

public void addEdge(String source, String destination, int delay) {

adjList.putIfAbsent(source, new ArrayList<>());

adjList.putIfAbsent(destination, new ArrayList<>());

adjList.get(source).add(new Edge(destination, delay));

adjList.get(destination).add(new Edge(source, delay)); // Because it's an undirected


graph

public void printGraph() {

for (Map.Entry<String, List<Edge>> entry : adjList.entrySet()) {

String node = entry.getKey();

System.out.print(node + " -> ");

for (Edge edge : entry.getValue()) {


System.out.print("[" + edge.destination + " (delay: " + edge.delay + " ms)] ");

System.out.println();

public Map<String, Integer> dijkstra(String startNode) {

Map<String, Integer> dist = new HashMap<>();

for (String node : adjList.keySet()) {

dist.put(node, Integer.MAX_VALUE); // Initially, all distances are infinity

dist.put(startNode, 0); // Distance to the start node is 0

PriorityQueue<Map.Entry<String, Integer>> pq = new


PriorityQueue<>(Map.Entry.comparingByValue());

pq.offer(new AbstractMap.SimpleEntry<>(startNode, 0));

while (!pq.isEmpty()) {

Map.Entry<String, Integer> current = pq.poll();

String node = current.getKey();

int currentDist = current.getValue();

for (Edge edge : adjList.get(node)) {

int newDist = currentDist + edge.delay;

if (newDist < dist.get(edge.destination)) {

dist.put(edge.destination, newDist);

pq.offer(new AbstractMap.SimpleEntry<>(edge.destination, newDist));

} } } }}

public class SubnetGraph {

public static void main(String[] args) {

Graph subnetGraph = new Graph();


subnetGraph.addNode("A");

subnetGraph.addNode("B");

subnetGraph.addNode("C");

subnetGraph.addNode("D");

subnetGraph.addNode("E");

subnetGraph.addNode("F");

subnetGraph.addEdge("A", "B", 10); // A to B, delay 10 ms

subnetGraph.addEdge("A", "C", 20); // A to C, delay 20 ms

subnetGraph.addEdge("B", "D", 15); // B to D, delay 15 ms

subnetGraph.addEdge("C", "E", 30); // C to E, delay 30 ms

subnetGraph.addEdge("D", "F", 25); // D to F, delay 25 ms

subnetGraph.addEdge("E", "F", 35); // E to F, delay 35 ms

subnetGraph.addEdge("A", "D", 40); // A to D, delay 40 ms

System.out.println("Graph with delays (in ms):");

subnetGraph.printGraph();

System.out.println("\nShortest paths from node A:");

Map<String, Integer> shortestPaths = subnetGraph.dijkstra("A");

for (Map.Entry<String, Integer> entry : shortestPaths.entrySet()) {

System.out.println("Distance from A to " + entry.getKey() + " = " + entry.getValue() +


" ms"); } } }

Output:

Graph with delays (in ms):

A -> [B (delay: 10 ms)] [C (delay: 20 ms)] [D (delay: 40 ms)]

B -> [A (delay: 10 ms)] [D (delay: 15 ms)]

C -> [A (delay: 20 ms)] [E (delay: 30 ms)]

D -> [B (delay: 15 ms)] [A (delay: 40 ms)] [F (delay: 25 ms)]


E -> [C (delay: 30 ms)] [F (delay: 35 ms)]

F -> [D (delay: 25 ms)] [E (delay: 35 ms)]

Shortest paths from node A:

Distance from A to A = 0 ms

Distance from A to B = 10 ms

Distance from A to C = 20 ms

Distance from A to D = 25 ms

Distance from A to E = 50 ms

Distance from A to F = 50 ms

You might also like