0% found this document useful (0 votes)
35 views34 pages

Java Client-Server Image Transfer Code

The document contains multiple Java programs demonstrating client-server communication using TCP and UDP protocols. It includes implementations for sending images, echoing messages, DNS resolution, and address resolution protocols (ARP and RARP). Each program is accompanied by a brief description of its functionality and expected output.

Uploaded by

jeni
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)
35 views34 pages

Java Client-Server Image Transfer Code

The document contains multiple Java programs demonstrating client-server communication using TCP and UDP protocols. It includes implementations for sending images, echoing messages, DNS resolution, and address resolution protocols (ARP and RARP). Each program is accompanied by a brief description of its functionality and expected output.

Uploaded by

jeni
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

PROGRAM:

Client :
[Link].*;
[Link].*;
import [Link].*;
[Link].*;
import [Link].*;

public class Client {


public static void main(String[] args) {
Socket soc = null;
BufferedImageimg = null;

try {
soc = new Socket("localhost", 4000);
[Link]("Client is running.");
[Link]("Reading image from disk.");
img = [Link](new File("digital_image_processing.jpg"));

ByteArrayOutputStreambaos = new ByteArrayOutputStream();


[Link](img, "jpg", baos);
[Link]();
byte[] bytes = [Link]();
[Link]();
[Link]("Sending image to server.");
OutputStream out = [Link]();
DataOutputStream dos = new DataOutputStream(out);
[Link]([Link]); // Send length first
[Link](bytes, 0, [Link]); // Then the data

[Link]("Image sent to server.");


[Link]();
[Link]();
}
catch (Exception e)
{
[Link]("Exception: " + [Link]());
}
finally {
try {
if (soc != null) [Link]();
} catch (IOException e) {
[Link]("Error closing socket: " + [Link]());
}
}
}
}
Server:

import [Link].*;
import [Link].*;
[Link].*;
[Link].*;
[Link].*;

public class Server {


public static void main(String[] args) {
ServerSocket server = null;
Socket socket = null;
try {
server = new ServerSocket(4000);
[Link]("Server waiting for image...");

socket = [Link](); // Wait for client connection


[Link]("Client connected.");
InputStream in = [Link]();
DataInputStream dis = new DataInputStream(in);
intlen = [Link](); // First receive the length
[Link]("Image Size: " + (len / 1024) + " KB");

byte[] data = new byte[len];


[Link](data);
[Link]();
[Link]()
InputStreambais = new ByteArrayInputStream(data);
BufferedImagebImage = [Link](bais);
JFrame frame = new JFrame("Server - Received Image");
[Link](JFrame.EXIT_ON_CLOSE);
[Link](500, 500);

ImageIcon icon = new ImageIcon(bImage);


JLabel label = new JLabel(icon);
[Link](label);
[Link]();
[Link](true);
}
catch (Exception e)\
{
[Link]("Exception: " + [Link]());
[Link]();
}
Finally
{
try {
if (socket != null) [Link]();
if (server != null) [Link]();
} catch (IOException e) {
[Link]("Error closing sockets: " + [Link]());
}
}
}

OUTPUT :

When you run the client code, following output screen would appear on client side.
PROGRAM:

[Link]
import [Link].*;
import [Link].*;

public class EServer {


public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket clientSocket = null;

try {
// Start server on port 9000
serverSocket = new ServerSocket(9000);
[Link]("Server started. Waiting for client...");

clientSocket = [Link]();
[Link]("Client connected: " + [Link]());

// Input stream from client


BufferedReader in = new BufferedReader(
new InputStreamReader([Link]()));

// Output stream to client


PrintWriter out = new PrintWriter([Link](), true);

String line;
while ((line = [Link]()) != null) {
[Link]("Received: " + line);
[Link](line); // Echo back to client
}

} catch (IOException e) {
[Link]("Error: " + [Link]());
} finally {
try {
if (clientSocket != null) [Link]();
if (serverSocket != null) [Link]();
} catch (IOException e) {
[Link]("Error closing sockets: " + [Link]());
}
}
}
}
[Link]
import [Link].*;
import [Link].*;

