You are on page 1of 41

PANIPAT INSTITUTE OF ENGINEERING &

TECHNOLOGY

Computer Science & Engineering Department

Lab Manual: Computer Networks Lab


Code: PC-CS-308LA

Submitted To: Submitted By:


Preeti Chhikara Rishabh Chauhan
Assistant Professor 2819124
CSE B.tech CSE VI th Sem

Affiliated to

KURUKSHETRA UNIVERSITY
INDEX

S.no Practical Date Signature

1
Create a socket for HTTP for web page
14/3/2022
upload and download.

2
Write a code simulating ARP /RARP
21/3/2022
protocols.

3
Study of TCP/UDP performance. 4/4/2022

4 Write a program:
a. To implement echo server and client in
java using TCP sockets.
b. To implement date server and client in 18/4/2022
java using TCP sockets.
c. To implement a chat server and client in
java using TCP sockets.
5
To implement simple calculator and invoke
25/4/2022
arithmetic operations from a remote client.

6
To implement bubble sort and sort data using
9/5/2022
a remote client.

7
To simulate a sliding window protocol that
23/5/2022
uses Go Back N ARQ.

8
To sniff and parse packets that pass through
30/5/2022
using raw sockets.
PC-CS- Computer Networks Lab
308LA
Lecture Tutorial Practical Minor Test Practical Total Time
-- -- 3 40 60 100 3 Hour
Purpose To explore networking concepts using Java programming & networking
tools.
Course Outcomes (CO)
CO1 Do Problem Solving using algorithms.
CO2 Design and test simple programs to implement networking concepts using Java.
CO3 Document artifacts using applied addressing & quality standards.
CO4 Design simple data transmission using networking concepts and implement.

COMPUTER NETWORKS (Lab)


1. Create a socket for HTTP for web page upload and download.
2. Write a code simulating ARP /RARP protocols.
3. Study of TCP/UDP performance.
4. Write a program:
a. To implement echo server and client in java using TCP sockets.
b. To implement date server and client in java using TCP sockets.
c. To implement a chat server and client in java using TCP sockets.
5. To implement simple calculator and invoke arithmetic operations from a remote client.
6. To sniff and parse packets that pass through using raw sockets.
7. To implement bubble sort and sort data using a remote client.
8. To simulate a sliding window protocol that uses Go Back N ARQ.
PRACTICAL 1
Create a socket for HTTP for web page upload and download.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
publicclassDownload{
publicstaticvoid main(String[] args)throwsException{
try{
String fileName ="digital_image_processing.jpg";
String website ="http://tutorialspoint.com/java_dip/images/"+fileName;
System.out.println("Downloading File From: "+ website);
URL url =new URL(website);
InputStream inputStream = url.openStream();
OutputStream outputStream =newFileOutputStream(fileName);
byte[] buffer =newbyte[2048];
int length =0;
while((length = inputStream.read(buffer))!=-1){
System.out.println("Buffer Read of length: "+ length);
outputStream.write(buffer,0, length);
}
inputStream.close();
outputStream.close();
}catch(Exception e){
System.out.println("Exception: "+ e.getMessage());
}
}
}

The following example demonstrates ByteArrayOutputStream to upload an image to the server:

Client code

import javax.swing.*;
import java.net.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