public class EClient {


public static void main(String[] args) {
Socket c = null;
String line;

BufferedReader userInput = null;


BufferedReader serverInput = null;
PrintWriter out = null;

try {
InetAddress ia = [Link]();
c = new Socket(ia, 9000);
[Link]("Connected to the server at: " + [Link]());

out = new PrintWriter([Link](), true);


userInput = new BufferedReader(new InputStreamReader([Link]));
serverInput = new BufferedReader(new InputStreamReader([Link]()));

while (true) {
[Link]("Client: ");
line = [Link]();

if (line == null || [Link]("exit")) {


[Link]("exit");
break;
}

[Link](line);
String serverResponse = [Link]();
if (serverResponse == null) break;
[Link]("Server: " + serverResponse);
}

} catch (IOException e) {
[Link]("Socket Closed or Error: " + [Link]());
} finally {
try {
if (userInput != null) [Link]();
if (serverInput != null) [Link]();
if (out != null) [Link]();
if (c != null) [Link]();
} catch (IOException e) {
[Link]("Error closing resources: " + [Link]());
}
}
}
}

OUTPUT
Server
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
C:\Program Files\Java\jdk1.5.0\bin>java EServer
C:\Program Files\Java\jdk1.5.0\bin>
Client
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
C:\Program Files\Java\jdk1.5.0\bin>java EClient
Client: Hai Server
Server:Hai Server
Client: Hello
Server:Hello
Client:end
Server:end
Client:ds
Socket Closed!
PROGRAM
UDPserver
import [Link].*;
import [Link].*;

class UDPserver {
public static void main(String args[]) throws Exception {
int serverport = 790; // Server listens on this port
DatagramSocket ds = new DatagramSocket(serverport);
[Link]("UDP Server started on port " + serverport + ". Type 'end' to stop.");

BufferedReader dis = new BufferedReader(new InputStreamReader([Link]));

while (true) {
byte[] receiveBuffer = new byte[1024];
DatagramPacket p = new DatagramPacket(receiveBuffer, [Link]);
[Link](p);

String clientMsg = new String([Link](), 0, [Link]());


[Link]("Client: " + clientMsg);

if ([Link]("end")) {
[Link]("Client requested termination. Server exiting...");
break;
}
[Link]("Server: ");
String serverResponse = [Link]();

if ([Link]("end")) {
[Link]("Server exiting...");
break;
}

byte[] sendBuffer = [Link]();


DatagramPacket sendPacket = new DatagramPacket(
sendBuffer,
[Link],
[Link](),
[Link]()
);
[Link](sendPacket);
}

[Link]();
}
}

[Link]
import [Link].*;
import [Link].*;

class UDPclient {
public static void main(String args[]) throws Exception {
int clientport = 789; // client local port
int serverport = 790; // server listening port

DatagramSocket ds = new DatagramSocket(clientport);


BufferedReader dis = new BufferedReader(new InputStreamReader([Link]));
InetAddress ia = [Link]();
[Link]("Client started. Type 'end' to quit.");

while (true) {
[Link]("Client: ");
String str = [Link]();

if ([Link]("end")) {
byte[] endBuffer = [Link]();
[Link](new DatagramPacket(endBuffer, [Link], ia, serverport));
[Link]("Client exiting...");
break;
}

byte[] sendBuffer = [Link]();


DatagramPacket sendPacket = new DatagramPacket(sendBuffer, [Link], ia,
serverport);
[Link](sendPacket);

byte[] receiveBuffer = new byte[1024];


DatagramPacket receivePacket = new DatagramPacket(receiveBuffer, [Link]);
[Link](receivePacket);

String response = new String([Link](), 0, [Link]());


[Link]("Server: " + response);
}

[Link]();
}
}

OUTPUT:

Server

C:\Program Files\Java\jdk1.5.0\bin>javac [Link]


C:\Program Files\Java\jdk1.5.0\bin>java UDPserver
press ctrl+c to quit the program
Client:Hai Server
Server:Hello Client
Client:How are You
Server:I am Fine

Client
C:\Program Files\Java\jdk1.5.0\bin>javac [Link]
C:\Program Files\Java\jdk1.5.0\bin>java UDPclient
server waiting
Client:Hai Server
Server:Hello Client
Client:How are You
Server:I am Fine
Client:end

PROGRAM

DNS Server

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].equalsIgnoreCase(str)) {

return i;

return -1;

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

String[] hosts = {"[Link]", "[Link]", "[Link]", "[Link]"};

String[] ip = {"[Link]", "[Link]", "[Link]", "[Link]"};

DatagramSocket serverSocket = new DatagramSocket(1362);

[Link]("UDP DNS Server started on port 1362...");

[Link]("Press Ctrl + C to Quit");

byte[] sendData;

byte[] receiveData = new byte[1024];

while (true) {

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);

[Link](receivePacket);

String hostName = new String([Link](), 0,


[Link]()).trim();

[Link]("Request for host: " + hostName);

String response;

int index = indexOf(hosts, hostName);

if (index != -1) {

response = ip[index];

} else {

response = "Host Not Found";

sendData = [Link]();
InetAddress clientAddress = [Link]();

int clientPort = [Link]();

DatagramPacket sendPacket = new DatagramPacket(sendData, [Link],

clientAddress, clientPort);

[Link](sendPacket);

DNS Client

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 serverAddress;

int port = 1362;

if ([Link] == 0) {

serverAddress = [Link]();

} else {

serverAddress = [Link](args[0]);

}
[Link]("Enter the hostname: ");

String sentence = [Link]();

byte[] sendData = [Link]();

DatagramPacket sendPacket = new DatagramPacket(sendData, [Link], se

serverAddress, port);

[Link](sendPacket);

byte[] receiveData = new byte[1024];

DatagramPacket receivePacket = new DatagramPacket(receiveData, [Link]);

[Link](receivePacket);

String response = new String([Link](), 0, [Link]());

[Link]("IP Address: " + response);

[Link]();

OUTPUT

Server

javac [Link]

java udpdnsserver

Press Ctrl + C to Quit

Request for host [Link]


Client

javac [Link]

java udpdnsclient

Enter the hostname : [Link]

IP Address: [Link]

PROGRAM
Client:
import [Link].*;
import [Link].*;
import [Link].*;
class Clientarp
{
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 Logical address(IP):");
String str1=[Link]();
[Link](str1+'\n';
String str=[Link]();
[Link]("The Physical Address is: "+str);
[Link]();
}
catch (Exception e)
{
[Link](e);
}}
}

Server:
import [Link].*;
import [Link].*;
import [Link].*;
class Serverarp
{
public static void main(String args[])
{
try{
ServerSocket obj=new
ServerSocket(139); Socket
obj1=[Link]();
while(true)
{
DataInputStream din=new DataInputStream([Link]());
DataOutputStream dout=new DataOutputStream([Link]());
String str=[Link]();
String ip[]={"[Link]","[Link]"};
String mac[]={"[Link]","[Link]"};
for(int i=0;i<[Link];i++)
{
if([Link](ip[i]))
{
[Link](mac[i]+'\n');
break;
}
}
[Link]();
}
}
catch(Exception e)
{

[Link](e);
}}
}
Output:
E:\networks>java Serverarp
E:\networks>java Clientarp
Enter the Logical address(IP):
[Link]
The Physical Address is: [Link]

Reverse Address Resolution Protocol (RARP) using UDP


PROGRAM:
Client
import [Link].*;
import [Link].*;
import [Link].*;
class Clientrarp12 {
public static void main(String args[]) {
try {
DatagramSocket client = new DatagramSocket();
InetAddress addr = [Link]("[Link]");
byte[] sendbyte = new byte[1024];
byte[] receivebyte = new byte[1024];
BufferedReader in = new BufferedReader(new InputStreamReader([Link]));
[Link]("Enter the Physical address (MAC):");
String str = [Link]();
sendbyte = [Link]();
DatagramPacket sender = new DatagramPacket(sendbyte, [Link], addr, 1309);
[Link](sender);
DatagramPacket receiver = new DatagramPacket(receivebyte, [Link]);
[Link](receiver);
String s = new String([Link](), 0, [Link]());
[Link]("The Logical Address is (IP): " + [Link]());
[Link]();
} catch (Exception e) {
[Link](e);
}
}
}

Server
import [Link].*;
import [Link].*;
import [Link].*;
class Serverrarp12 {
public static void main(String args[]) {
try {
DatagramSocket server = new DatagramSocket(1309);
String ip[] = {"[Link]", "[Link]"};
String mac[] = {"[Link]", "[Link]"};
while (true) {
byte[] sendbyte = new byte[1024];
byte[] receivebyte = new byte[1024];

DatagramPacket receiver = new DatagramPacket(receivebyte, [Link]);


[Link](receiver);
String str = new String([Link](), 0, [Link]()).trim();
InetAddress addr = [Link]();
int port = [Link]();
String responseIP = "MAC Address not found";
for (int i = 0; i < [Link]; i++) {
if ([Link](mac[i])) {
responseIP = ip[i]; // Corresponding IP
break;
}
}
sendbyte = [Link]();
DatagramPacket sender = new DatagramPacket(sendbyte, [Link], addr,
port);
[Link](sender);
}
} catch (Exception e) {
[Link](e);
}
}
}

Output:
I:\ex>java Serverrarp12
I:\ex>java Clientrarp12
Enter the Physical address (MAC): [Link]
The Logical Address is(IP): [Link]
PROCEDURE:

Network Simulator (Version 2), widely known as NS2, is simply an eventdriven simulation tool
that has proved useful in studying the dynamic nature of communication networks. Simulation of
wired as well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP)
can be done using NS2. In general, NS2 provides users with a way of specifying such network
protocols and simulating their corresponding behaviors