publicclassClient{
publicstaticvoid main(String args[])throwsException{
Socket soc;
BufferedImage img =null;
soc=newSocket("localhost",4000);
System.out.println("Client is running. ");
try{
System.out.println("Reading image from disk. ");
img =ImageIO.read(newFile("digital_image_processing.jpg"));
ByteArrayOutputStream baos =newByteArrayOutputStream();
ImageIO.write(img,"jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
baos.close();
System.out.println("Sending image to server. ");
OutputStreamout= soc.getOutputStream();
DataOutputStream dos =newDataOutputStream(out);
dos.writeInt(bytes.length);
dos.write(bytes,0, bytes.length);
System.out.println("Image sent to server. ");
dos.close();
out.close();
}catch(Exception e){
System.out.println("Exception: "+ e.getMessage());
soc.close();
}
soc.close();
}
}
Server Code

import java.net.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
classServer{
publicstaticvoid main(String args[])throwsException{
ServerSocket server=null;
Socket socket;
server =newServerSocket(4000);
System.out.println("Server Waiting for image");
socket = server.accept();
System.out.println("Client connected.");
InputStreamin= socket.getInputStream();
DataInputStream dis =newDataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: "+ len/1024+"KB");
byte[] data =newbyte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian =newByteArrayInputStream(data);
BufferedImage bImage =ImageIO.read(ian);
JFrame f =newJFrame("Server");
ImageIcon icon =newImageIcon(bImage);
JLabel l =newJLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}
PRACTICAL 2

Write a code simulating ARP /RARP protocols

Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientrarp
{
public static void main(String args[])
{
try
{
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the Physical Addres (MAC):");
String str1=in.readLine();
dout.writeBytes(str1+'\n');
String str=din.readLine();
System.out.println("The Logical address is(IP): "+str);
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverrarp
{
public static void main(String args[])
{
try
{
ServerSocket obj=new ServerSocket(139);
Socket obj1=obj.accept();
while(true)
{
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
String ip[]={"165.165.80.80","165.165.79.1"};
String mac[]={"6A:08:AA:C2","8A:BC:E3:FA"};
for(int i=0;i<mac.length;i++)
{
if(str.equals(mac[i]))
{
dout.writeBytes(ip[i]+'\n');
break;
}
}
obj.close();
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output:
E:\networks>java Serverrarp
E:\networks>java Clientrarp
Enter the Physical Address (MAC):
6A:08:AA:C2
The is Logical address(IP): 165.165.80.80
Posted by Meenakshi at 18:20
PRACTICAL 3
Study of TCP/UDP performance.

THEORY:-
TCP (TRANSMISSION CONTROL PROTOCOL)
TCP is a connection oriented protocol. Once a connection is established data can be sent
bidirectional. These are more reliable as they use 3-way handshaking and are used where large
amount of data or secure data is to be transmitted.

WORKING OF TCP:-
A TCP connection is established via 3-way handshaking, which is a process of initiating and
acknowledge a connection. Once it is established connection data transfer can begin. After
transmission the connection is terminated by closing of established virtual circuits.

UDP (USER DATAGRAM PROTOCOL):-


UDP is a simple, connectionless internet protocol. Multiple messages are sent as packets in chunks
using UDP.

WORKING OF UDP:-
It uses simple transmission model without implicit handshaking dialogues for reliability, ordering on
data integrity. Thus UDP provides unreliable service and datagrams way arrive out of order, appear
duplicated or go missing without notice.
Basis Transmission control protocol (TCP) User datagram protocol (UDP)

TCP is a connection-oriented protocol. UDP is the Datagram-oriented protocol.


Connection-orientation means that the This is because there is no overhead for
communicating devices should establish opening a connection, maintaining a
Type of Service a connection before transmitting data connection, and terminating a connection.
and should close the connection after UDP is efficient for broadcast and
transmitting the data. multicast types of network transmission.

Reliability TCP is reliable as it guarantees the


delivery of data to the destination The delivery of data to the destination
router. cannot be guaranteed in UDP.

TCP provides extensive error-checking


mechanisms. It is because it provides
Error checking flow control and acknowledgment of UDP has only the basic error checking
mechanism data. mechanism using checksums.

Acknowledgment An acknowledgment segment is present. No acknowledgment segment.

Sequencing of data is a feature of


Sequence Transmission Control Protocol (TCP). There is no sequencing of data in UDP. If
this means that packets arrive in order at the order is required, it has to be managed
the receiver. by the application layer.

Speed UDP is faster, simpler, and more efficient


TCP is comparatively slower than UDP. than TCP.

Retransmission Retransmission of lost packets is There is no retransmission of lost packets


possible in TCP, but not in UDP. in the User Datagram Protocol (UDP).

Header Length TCP has a (20-60) bytes variable length


header. UDP has an 8 bytes fixed-length header.

Weight TCP is heavy-weight. UDP is lightweight.


Basis Transmission control protocol (TCP) User datagram protocol (UDP)

Handshaking Uses handshakes such as SYN, ACK, It’s a connectionless protocol i.e. No
Techniques SYN-ACK handshake

Broadcasting TCP doesn’t support Broadcasting. UDP supports Broadcasting.

TCP is used by HTTP, HTTPs, FTP, UDP is used by DNS, DHCP, TFTP,
Protocols SMTP and Telnet. SNMP, RIP, and VoIP.

Stream Type The TCP connection is a byte stream. UDP connection is message stream.

Overhead Low but higher than UDP. Very low.


PRACTICAL 4

Write a program:
a. To implement echo server and client in java using TCP sockets.

EchoServer.java
import java.io.*;
import java.net.*;
public class EchoServer
{
public EchoServer(int portnum)
{
try
{
server = new ServerSocket(portnum);
}
catch (Exception err)
{
System.out.println(err);
}
}
public void serve()
{
try
{
while (true)
{
Socket client = server.accept();
BufferedReader r = new BufferedReader(new
InputStreamReader(client.getInputStream()));
PrintWriter w = new PrintWriter(client.getOutputStream(), true);
w.println("Welcome to the Java EchoServer. Type 'bye' to close.");
String line;
do
{
line = r.readLine();
if ( line != null )
w.println("Got: "+ line);
}
while ( !line.trim().equals("bye") );
client.close();
}
}
catch (Exception err)
{
System.err.println(err);
}
}
public static void main(String[] args)
{
EchoServer s = new EchoServer(9999);
s.serve();
}
private ServerSocket server;
}

b) Echo.Client.java
import java.io.*;
import java.net.*;
public class EchoClient
{
public static void main(String[] args)
{
try
{
Socket s = new Socket("127.0.0.1", 9999);
BufferedReader r = new BufferedReader(new
InputStreamReader(s.getInputStream()));
PrintWriter w = new PrintWriter(s.getOutputStream(), true);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
String line;
do
{
line = r.readLine();
if ( line != null )
System.out.println(line);
line = con.readLine();
w.println(line);
}
while ( !line.trim().equals("bye") );
}
catch (Exception err)
{
System.err.println(err);
}
}
}

b) To implement date server and client in java using TCP sockets.

Date Client

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

class DateClient
{
publicstaticvoid main(String args[]) throws Exception
{
Socket soc=new Socket(InetAddress.getLocalHost(),5217);
BufferedReader in=new BufferedReader(
new InputStreamReader(
soc.getInputStream()
)
);

System.out.println(in.readLine());
}
}

// Date Server
import java.net.*;
import java.io.*;
import java.util.*;

class DateServer
{
publicstaticvoid main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(5217);

while(true)
{
System.out.println("Waiting For Connection ...");
Socket soc=s.accept();
DataOutputStream out=new DataOutputStream(soc.getOutputStream());
out.writeBytes("Server Date" + (new Date()).toString() + "\n");
out.close();
soc.close();
}

}
}

c)To implement a chat server and client in java using TCP sockets

TCP CLIENT

//tcpclient.java

import java.io.*;

import java.net.*;

public class tcpclient

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

System.out.println(“TCP CLIENT”);

System.out.println(“Enter the host name to connect”);

DataInputStream inp=new DataInputStream(System.in);

String str=inp.readLine();

Socket clientsoc = new Socket(str, 9);

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


BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));

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

String userinput;

try

while (true)

System.out.println(“Sever Says : ” + in.readLine());

userinput = stdin.readLine();

out.println(userinput);

catch(Exception e)

System.exit(0);

TCP SERVER

//tcpserver.java

import java.io.*;

import java.net.*;

public class tcpserver

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

System.out.println(“TCP SERVER”);

System.out.println(“Server is ready to connect…”);


ServerSocket serversoc=new ServerSocket(9);

Socket clientsoc = serversoc.accept();

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

BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));

String inputline;

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

try

while (true)

inputline = stdin.readLine();

out.println(inputline);

System.out.println(“Client Says : “+in.readLine());

catch(Exception e)

System.exit(0);

Sample Output:

CLIENT-SERVER CHATTING USING TCP

*************************************

TCP SERVER

************

Server is ready to connect…

hello
Client Says : hello

How are you

Client Says : I’m doing programs

What programs

Client Says : networking

ok.Go ahead

Client Says : ok.Bye

Bye
PRACTICAL 5

TO IMPLEMENT SIMPLE CALCULATOR AND INVOKE ARITHMETIC OPERATIONS FROM


A REMOTE CLIENT

import java.io.*;

import java.net.*;

public class arithtcpclient

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

System.out.println();

System.out.println(“ARITHMETIC CLIENT”);

System.out.println(“*****************”);

System.out.println(“Enter the host name to connect”);

String str;

DataInputStream inp=new DataInputStream(System.in);

str=inp.readLine();

Socket clientsoc = new Socket(str, 9);

System.out.println(“Enter the inputs”);

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

BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));

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