Ns functionalities
Routing, Transportation, Traffic sources,Queuing disciplines, QoS

Congestion Control Algorithms


 Slow start
 Additive increase/multiplicative decrease
 Fast retransmit and Fast recovery

Case Study: A simple Wireless network.


Ad hoc routing, mobile IP,
sensor-MAC Tracing,
visualization and various utilitie NS(Network Simulators)

Packet loss
Packet loss occurs when one or more packets of data travelling across a computer network fail 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 error and spurious packets caused due to noise.

Throughput
Throughput is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, 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 value of 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 the system 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.

Congestion control Algorithms


Slow-start is used in conjunction with other algorithms to avoid sending more data than the network
is capable of transmitting, that is, to avoid causing network congestion. AIMD combines linear
growth of the congestion window with an exponential reduction when a congestion takes place.
Multiple flows using AIMD congestion control will eventually converge to use equal amounts of
a contended link. Fast Retransmit is an enhancement to TCP that reduces the time a sender waits
before retransmitting a lost segment.

PROGRAM:

set ns [new Simulator]


$ns color 0 Blue
$ns color 1 Red
$ns color 2 Yellow
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set f [open [Link] w]
$ns trace-all $f
set nf [open [Link] w]
$ns namtrace-all $nf
$ns duplex-link $n0 $n2 5Mb 2ms DropTail
$ns duplex-link $n1 $n2 5Mb 2ms DropTail
$ns duplex-link $n2 $n3 1.5Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-up
$ns duplex-link-op $n1 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n2 $n3 queuePos 0.5
set tcp [new Agent/TCP]
$tcp set class_ 1
set sink [new Agent/TCPSink]

$ns attach-agent $n1 $tcp


$ns attach-agent $n3 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 1.2 "$ftp start"
$ns at 1.35 "$ns detach-agent $n1 $tcp ; $ns detach-
agent $n3 $sink" $ns at 3.0 "finish"
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
puts "Running nam.."
exec xgraph [Link] -geometry 600x800
& exec nam [Link] &
exit 0

}
$ns run
Output

# Time (s) Event Node Agent Packet Source Dest Info


# ----------- -------- ----- ---------- ------- ------- ------- ----------------
0.0000 "Start" 0 Agent/TCP 1 0 1 "Sender starts"
0.1000 "Send" 0 Agent/TCP 500 0 1 "Packet 0 sent"
0.1100 "Send" 0 Agent/TCP 500 0 1 "Packet 1 sent"
0.1200 "Send" 0 Agent/TCP 500 0 1 "Packet 2 sent"
0.1300 "Send" 0 Agent/TCP 500 0 1 "Packet 3 sent"
0.1500 "Recv" 1 Agent/TCPSink 500 0 1 "Ack 0 received"
0.1700 "Recv" 1 Agent/TCPSink 500 0 1 "Ack 1 received"
0.1900 "Recv" 1 Agent/TCPSink 500 0 1 "Ack 2 received"
0.2100 "Recv" 1 Agent/TCPSink 500 0 1 "Ack 3 received"
0.3400 "Send" 0 Agent/TCP 500 0 1 "Packet 4 sent"
0.3600 "Send" 0 Agent/TCP 500 0 1 "Packet 5 sent"
0.3800 "Recv" 1 Agent/TCPSink 500 0 1 "Ack 4 received"
...
3.5000 "Stop" 0 Application/FTP 0 0 1 "FTP stops"
PROCEDURE:
 TCP is a connection-oriented protocol that ensures reliable delivery of data. It provides