String userinput;

try

while (true)

do

{
userinput = stdin.readLine();

out.println(userinput);

}while(!userinput.equals(“.”));

System.out.println(“Sever Says : ” + in.readLine());

catch(Exception e)

System.exit(0);

TCP SERVER

//arithtcpserver

import java.io.*;

import java.net.*;

public class arithtcpserver

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

System.out.println();

System.out.println(“ARITHMETIC SERVER”);

System.out.println(“*****************”);

System.out.println(“Server is ready to accept inputs…”);

ServerSocket serversoc=new ServerSocket(9);

Socket clientsoc = serversoc.accept();

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

BufferedReader in = new BufferedReader(new

InputStreamReader(clientsoc.getInputStream()));
String inputline;

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

try

while (true)

String s,op=””,st;

int i=0,c=0;

int[] a=new int[2];

while(true)

s=in.readLine();

if(s.equals(“+”) || s.equals(“-“) || s.equals(“*”) || s.equals(“/”))

op=s;

else if(s.equals(“.”))

break;

else

a[i]=Integer.parseInt(s);

i++;

if(op.equals(“+”))

c=a[0]+a[1];

else if(op.equals(“-“))

c=a[0]-a[1];

else if(op.equals(“*”))

c=a[0]*a[1];

else if(op.equals(“/”))
c=a[0]/a[1];

s=Integer.toString(c);

out.println(s);

catch(Exception e)

System.exit(0);

Sample Output:

SERVER SIDE

*************

C:\jdk1.5\bin>javac arithtcpserver.java

C:\jdk1.5\bin>java arithtcpserver

ARITHMETIC SERVER

*********************

Server is ready to accept inputs…

CLIENT SIDE

************

C:\JDK1.5\bin>javac arithtcpclient.java

C:\JDK1.5\bin>java arithtcpclient

ARITHMETIC CLIENT

********************

Enter the host name to connect

p4-221

Enter the inputs

8
+

Sever Says : 11

11

Sever Says : -2

Sever Says : 63

12

Sever Says : 4
PRACTICAL 6

To implement bubble sort and selection sort data using a remote client.

Client.java file will contain client panel. Here we are going to access services provided by the server.
To access the service, we are going take help of the interface.
Here it is SortInterface.java. and si is its object.

Client.java

package rmisort;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.Scanner;

public class Client


{
private static final long serialVersionUID = 1L;

public static void main(String[] args) throws MalformedURLException, RemoteException,


NotBoundException
{
SortInterface si=(SortInterface)Naming.lookup("rmi://127.0.0.1/SortingDemo");
Scanner sc=new Scanner(System.in);
int ch;
System.out.println("\n1:Bubble Sort\t2:Selection Sort\t3:Insertion Sort\nEnter your choice :");
ch=sc.nextInt();
switch(ch)
{
case 1:si.bubbleSort();break;
case 2:si.insertionSort();break;
case 3:si.selectionSort();break;
default: System.out.println("\nWrong Choice ...");
}
}
}