features like error correction, flow control, and congestion control.

 UDP is a connectionless protocol that sends data without ensuring reliability. It is faster
but may lose packets due to network issues, as it does not have mechanisms for error
handling or retransmission.

 TCP is reliable protocol. That is, the receiver always sends either positive or negative
acknowledgement about the data packet to the sender, so that the sender always has
bright clue about whether the data packet is reached the destination or it needs to resend
it.
 TCP ensures that the data reaches intended destination in the same order it was sent.

 The User Datagram Protocol (UDP) is simplest Transport Layer communication protocol
available of the TCP/IP protocol suite. It involves minimum amount of communication
mechanism. UDP is said to be an unreliable transport protocol but it uses IP services
which provides best effort delivery [Link] is used when acknowledgement of
data does not hold any significance.

 UDP is suitable protocol for streaming applications such as VoIP, multimedia streaming.

Objective of the Study


The main objective of the study is to compare TCP and UDP based on several performance
metrics:

 Throughput (Data transfer rate)

 Latency (RTT) (Round-trip time)


 Packet Loss

 Congestion Control

 Retransmissions

Steps for TCP/UDP Performance Evaluation in NS-2


1. Define Simulation Parameters:

o Set the total simulation time, node configurations, link parameters, etc.

2. Create Nodes:

o Create sender and receiver nodes for both TCP and UDP.

3. Link Configuration:

o Set bandwidth, delay, and drop behavior on the links between nodes.

4. Setup TCP and UDP Protocols:

o Attach TCP or UDP agents to the sender and receiver nodes.

5. Attach Applications:

o For TCP, use FTP application.

o For UDP, use a Traffic Generator to simulate UDP packet sending.

6. Trace Files:

o Define trace files to capture the packet transmission, throughput, RTT, and other
important metric
DISTANCE VECTOR PROTOCOL
PROGRAM
setns[newSimulator]
set nr [[Link] w]
$nstrace-all$nr
setnf[[Link]]
$nsnamtrace-all$nf
proc finish { } {
global ns nr nf
$nsflush-trace close $nf
close$nr
[Link]&
exit 0
}
for{seti0}{$i<12}{incr i1}{ set n($i)
[$ns node]}
for{seti0}{$i<8}{incri} {
$nsduplex-link$n($i)$n([expr$i+1]) 1Mb10msDropTail}
$nsduplex-link$n(0) $n(8) 1Mb10msDropTail
$nsduplex-link$n(1) $n(10) 1Mb10msDropTail
$nsduplex-link$n(0) $n(9)1Mb10msDropTail
$nsduplex-link$n(9) $n(11) 1Mb10msDropTail
$nsduplex-link$n(10) $n(11) 1Mb10msDropTail
$nsduplex-link$n(11) $n(5) 1Mb10msDropTail
setudp0[new Agent/UDP]
$nsattach-agent$n(0)$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_ 500
$cbr0setinterval_0.005
$cbr0attach-agent$udp0
set null0[newAgent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp0$null0
setudp1[new Agent/UDP]
$nsattach-agent$n(1)$udp1
setcbr1[newApplication/Traffic/CBR]
$cbr1setpacketSize_ 500
$cbr1setinterval_0.005
$cbr1attach-agent$udp1
set null0[newAgent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp1$null0
$nsrtprotoDV
$nsrtmodel-at10.0down$n(11) $n(5)
$nsrtmodel-at15.0down$n(7)$n(6)
$nsrtmodel-at30.0 up$n(11)$n(5)
$nsrtmodel-at20.0 up$n(7)$n(6)
$udp0set fid_1
$udp1set fid_2
$nscolor1 Red
$nscolor2 Green
$nsat1.0"$cbr0 start"
$nsat2.0"$cbr1 start"
$nsat45"finish"
$nsrun

OUTPUT
LINK STATE ROUTING PROTOCOL

PROGRAM
setns[newSimulator]
set nr [[Link] w]
$nstrace-all$nr
setnf[[Link]]
$nsnamtrace-all$nf
proc finish { } {
global ns nr nf
$nsflush-trace
close $nf
close$nr
[Link]&
exit 0
}
for{seti0}{$i<12}{incr i1}{
set n($i) [$ns node]}
for{seti0}{$i<8}{incri} {
$nsduplex-link$n($i)$n([expr$i+1]) 1Mb10msDropTail}
$nsduplex-link$n(0) $n(8) 1Mb10msDropTail
$nsduplex-link$n(1) $n(10) 1Mb10msDropTail
$nsduplex-link$n(0) $n(9) 1Mb10msDropTail
$nsduplex-link$n(9) $n(11) 1Mb10msDropTail
$nsduplex-link$n(10) $n(11)1Mb10msDropTail
$nsduplex-link$n(11) $n(5) 1Mb10msDropTail
setudp0[new Agent/UDP]
$nsattach-agent$n(0)$udp0
setcbr0[newApplication/Traffic/CBR]
$cbr0setpacketSize_ 500
$cbr0setinterval_0.005
$cbr0attach-agent$udp0
set null0[newAgent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp0$null0
setudp1[new Agent/UDP]
$nsattach-agent$n(1)$udp1
setcbr1[newApplication/Traffic/CBR]
$cbr1setpacketSize_ 500
$cbr1setinterval_0.005
$cbr1attach-agent$udp1
set null0[newAgent/Null]
$nsattach-agent$n(5)$null0
$nsconnect$udp1$null0
$nsrtprotoLS
$nsrtmodel-at10.0down$n(11) $n(5)
$nsrtmodel-at15.0down$n(7)$n(6)
$nsrtmodel-at30.0 up$n(11)$n(5)
$nsrtmodel-at20.0 up$n(7)$n(6)
$udp0set fid_1
$udp1set fid_2
$nscolor1 Red
$nscolor2 Green
$nsat1.0"$cbr0 start"
$nsat2.0"$cbr1 start"
$nsat45"finish"
$ns run
OUTPUT

Program :

import sys

from [Link] import *

# Define the packet capturing function

def packet_handler(packet):

print([Link]())

# Capture packets on the network interfacesniff(iface='eth0',

prn=packet_handler)

Output:

###[ Ethernet ]###

dst = [Link]

src = [Link] type = IPv4 ###[ IP ]###

version = 4
ihl =5

tos = 0x0

len = 1500

id = 52786

flags = DF frag = 0

ttl = 128

proto= tcp

chksum= 0xe877

src = [Link]

dst = [Link]

\options \ ###[ TCP ]### sport= 54321

dport= http

seq = 3665840854

ack = 2542707921

dataofs = 5

reserved = 0 flags = FA window= 8760 chksum= 0x9d6c urgptr= 0

options = [('MSS', 1460), ('SAckOK', ''), ('Timestamp', (12576855, 2413)), ('NOP', None),

('WScale', 7)] ###[ Raw ]###

load = ''
Program
import [Link].*;
[Link].*;
class crc
{
publicstaticvoidmain(Stringargs[])
{
Scannerinput=newScanner([Link]); int n;

// Readinput
[Link]("Enterthesizeofthedata:"); n = [Link]();
int data[] = new int[n]; [Link]("Enterthedata,bitbybit:");
for(inti=0 ; i < n ; i++)
{
[Link]("Enterbitnumber"+(n-i)+":");
data[i] = [Link]();
}
//ReadDivisor
[Link]("Enterthesizeofthedivisor:");
n = [Link]();
int divisor[] = new int[n];
[Link]("Enterthedivisor,bitbybit:");
for(inti=0 ; i< n ; i++)
{
[Link]("Enterbitnumber"+(n-i)+":"); divisor[i] = [Link]();
}
//PerformDivision
int remainder[] = divide(data, divisor); for(inti=0;i<[Link]-1;i++)
{
[Link](remainder[i]);
}
[Link]("\nTheCRCcodegenerated is:");
for(inti=0;i<[Link];i++)
{
[Link](data[i]);
}
for(inti=0;i<[Link]-1;i++)
{
[Link](remainder[i]);
}
[Link]();
//Appendtheremainder
int sent_data[]=newint[[Link]+[Link]-1];
[Link]("Enter the data to be sent:");
for(inti=0;i<sent_data.length;i++)
{
[Link]("Enterbitnumber"+(sent_data.length-i)+":"); sent_data[i] =
[Link]();
}
receive(sent_data,divisor);
}
staticint[]divide(intold_data[],int divisor[])
{
int remainder[], i;
int data[] = new int[old_data.length + [Link]];
[Link](old_data,0,data,0,old_data.length);

//Remainderarraystorestheremainder
remainder = new int[[Link]];
// Initially, remainder's bits will be set to the data bits
[Link](data,0,remainder,0,[Link]);
for(i=0;i<old_data.length; i++)
{
[Link]((i+1)+".)Firstdatabitis:"
+remainder[0]);
[Link]("Remainder:");
//Iffirstbit ofremainderis1thenexortheremainderbitswithdivisorbits

if(remainder[0] ==1)
{
for(intj=1;j<[Link]; j++)
{
remainder[j-1]=exor(remainder[j],divisor[j]);
[Link](remainder[j-1]);
}
}
else
{
//Iffirstbitofremainder is0thenexortheremainderbitswith0 for(int j=1 ;
j< [Link] ; j++)
{
remainder[j-1]=exor(remainder[j],0);
[Link](remainder[j-1]);
}
}
remainder[[Link]-1]=data[i+[Link]];
[Link](remainder[[Link]-1]);
}
returnremainder;
}
staticint exor(inta,intb)
{
if(a==b)
{
return 0;
}
return1;
}
staticvoidreceive(intdata[],int divisor[])
{

intremainder[]=divide(data,divisor);
for(inti=0 ;i<[Link]; i++)
{

if(remainder[i]!=0)
{
[Link]("Thereisanerrorinreceiveddata..."); return;
}
}
[Link]("Datawasreceivedwithoutanyerror.");
}

OUTPUT
D:\Abarna>[Link] D:\Abarna>java crc
Enterthesizeofthedata:7
Enter the data, bit by bit:
Enter bit number 7:
1
Enterbitnumber6:
0
Enterbitnumber5:
0
Enterbitnumber4:
1
Enterbitnumber3:
1
Enterbitnumber2:
0
Enterbitnumber1:
1
Enterthesizeofthedivisor:4 Enter the divisor, bit by bit: Enter bit number 4:
1
Enterbitnumber3:
0
Enterbitnumber2:
1
Enterbitnumber1:
1
1.) Firstdatabitis:1
Remainder : 0101
2.) Firstdatabitis:0
Remainder : 1010
3.) Firstdatabitis:1
Remainder : 0011
4.) Firstdatabitis:0
Remainder : 0110
5.) Firstdatabitis:0
Remainder : 1100
6.) Firstdatabitis:1
Remainder : 1110
7.) Firstdatabitis:1
Remainder : 1010

The CRC code generated is: 1001101101


Enter the data to be sent: Enter bit number 10:
1
Enterbitnumber9: 0
Enterbitnumber8: 0
Enterbitnumber7: 1
Enterbitnumber6: 1
Enterbitnumber5: 0

Enterbitnumber4:
1
Enterbitnumber3:
1
Enterbitnumber2:
0
Enterbitnumber1:
1
1.) Firstdatabitis:1
Remainder : 0101
2.) Firstdatabitis:0
Remainder : 1010
3.) Firstdatabitis:1
Remainder : 0011
4. ) Firstdatabitis:0
Remainder : 0111
5.) Firstdatabitis:0
Remainder : 1110
6.) Firstdatabitis:1
Remainder : 1011
7.) Firstdatabitis:1
Remainder : 0000
8. ) Firstdatabitis:0
Remainder : 0000
9.) Firstdatabitis:0
Remainder : 0000
10.) Firstdatabitis:0
Remainder : 0000
Data was received without any error.

You might also like