2.
Server contains the actual code of service.Here client is remote, hence he cant make a direct cal to methods
in the server.
Server implements the SortInterface.

Server.java

package rmisort;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Scanner;

public class Server extends UnicastRemoteObject implements SortInterface


{
/**
*
*/
private static final long serialVersionUID = 1L;
int array[]={9,8,7,6,5,4,3,2,1,0};
int n=10;
Scanner sc=new Scanner(System.in);
public Server() throws RemoteException
{
/*System.out.println("\nEnter 10 numbers : ");
for(int i=0;i<10;i++)
array[i]=sc.nextInt();*/

}
public void bubbleSort() throws RemoteException
{
int i, j,t=0;
for(i = 0; i < n; i++)
{
for(j = 1; j < (n-i); j++)
{
if(array[j-1] > array[j])
{
t = array[j-1];
array[j-1]=array[j];
array[j]=t;
}
}
}
}
public void selectionSort() throws RemoteException
{
for(int x=0; x<n; x++)
{
int index_of_min = x;
for(int y=x; y<n; y++){
if(array[index_of_min]<array[y])
{
index_of_min = y;
}
}
int temp = array[x];
array[x] = array[index_of_min];
array[index_of_min] = temp;
}

}
public void insertionSort() throws RemoteException
{

for (int i = 1; i < n; i++)


{
int j = i;
int B = array[i];
while ((j > 0) && (array[j-1] > B))
{
array[j] = array[j-1];
j--;
}
array[j] = B;
}
}

3.
ServiceDemo is used to bind client to the server.

ServiceDemo.java

package rmisort;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.RemoteException;

public class ServiceDemo


{

public static void main(String[] args) throws RemoteException, MalformedURLException


{
Server cs=new Server();
Naming.rebind("SortingDemo", cs);//publishing service

4. SortInterface is interface which provides service to client.

SortInterface.java

package rmisort;

import java.rmi.Remote;
import java.rmi.RemoteException;

public interface SortInterface extends Remote


{

public void bubbleSort()throws RemoteException;


public void selectionSort()throws RemoteException;
public void insertionSort()throws RemoteException;
}

How to run this program ?

Here you can create two bat files, one to run server, and other to run client .
Server.bat

cd g:
cd G:\sort

javac *.java
pause
rmic

start rmiregistry

java ServiceDemo

client.bat

cd g:
cd G:\sort

java Client
PRACTICAL 7
TO SIMULATE A SLIDING WINDOW PROTOCOL THAT USES GO BACK N ARQ.

/*Server Program*/

import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String args[]) throws Exception
{
ServerSocket server=new ServerSocket(6262);
System.out.println(“Server established.”);
Socket client=server.accept();
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
System.out.println(“Client is now connected.”);
int x=(Integer)ois.readObject();
int k=(Integer)ois.readObject();
int j=0;
int i=(Integer)ois.readObject();
boolean flag=true;
Random r=new Random(6);
int mod=r.nextInt(6);
while(mod==1||mod==0)
mod=r.nextInt(6);
while(true)
{
int c=k;
for(int h=0;h<=x;h++)
{
System.out.print(“|”+c+”|”);
c=(c+1)%x;
}
System.out.println();
System.out.println();
if(k==j)
{
System.out.println(“Frame “+k+” recieved”+”\n”+”Data:”+j);
j++;
System.out.println();
}

else
System.out.println(“Frames recieved not in correct order”+”\n”+” Expected farme:” + j +”\n”+ ” Recieved
frame no :”+ k);
System.out.println();
if(j%mod==0 && flag)
{
System.out.println(“Error found. Acknowledgement not sent. “);
flag=!flag;
j–;
}
else if(k==j-1)
{
oos.writeObject(k);
System.out.println(“Acknowledgement sent”);
}
System.out.println();
if(j%mod==0)
flag=!flag;
k=(Integer)ois.readObject();
if(k==-1)
break;
i=(Integer)ois.readObject();
}
System.out.println(“Client finished sending data. Exiting”);
oos.writeObject(-1);
}
}

/*Client Program*/

import java.util.*;
import java.net.*;
import java.io.*;
public class Client
{
public static void main(String args[]) throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter the value of m : “);
int m=Integer.parseInt(br.readLine());
int x=(int)((Math.pow(2,m))-1);
System.out.print(“Enter no. of frames to be sent:”);
int count=Integer.parseInt(br.readLine());
int data[]=new int[count];
int h=0;
for(int i=0;i<count;i++)
{
System.out.print(“Enter data for frame no ” +h+ ” => “);
data[i]=Integer.parseInt(br.readLine());
h=(h+1)%x;
}
Socket client=new Socket(“localhost”,6262);
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
System.out.println(“Connected with server.”);
boolean flag=false;
GoBackNListener listener=new GoBackNListener(ois,x);
listener=new GoBackNListener(ois,x);
listener.t.start();
int strt=0;
h=0;
oos.writeObject(x);
do
{
int c=h;
for(int i=h;i<count;i++)
{
System.out.print(“|”+c+”|”);
c=(c+1)%x;
}
System.out.println();
System.out.println();
h=strt;
for(int i=strt;i<x;i++)
{
System.out.println(“Sending frame:”+h);
h=(h+1)%x;
System.out.println();
oos.writeObject(i);
oos.writeObject(data[i]);
Thread.sleep(100);
}
listener.t.join(3500);
if(listener.reply!=x-1)
{
System.out.println(“No reply from server in 3.5 seconds. Resending data from frame no ” +
(listener.reply+1));
System.out.println();
strt=listener.reply+1;
flag=false;
}
else
{
System.out.println(“All elements sent successfully. Exiting”);
flag=true;
}
}while(!flag);
oos.writeObject(-1);
}
}

class GoBackNListener implements Runnable


{
Thread t;
ObjectInputStream ois;
int reply,x;
GoBackNListener(ObjectInputStream o,int i)
{
t=new Thread(this);
ois=o;
reply=-2;
x=i;
}
@Override
public void run() {
try
{
int temp=0;
while(reply!=-1)
{
reply=(Integer)ois.readObject();
if(reply!=-1 && reply!=temp+1)
reply=temp;
if(reply!=-1)
{
temp=reply;
System.out.println(“Acknowledgement of frame no ” + (reply%x) + ” recieved.”);
System.out.println();
}
}
reply=temp;
}
catch(Exception e)
{
System.out.println(“Exception => ” + e);
}
}
}

/*Client Output

Enter the value of m : 7


Enter no. of frames to be sent:5
Enter data for frame no 0 => 1
Enter data for frame no 1 => 2
Enter data for frame no 2 => 3
Enter data for frame no 3 => 4
Enter data for frame no 4 => 5
Connected with server.
|0||1||2||3||4|

Sending frame:0

Acknowledgement of frame no 0 recieved.

Sending frame:1

Sending frame:2

Sending frame:3

Sending frame:4

Sending frame:5
*/

/*Server Output
Server established.
Client is now connected.
|0||1||2||3||4||5||6||7||8||9||10||11||12||13||14||15||16||17||18||19||20||21||22||23||24||25||26||27||28||29||30||31||32||33||3
4||35||36||37||38||39||40||41||42||43||44||45||46||47||48||49||50||51||52||53||54||55||56||57||58||59||60||61||62||63||64||6
5||66||67||68||69||70||71||72||73||74||75||76||77||78||79||80||81||82||83||84||85||86||87||88||89||90||91||92||93||94||95||9
6||97||98||99||100||101||102||103||104||105||106||107||108||109||110||111||112||113||114||115||116||117||118||119||
120||121||122||123||124||125||126||0|

Frame 0 recieved
Data:0
Acknowledgement sent

|1||2||3||4||5||6||7||8||9||10||11||12||13||14||15||16||17||18||19||20||21||22||23||24||25||26||27||28||29||30||31||32||33||34||
35||36||37||38||39||40||41||42||43||44||45||46||47||48||49||50||51||52||53||54||55||56||57||58||59||60||61||62||63||64||65||
66||67||68||69||70||71||72||73||74||75||76||77||78||79||80||81||82||83||84||85||86||87||88||89||90||91||92||93||94||95||96||
97||98||99||100||101||102||103||104||105||106||107||108||109||110||111||112||113||114||115||116||117||118||119||12
0||121||122||123||124||125||126||0||1|

Frame 1 recieved
Data:1
Error found. Acknowledgement not sent.

|2||3||4||5||6||7||8||9||10||11||12||13||14||15||16||17||18||19||20||21||22||23||24||25||26||27||28||29||30||31||32||33||34||35
||36||37||38||39||40||41||42||43||44||45||46||47||48||49||50||51||52||53||54||55||56||57||58||59||60||61||62||63||64||65||66
||67||68||69||70||71||72||73||74||75||76||77||78||79||80||81||82||83||84||85||86||87||88||89||90||91||92||93||94||95||96||97
||98||99||100||101||102||103||104||105||106||107||108||109||110||111||112||113||114||115||116||117||118||119||120||
121||122||123||124||125||126||0||1||2|

Frames recieved not in correct order


Expected farme:1
Recieved frame no :2
|3||4||5||6||7||8||9||10||11||12||13||14||15||16||17||18||19||20||21||22||23||24||25||26||27||28||29||30||31||32||33||34||35||3
6||37||38||39||40||41||42||43||44||45||46||47||48||49||50||51||52||53||54||55||56||57||58||59||60||61||62||63||64||65||66||6
7||68||69||70||71||72||73||74||75||76||77||78||79||80||81||82||83||84||85||86||87||88||89||90||91||92||93||94||95||96||97||9
8||99||100||101||102||103||104||105||106||107||108||109||110||111||112||113||114||115||116||117||118||119||120||12
1||122||123||124||125||126||0||1||2||3|

Frames recieved not in correct order


Expected farme:1
Recieved frame no :3
|4||5||6||7||8||9||10||11||12||13||14||15||16||17||18||19||20||21||22||23||24||25||26||27||28||29||30||31||32||33||34||35||36||
37||38||39||40||41||42||43||44||45||46||47||48||49||50||51||52||53||54||55||56||57||58||59||60||61||62||63||64||65||66||67||
68||69||70||71||72||73||74||75||76||77||78||79||80||81||82||83||84||85||86||87||88||89||90||91||92||93||94||95||96||97||98||
99||100||101||102||103||104||105||106||107||108||109||110||111||112||113||114||115||116||117||118||119||120||121||
122||123||124||125||126||0||1||2||3||4|

Frames recieved not in correct order


Expected farme:1
Recieved frame no :4
*/
PRACTICAL 8

TO SNIFF AND PARSE PACKETS THAT PASS THROUGH USING RAW SOCKETS

Basic Sniffer using sockets


To code a very simply sniffer in C the steps would be

1. Create a raw socket.


2. Put it in a recvfrom loop and receive data on it.
A raw socket when put in recvfrom loop receives all incoming packets. This is because it is not bound to a
particular address or port.

1 sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);


2 while(1)
3 {
4 data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , &saddr_size);
5 }

Thats all. The buffer will hold the data sniffed or picked up. The sniffing part is actually complete over here.
The next task is to actually read the captured packet, analyse it and present it to the user in a readable
format.

The following code shows an example of such a sniffer. Note that it sniffs only incoming packets.

Code
#include<stdio.h> //For standard things
#include<stdlib.h> //malloc
#include<string.h> //memset
#include<netinet/ip_icmp.h> //Provides declarations for icmp header
#include<netinet/udp.h> //Provides declarations for udp header
#include<netinet/tcp.h> //Provides declarations for tcp header
#include<netinet/ip.h> //Provides declarations for ip header
#include<sys/socket.h>
#include<arpa/inet.h>

voidProcessPacket(unsigned char* , int);


voidprint_ip_header(unsigned char* , int);
voidprint_tcp_packet(unsigned char* , int);
voidprint_udp_packet(unsigned char* , int);
voidprint_icmp_packet(unsigned char* , int);
voidPrintData (unsigned char* , int);

intsock_raw;
FILE*logfile;
inttcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
structsockaddr_in source,dest;

intmain()
{
intsaddr_size , data_size;
structsockaddr saddr;
structin_addr in;

unsigned char*buffer = (unsigned char*)malloc(65536); //Its Big!

logfile=fopen("log.txt","w");
if(logfile==NULL) printf("Unable to create file.");
printf("Starting...\n");
//Create a raw socket that shall sniff
sock_raw = socket(AF_INET , SOCK_RAW , IPPROTO_TCP);
if(sock_raw < 0)
{
printf("Socket Error\n");
return1;
}
while(1)
{
saddr_size = sizeofsaddr;
//Receive a packet
data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , &saddr_size);
if(data_size <0 )
{
printf("Recvfrom error , failed to get packets\n");
return1;
}
//Now process the packet
ProcessPacket(buffer , data_size);
}
close(sock_raw);
printf("Finished");
return0;
}

voidProcessPacket(unsigned char* buffer, intsize)


{
//Get the IP Header part of this packet
structiphdr *iph = (structiphdr*)buffer;
++total;
switch(iph->protocol) //Check the Protocol and do accordingly...
{
case1: //ICMP Protocol
++icmp;
//PrintIcmpPacket(Buffer,Size);
break;

case2: //IGMP Protocol


++igmp;
break;

case6: //TCP Protocol


++tcp;
print_tcp_packet(buffer , size);
break;
case17: //UDP Protocol
++udp;
print_udp_packet(buffer , size);
break;

default: //Some Other Protocol like ARP etc.


++others;
break;
}
printf("TCP : %d UDP : %d ICMP : %d IGMP : %d Others : %d Total : %d\r",tcp,udp,icmp,igmp,others,t
}

voidprint_ip_header(unsigned char* Buffer, intSize)


{
unsigned shortiphdrlen;

structiphdr *iph = (structiphdr *)Buffer;


iphdrlen =iph->ihl*4;

memset(&source, 0, sizeof(source));
source.sin_addr.s_addr = iph->saddr;

memset(&dest, 0, sizeof(dest));
dest.sin_addr.s_addr = iph->daddr;

fprintf(logfile,"\n");
fprintf(logfile,"IP Header\n");
fprintf(logfile," |-IP Version : %d\n",(unsigned int)iph->version);
fprintf(logfile," |-IP Header Length : %d DWORDS or %d Bytes\n",(unsigned int)iph->ihl,((unsigned int)(iph-
fprintf(logfile," |-Type Of Service : %d\n",(unsigned int)iph->tos);
fprintf(logfile," |-IP Total Length : %d Bytes(Size of Packet)\n",ntohs(iph->tot_len));
fprintf(logfile," |-Identification : %d\n",ntohs(iph->id));
//fprintf(logfile," |-Reserved ZERO Field : %d\n",(unsigned int)iphdr->ip_reserved_zero);
//fprintf(logfile," |-Dont Fragment Field : %d\n",(unsigned int)iphdr->ip_dont_fragment);
//fprintf(logfile," |-More Fragment Field : %d\n",(unsigned int)iphdr->ip_more_fragment);
fprintf(logfile," |-TTL : %d\n",(unsigned int)iph->ttl);
fprintf(logfile," |-Protocol : %d\n",(unsigned int)iph->protocol);
fprintf(logfile," |-Checksum : %d\n",ntohs(iph->check));
fprintf(logfile," |-Source IP : %s\n",inet_ntoa(source.sin_addr));
fprintf(logfile," |-Destination IP : %s\n",inet_ntoa(dest.sin_addr));
}

voidprint_tcp_packet(unsigned char* Buffer, intSize)


{
unsigned shortiphdrlen;

structiphdr *iph = (structiphdr *)Buffer;


iphdrlen = iph->ihl*4;

structtcphdr *tcph=(structtcphdr*)(Buffer + iphdrlen);

fprintf(logfile,"\n\n***********************TCP Packet*************************\n");

print_ip_header(Buffer,Size);
fprintf(logfile,"\n");
fprintf(logfile,"TCP Header\n");
fprintf(logfile," |-Source Port : %u\n",ntohs(tcph->source));
fprintf(logfile," |-Destination Port : %u\n",ntohs(tcph->dest));
fprintf(logfile," |-Sequence Number : %u\n",ntohl(tcph->seq));
fprintf(logfile," |-Acknowledge Number : %u\n",ntohl(tcph->ack_seq));
fprintf(logfile," |-Header Length : %d DWORDS or %d BYTES\n",(unsigned int)tcph->doff,(unsigned int)tc
//fprintf(logfile," |-CWR Flag : %d\n",(unsigned int)tcph->cwr);
//fprintf(logfile," |-ECN Flag : %d\n",(unsigned int)tcph->ece);
fprintf(logfile," |-Urgent Flag : %d\n",(unsigned int)tcph->urg);
fprintf(logfile," |-Acknowledgement Flag : %d\n",(unsigned int)tcph->ack);
fprintf(logfile," |-Push Flag : %d\n",(unsigned int)tcph->psh);
fprintf(logfile," |-Reset Flag : %d\n",(unsigned int)tcph->rst);
fprintf(logfile," |-Synchronise Flag : %d\n",(unsigned int)tcph->syn);
fprintf(logfile," |-Finish Flag : %d\n",(unsigned int)tcph->fin);
fprintf(logfile," |-Window : %d\n",ntohs(tcph->window));
fprintf(logfile," |-Checksum : %d\n",ntohs(tcph->check));
fprintf(logfile," |-Urgent Pointer : %d\n",tcph->urg_ptr);
fprintf(logfile,"\n");
fprintf(logfile," DATA Dump ");
fprintf(logfile,"\n");

fprintf(logfile,"IP Header\n");
PrintData(Buffer,iphdrlen);

fprintf(logfile,"TCP Header\n");
PrintData(Buffer+iphdrlen,tcph->doff*4);

fprintf(logfile,"Data Payload\n");
PrintData(Buffer + iphdrlen + tcph->doff*4 , (Size - tcph->doff*4-iph->ihl*4) );

fprintf(logfile,"\n###########################################################");
}

voidprint_udp_packet(unsigned char*Buffer , intSize)


{

unsigned shortiphdrlen;

structiphdr *iph = (structiphdr *)Buffer;


iphdrlen = iph->ihl*4;

structudphdr *udph = (structudphdr*)(Buffer + iphdrlen);

fprintf(logfile,"\n\n***********************UDP Packet*************************\n");

print_ip_header(Buffer,Size);

fprintf(logfile,"\nUDP Header\n");
fprintf(logfile," |-Source Port : %d\n", ntohs(udph->source));
fprintf(logfile," |-Destination Port : %d\n", ntohs(udph->dest));
fprintf(logfile," |-UDP Length : %d\n", ntohs(udph->len));
fprintf(logfile," |-UDP Checksum : %d\n", ntohs(udph->check));

fprintf(logfile,"\n");
fprintf(logfile,"IP Header\n");
PrintData(Buffer , iphdrlen);

fprintf(logfile,"UDP Header\n");
PrintData(Buffer+iphdrlen , sizeofudph);

fprintf(logfile,"Data Payload\n");
PrintData(Buffer + iphdrlen + sizeofudph ,( Size - sizeofudph - iph->ihl * 4 ));

fprintf(logfile,"\n###########################################################");
}

voidprint_icmp_packet(unsigned char* Buffer , intSize)


{
unsigned shortiphdrlen;

structiphdr *iph = (structiphdr *)Buffer;


iphdrlen = iph->ihl*4;

structicmphdr *icmph = (structicmphdr *)(Buffer + iphdrlen);

fprintf(logfile,"\n\n***********************ICMP Packet*************************\n");

print_ip_header(Buffer , Size);

fprintf(logfile,"\n");

fprintf(logfile,"ICMP Header\n");
fprintf(logfile," |-Type : %d",(unsigned int)(icmph->type));

if((unsigned int)(icmph->type) == 11)


fprintf(logfile," (TTL Expired)\n");
elseif((unsigned int)(icmph->type) == ICMP_ECHOREPLY)
fprintf(logfile," (ICMP Echo Reply)\n");
fprintf(logfile," |-Code : %d\n",(unsigned int)(icmph->code));
fprintf(logfile," |-Checksum : %d\n",ntohs(icmph->checksum));
//fprintf(logfile," |-ID : %d\n",ntohs(icmph->id));
//fprintf(logfile," |-Sequence : %d\n",ntohs(icmph->sequence));
fprintf(logfile,"\n");

fprintf(logfile,"IP Header\n");
PrintData(Buffer,iphdrlen);

fprintf(logfile,"UDP Header\n");
PrintData(Buffer + iphdrlen , sizeoficmph);

fprintf(logfile,"Data Payload\n");
PrintData(Buffer + iphdrlen + sizeoficmph , (Size - sizeoficmph - iph->ihl * 4));

fprintf(logfile,"\n###########################################################");
}

voidPrintData (unsigned char* data , intSize)


{
for(i=0 ; i < Size ; i++)
{
if( i!=0 && i%16==0) //if one line of hex printing is complete...
{
fprintf(logfile," ");
for(j=i-16 ; j<i ; j++)
{
if(data[j]>=32 && data[j]<=128)
fprintf(logfile,"%c",(unsigned char)data[j]); //if its a number or alphabet

elsefprintf(logfile,"."); //otherwise print a dot


}
fprintf(logfile,"\n");
}

if(i%16==0) fprintf(logfile," ");


fprintf(logfile," %02X",(unsigned int)data[i]);

if( i==Size-1) //print the last spaces


{
for(j=0;j<15-i%16;j++) fprintf(logfile," "); //extra spaces

fprintf(logfile," ");

for(j=i-i%16 ; j<=i ; j++)


{
if(data[j]>=32 && data[j]<=128) fprintf(logfile,"%c",(unsigned char)data[j]);
elsefprintf(logfile,".");
}
fprintf(logfile,"\n");
}
}
}

Compile and Run


$ gcc sniffer.c && sudo ./a.out
The program must be run as root user or superuser privileges. e.g. sudo ./a.out in ubuntu
The program creates raw sockets which require root access.
The output in the log file is something like this :

***********************TCP Packet*************************

IP Header
|-IP Version :4
|-IP Header Length : 5 DWORDS or 20 Bytes
|-Type Of Service : 32
|-IP Total Length : 137 Bytes(Size of Packet)
|-Identification : 35640
|-TTL : 51
|-Protocol : 6
|-Checksum : 54397
|-Source IP : 174.143.119.91
|-Destination IP : 192.168.1.6

TCP Header
|-Source Port : 6667
|-Destination Port : 38265
|-Sequence Number : 1237278529
|-Acknowledge Number : 65363511
|-Header Length : 5 DWORDS or 20 BYTES
|-Urgent Flag :0
|-Acknowledgement Flag : 1
|-Push Flag :1
|-Reset Flag :0
|-Synchronise Flag : 0
|-Finish Flag :0
|-Window : 9648
|-Checksum : 46727
|-Urgent Pointer : 0

DATA Dump
IP Header
45 20 00 89 8B 38 40 00 33 06 D4 7D AE 8F 77 5B E ...8@.3..}..w[
C0 A8 01 06 ....
TCP Header
1A 0B 95 79 49 BF 5F 41 03 E5 5E 37 50 18 25 B0 ...yI._A..^7P.%.
B6 87 00 00 ....
Data Payload
3A 6B 61 74 65 60 21 7E 6B 61 74 65 40 75 6E 61 :kate`!~kate@una
66 66 69 6C 69 61 74 65 64 2F 6B 61 74 65 2F 78 ffiliated/kate/x
2D 30 30 30 30 30 30 31 20 50 52 49 56 4D 53 47 -0000001 PRIVMSG
20 23 23 63 20 3A 69 20 6E 65 65 64 20 65 78 61 ##c :i need exa
63 74 6C 79 20 74 68 65 20 72 69 67 68 74 20 6E ctly the right n
75 6D 62 65 72 20 6F 66 20 73 6F 63 6B 73 21 0D umber of socks!.
0A .

###########################################################

***********************TCP Packet*************************

IP Header
|-IP Version :4
|-IP Header Length : 5 DWORDS or 20 Bytes
|-Type Of Service : 32
|-IP Total Length : 186 Bytes(Size of Packet)
|-Identification : 56556
|-TTL : 48
|-Protocol : 6
|-Checksum : 22899
|-Source IP : 74.125.71.147
|-Destination IP : 192.168.1.6

TCP Header
|-Source Port : 80
|-Destination Port : 49374
|-Sequence Number : 3136045905
|-Acknowledge Number : 2488580377
|-Header Length : 5 DWORDS or 20 BYTES
|-Urgent Flag :0
|-Acknowledgement Flag : 1
|-Push Flag :1
|-Reset Flag :0
|-Synchronise Flag : 0
|-Finish Flag :0
|-Window : 44765
|-Checksum : 15078
|-Urgent Pointer : 0

DATA Dump
IP Header
45 20 00 BA DC EC 00 00 30 06 59 73 4A 7D 47 93 E ......0.YsJ}G.
C0 A8 01 06 ....
TCP Header
00 50 C0 DE BA EC 43 51 94 54 B9 19 50 18 AE DD .P....CQ.T..P...
3A E6 00 00 :...
Data Payload
48 54 54 50 2F 31 2E 31 20 33 30 34 20 4E 6F 74 HTTP/1.1 304 Not
20 4D 6F 64 69 66 69 65 64 0D 0A 58 2D 43 6F 6E Modified..X-Con
74 65 6E 74 2D 54 79 70 65 2D 4F 70 74 69 6F 6E tent-Type-Option
73 3A 20 6E 6F 73 6E 69 66 66 0D 0A 44 61 74 65 s: nosniff..Date
3A 20 54 68 75 2C 20 30 31 20 44 65 63 20 32 30 : Thu, 01 Dec 20
31 31 20 31 33 3A 31 36 3A 34 30 20 47 4D 54 0D 11 13:16:40 GMT.
0A 53 65 72 76 65 72 3A 20 73 66 66 65 0D 0A 58 .Server: sffe..X
2D 58 53 53 2D 50 72 6F 74 65 63 74 69 6F 6E 3A -XSS-Protection:
20 31 3B 20 6D 6F 64 65 3D 62 6C 6F 63 6B 0D 0A 1; mode=block..
0D 0A ..

###########################################################

You might also like