Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 41

RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Study of Networking Commands

AIM:

To learn to use commands like tcpdump, netstat, ifconfig, nslookup and traceroute ping.

PRE LAB DISCUSSION:

Tcpdump:
The tcpdump utility allows you to capture packets that flow within your network to assist in
network troubleshooting. The following are several examples of using tcpdump with different
options. Traffic is captured based on a specified filter.

Netstat
Netstat is a common command line TCP/IP networking available in most versions of
Windows, Linux, UNIX and other operating systems. Netstat provides information and
statistics about protocols in use and current TCP/IP network connections.

ipconfig
ipconfig is a console application designed to run from the Windows command prompt. This
utility allows you to get the IP address information of a Windows computer. From the
command prompt, type ipconfig to run the utility with default options. The output of the
default command contains the IP address, network mask, and gateway for all physical and
virtual
network adapter.

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

Trace route:
Traceroute is a network diagnostic tool used to track the pathway taken by a packet on an IP
network from source to destination. Traceroute also records the time taken for each hop the
packet makes during its route to the destination

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

COMMANDS & OUTPUT:

Netstat
Netstat is a common command line TCP/IP networking available in most versions of
Windows, Linux, UNIX and other operating systems. Netstat provides information and
statistics about protocols in use and current TCP/IP network connections. The Windows help
screen (analogous to a Linux or UNIX for netstat reads as follows:

displays protocol statistics and current TCP/IP network connections.

#netstat

OUTPUT:

ipconfig
In Windows, ipconfig is a console application designed to run from the Windows command
prompt. This utility allows you to get the IP address information of a Windows computer.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Using ipconfig

From the command prompt, type ipconfig to run the utility with default options. The output
of the default command contains the IP address, network mask, and gateway for all physical
and virtual network adapter.

#ipconfig

OUTPUT:

nslookup

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

The nslookup command is a powerful tool for diagnosing DNS problems. You know you're
experiencing a DNS problem when you can access a resource by specifying its IP address but
not its DNS name.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

#nslookup

OUTPUT:

Ping:

The ping command sends an echo request to a host available on the network. Using this
command, you can check if your remote host is responding well or not. Tracking and isolating
hardware and software problems. Determining the status of the network and various foreign
hosts. The ping command is usually used as a simple way to verify that a computer can
communicate over the network with another computer or network device. The ping command
operates by sending Internet Control Message Protocol (ICMP) Echo Request messages to the
destination computer and waiting for a response

# ping172.16.6.2

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

OUTPUT:

RESULT:

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

PRE-LAB DISCUSSION

IP Address
An IP address is a unique address that identifies a device on the internet or a local network. IP
stands for "Internet Protocol," which is the set of rules governing the format of data sent via
the internet or local network.

An IP address is a string of numbers separated by periods. IP addresses are expressed as a set


of four numbers — an example address might be 192.158.1.38. Each number in the set can
range from 0 to 255. So, the full IP addressing range goes from 0.0.0.0 to 255.255.255.255.

SOURCE CODE

// Display the IP Address of the System


import java.io.*;
import java.net.*;
class DisplayIP
{
public InetAddress ip;
public static void main(String args[])throws UnknownHostException
{
InetAddress ip=InetAddress.getLocalHost();
System.out.println("\nIP address is :"+ip);
String s1=ip.getHostName();
System.out.println("System Number is:"+s1);
}
}

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

PRE-LAB DISCUSSION

Transmission Modes in Computer Networks


(Simplex, Half-Duplex and Full-Duplex)

Transmission mode means transferring of data between two devices. It is also known as
communication mode. Buses and networks are designed to allow communication to occur
between individual devices that are interconnected. There are three types of transmission
mode:-

These are explained as following below.


1. Simplex Mode

In Simplex mode, the communication is unidirectional, as on a one-way street. Only one of


the two devices on a link can transmit, the other can only receive. The simplex mode can
use the entire capacity of the channel to send data in one direction.
Example: Keyboard and traditional monitors. The keyboard can only introduce input, the
monitor can only give the output.

2. Half-Duplex Mode

In half-duplex mode, each station can both transmit and receive, but not at the same time.
When one device is sending, the other can only receive, and vice versa. The half-duplex
mode is used in cases where there is no need for communication in both direction at the
same time. The entire capacity of the channel can be utilized for each direction.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Example: Walkie- talkie in which message is sent one at a time and messages are sent in
both the directions.

Channel capacity=Bandwidth * Propagation Delay

3. Full-Duplex Mode

In full-duplex mode, both stations can transmit and receive simultaneously. In full_duplex
mode, signals going in one direction share the capacity of the link with signals going in
other direction, this sharing can occur in two ways:
 Either the link must contain two physically separate transmission paths, one for sending
and other for receiving.
 Or the capacity is divided between signals travelling in both directions.

Full-duplex mode is used when communication in both direction is required all the time.
The capacity of the channel, however must be divided between the two directions.
Example: Telephone Network in which there is communication between two persons by a
telephone line, through which both can talk and listen at the same time.
Channel Capacity=2* Bandwidth*propagation Delay

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Java DatagramSocket and DatagramPacket


Java DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
Java DatagramSocket class
Java DatagramSocket class represents a connection-less socket for sending and receiving
datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or
arrival time.
Commonly used Constructors of DatagramSocket class
o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it
with the available Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and
binds it with the given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates
a datagram socket and binds it with the specified port number and host address.

Java DatagramPacket class


Java DatagramPacket is a message that can be sent or received. If you send multiple packet,
it may arrive in any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This
constructor is used to receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates
a datagram packet. This constructor is used to send the packets.

SOURCE CODE

// Factorial of a Number – CLIENT

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

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

public class FactClient {


public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
String str="";
System.out.println("\n Enter the Number...");
str=br.readLine();
dout.writeUTF(str);
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}

// Factorial of a Number – SERVER

import java.io.*;
import java.net.*;
public class FactServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
int num,i,fact=1;
num=Integer.parseInt(str);
for(i=1;i<=num;i++)
fact=fact*i;
System.out.println("\n Factorial of "+num+" is "+fact);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

PRE-LAB DISCUSSION

Transmission Modes in Computer Networks

(Simplex, Half-Duplex and Full-Duplex)

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Transmission mode means transferring of data between two devices. It is also known as
communication mode. Buses and networks are designed to allow communication to occur
between individual devices that are interconnected.

Half-Duplex Mode

In half-duplex mode, each station can both transmit and receive, but not at the same time.
When one device is sending, the other can only receive, and vice versa. The half-duplex
mode is used in cases where there is no need for communication in both direction at the
same time. The entire capacity of the channel can be utilized for each direction.
Example: Walkie- talkie in which message is sent one at a time and messages are sent in
both the directions.

Channel capacity=Bandwidth * Propagation Delay

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.
The client in socket programming must know two information:

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

1. IP Address of Server, and


2. Port number.
Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, server reads the message and prints it. Here, two classes
are being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at
server-side.

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Method Description

1) public InputStream returns the InputStream attached with this socket.


getInputStream()

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

2) public OutputStream returns the OutputStream attached with this socket.


getOutputStream()

3) public synchronized void closes this socket


close()

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection


between server and client.

2) public synchronized void closes the server socket.


close()

SOURCE CODE

// One Way Communication – CLIENT

import java.net.*;
import java.io.*;
public class rclient{
public static void main(String args[]) {
Socket servsoc=null;
BufferedReader in=null;
BufferedReader key=null;
PrintStream out=null;
String str=null;
String skey=null;
try{
InetAddress address=InetAddress.getLocalHost();
System.out.println(address);

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

servsoc=new Socket(address,3500);
in=new BufferedReader(new InputStreamReader(servsoc.getInputStream()));
out=new PrintStream(servsoc.getOutputStream());
key=new BufferedReader(new InputStreamReader(System.in));
str=in.readLine();
System.out.println("client from server"+str);
System.out.println("Enter the message <End- to Quit>");
while(true) {
skey=key.readLine();
out.println(skey);
in=new BufferedReader(new InputStreamReader(servsoc.getInputStream()));
str=in.readLine();
System.out.println("From server : "+str);
out.println("ok");
String s2="End";
if(skey.equals(s2))
break;
}
}
catch(Exception e){System.out.println("connection is not properly");}
}
}

// One Way Communication – SERVER

import java.net.*;
import java.io.*;
public class rserver {
ServerSocket server=null;
Socket clientserver=null;
Thread ServerThread;
PrintStream out;
BufferedReader in;
String strs;
public rserver() {
try{
server=new ServerSocket(3500);
clientserver=server.accept();
System.out.println("server-client connnection is established");
out=new PrintStream(clientserver.getOutputStream());
out.println(" welcome");

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

out.println("Type <Quit> to end");


while(true) {
in=new BufferedReader(new InputStreamReader(clientserver.getInputStream()));
strs=in.readLine();
System.out.println("server,from client : "+strs);
out.println("information is received");
String s2="Quit";
if(strs.equals(s2))
break; }
}
catch (Exception e) { System.out.println(e); }
}
public static void main(String args[]) {
new rserver(); }
}

PRE-LAB DISCUSSION

Transmission Modes in Computer Networks


(Simplex, Half-Duplex and Full-Duplex)

Transmission mode means transferring of data between two devices. It is also known as
communication mode. Buses and networks are designed to allow communication to occur
between individual devices that are interconnected.

Full-Duplex Mode

In full-duplex mode, both stations can transmit and receive simultaneously. In full_duplex
mode, signals going in one direction share the capacity of the link with signals going in
other direction, this sharing can occur in two ways:
 Either the link must contain two physically separate transmission paths, one for sending
and other for receiving.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

 Or the capacity is divided between signals travelling in both directions.

Full-duplex mode is used when communication in both direction is required all the time.
The capacity of the channel, however must be divided between the two directions.
Example: Telephone Network in which there is communication between two persons by a
telephone line, through which both can talk and listen at the same time.
Channel Capacity=2* Bandwidth*propagation Delay

Java Socket Programming


Java Socket programming is used for communication between the applications running on
different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket
programming.

The client in socket programming must know two information:


1. IP Address of Server, and
2. Port number.

Here, we are going to make one-way client and server communication. In this application,
client sends a message to the server, server reads the message and prints it. Here, two classes
are being used: Socket and ServerSocket. The Socket class is used to communicate client and
server. Through this class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console until the client is
connected. After the successful connection of client, it returns the instance of Socket at
server-side.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class
can be used to create a socket.
Important methods
Method Description

1) public InputStream returns the InputStream attached with this socket.


getInputStream()

2) public OutputStream returns the OutputStream attached with this socket.


getOutputStream()

3) public synchronized void closes this socket

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

close()

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods
Method Description

1) public Socket accept() returns the socket and establish a connection


between server and client.

2) public synchronized void closes the server socket.


close()

SOURCE CODE

// TWO Way Communication – CLIENT

import java.net.*;
import java.io.*;
class TClient{
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")){
System.out.println("Enter your Message... (stop)");
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

}
}

// TWO Way Communication – SERVER

import java.net.*;
import java.io.*;
class TServer{
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);
System.out.println("Enter your Message...(stop)");
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

}
}

PRE-LAB DISCUSSION

Data is transported over a network by three simple methods i.e. Unicast, Broadcast, and
Multicast. So let’s begin to summarize the difference between these three:
 Unicast: from one source to one destination i.e. One-to-One
 Broadcast: from one source to all possible destinations i.e. One-to-All
 Multicast: from one source to multiple destinations stating an interest in receiving the
traffic i.e. One-to-Many

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

So let’s Dig Deeper into this subject

Unicast: traffic, many streams of IP packets that move across networks flow from a single
point, such as a website server, to a single endpoint such as a client PC. This is the most
common form of information transference on networks.
Broadcast: Here, traffic streams from a single point to all possible endpoints within reach on
the network, which is generally a LAN. This is the easiest technique to ensure traffic reaches
its destinations.

This mode is mainly utilized by television networks for video and audio distribution. Even if
the television network is a cable television (CATV) system, the source signal reaches all
possible destinations, which is the key reason that some channels’ content is scrambled.
Broadcasting is not practicable on the public Internet due to the massive amount of
unnecessary data that would continually reach each user’s device, the complications and
impact of scrambling, and related privacy issues.

Multicast: In this method traffic recline between the boundaries of unicast (one point to one
destination) and broadcast (one point to all destinations). And multicast is a “one source to
many destinations” way of traffic distribution, which means that only the destinations that
openly point to their requisite to accept the data from a specific source to receive the traffic
stream.

On an IP network, destinations (i.e. clients) do not regularly communicate straight to sources


(i.e. servers), because the routers between source and destination must be able to regulate the
topology of the network from unicast or multicast side to avoid disordered routing traffic.
Multicast routers replicate packets received on one input interface and send the replicas out on
multiple output interfaces.

In the multicast model, the source and destinations are almost every time “Host” and not
“Routers”. The multicast traffic is spread by multicast routers across the network from source
to destination. The multicast routers must find multicast sources on the network, send out
copies of packets on a number of interfaces, avoid loops, connect interested destinations with

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

accurate sources and keep the flow of unsolicited packets to a minimum. The standard
protocols of multicast routing provide most of these facilities, but some router architecture
cannot send multiple copies of packets and so do not support direct multicasting.

Multicasting can be used to push data to multiple hosts simultaneously.


Characteristics of multicasting are as follows:

 Designed to handle traffic destined to multiple hosts.


 Multicast traffic establishes a one-to-many type of transmission, sending one
stream of traffic to each requesting broadcast domain.
 The IP address that defines a multicast group is a Class D address (224.0.0.0 to
239.255.255.255).
 Multicast addresses cannot be used as source addresses for any traffic.
 A multicast address identifies a group of hosts sharing the same address.
 Multicast addresses are not assigned to a device, rather, a device proceeds to
listen for and receive traffic destined to a multicast group that it has joined by
some process.
 Multicasting is UDP-based.
 A computer uses Internet Group Management Protocol (IGMP) to report its
multicast group memberships to multicast routers.
 IGMP is required to be used in host computers that wish to participate in
multicasting.

Unicast traffic is the transmission of data from one host to another, one host at a time.
Characteristics of unicast traffic are as follows:

 A one-to-one session between one host and another, such as a client and server
arrangement.
 It will not transmit to every computer on a network.
 Multiple requests for the same conference or data would cause that data to be
pushed across the network media at the same time to multiple targets.

Broadcast traffic is the broadcast traffic sent to all computer systems that can be
reached on the network. Characteristics of broadcast traffic are as follows:

 Each host receiving the broadcast has to process the broadcast traffic.
 If a host does not require the broadcast traffic data, the host will still accept the
datagram and then determine what to do with it – accept it or reject it.
 Routers filter (block) broadcast traffic by default. Broadcasts must be explicitly
allowed to traverse routers.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

SOURCE CODE

//Multicasting - CLIENT

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
public class MulticastSocketClient {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException {
// Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(INET_ADDR);
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256];

// Create a new Multicast socket (that will allow other sockets/programs


// to join it as well.
try (MulticastSocket clientSocket = new MulticastSocket(PORT)){
//Joint the Multicast group.
clientSocket.joinGroup(address);
while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
clientSocket.receive(msgPacket);
String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg);
}
}

catch (IOException ex) {


ex.printStackTrace();
}
}
}

//Multicasting - SERVER

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

import java.net.UnknownHostException;
public class MulticastSocketServer {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
public static void main(String[] args) throws UnknownHostException,
InterruptedException {
// Get the address that we are going to connect to.
InetAddress addr = InetAddress.getByName(INET_ADDR);
// Open a new DatagramSocket, which will be used to send the data.
try (DatagramSocket serverSocket = new DatagramSocket()) {
for (int i = 0; i < 5; i++) {
String msg = "Sent message no " + i;
// Create a packet that will contain the data
// (in the form of bytes) and send it.
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket);
System.out.println("Server sent packet with msg: " + msg);
Thread.sleep(500);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

SOURCE CODE

// Filer Sharing using Socket - SERVER

import java.io.*;
import java.net.*;
public class FileServer {
public static void main(String args[])throws IOException
{
ServerSocket ss=null;
try
{

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

ss=new ServerSocket(8081);
}
catch(IOException e)
{
System.out.println("couldn't listen");
System.exit(0);
}
Socket cs=null;
try
{
cs=ss.accept();
System.out.println("Connection established"+cs);
}
catch(Exception e)
{
System.out.println("Accept failed");
System.exit(1);
}
PrintWriter put=new PrintWriter(cs.getOutputStream(),true);
BufferedReader st=new BufferedReader(new InputStreamReader(cs.getInputStream()));
String s=st.readLine();
System.out.println("The requested file is : "+s);
File f=new File(s);
if(f.exists())
{
BufferedReader d=new BufferedReader(new FileReader(s));
String line;
while((line=d.readLine())!=null)
{
put.write(line);
put.flush();
}
d.close();
System.out.println("File transfered");
cs.close();
ss.close();
}
}
}

// Filer Sharing using Socket - CLIENT

import java.net.*;
import java.io.*;
class MyClient {
public static void main(String srgs[])throws IOException

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

{
Socket s=null;
BufferedReader get=null;
PrintWriter put=null;
try
{
s=new Socket("127.0.0.1",8081);
get=new BufferedReader(new InputStreamReader(s.getInputStream()));
put=new PrintWriter(s.getOutputStream(),true);
}
catch(Exception e)
{
System.exit(0);
}

String u,f;
System.out.println("Enter the file name to transfer from server:");
DataInputStream dis=new DataInputStream(System.in);
f=dis.readLine();
put.println(f);
File f1=new File("output.doc");
FileOutputStream fs=new FileOutputStream(f1);
while((u=get.readLine())!=null)
{
byte jj[]=u.getBytes();
fs.write(jj);
}
fs.close();
System.out.println("File received");
s.close();
}
}

PRE-LAB DISCUSSION

Substitution cipher technique and Transposition cipher technique are the types of
Traditional cipher which are used to convert the plain text into cipher text.

Substitution Cipher Technique:


In Substitution Cipher Technique plain text characters are replaced with other characters,
numbers and symbols as well as in substitution Cipher Technique, character’s identity is
changed while its position remains unchanged.

Transposition Cipher Technique:


Transposition Cipher Technique rearranges the position of the plain text’s characters. In

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

transposition Cipher Technique, The position of the character is changed but character’s
identity is not changed.

RSA Algorithm
RSA algorithm is a public key encryption technique and is considered as the most secure
way of encryption. It was invented by Rivest, Shamir and Adleman in year 1978 and hence
name RSA algorithm.
Algorithm
The RSA algorithm holds the following features −
 RSA algorithm is a popular exponentiation in a finite field over integers including
prime numbers.
 The integers used by this method are sufficiently large making it difficult to solve.
 There are two sets of keys in this algorithm: private key and public key.

You will have to go through the following steps to work on RSA algorithm −
Step 1: Generate the RSA modulus
The initial procedure begins with selection of two prime numbers namely p and q, and then
calculating their product N, as shown −
N=p*q
Here, let N be the specified large number.
Step 2: Derived Number (e)
Consider number e as a derived number which should be greater than 1 and less than (p-1)
and (q-1). The primary condition will be that there should be no common factor of (p-1) and
(q-1) except 1
Step 3: Public key
The specified pair of numbers n and e forms the RSA public key and it is made public.

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

Step 4: Private Key


Private Key d is calculated from the numbers p, q and e. The mathematical relationship
between the numbers is as follows −
ed = 1 mod (p-1) (q-1)
The above formula is the basic formula for Extended Euclidean Algorithm, which takes p
and q as the input parameters.

Encryption Formula
Consider a sender who sends the plain text message to someone whose public key
is (n,e). To encrypt the plain text message in the given scenario, use the following syntax −
C = Pe mod n

Decryption Formula
The decryption process is very straightforward and includes analytics for calculation in a
systematic approach. Considering receiver C has the private key d, the result modulus will
be calculated as −
Plaintext = Cd mod n

SOURCE CODE

//CRYPTING with SUBSTITUTION Using RSA Algorithm

import java.io.*;
import java.net.*;
public class SCrypt
{ public static void main(String arg[]) throws Exception
{ double tot,p,q,d,z,e;
String str=new String();
DatagramSocket ds;
DatagramPacket dp;
BufferedReader br;

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

byte bu[]=new byte[10240];


int len;
int tonum[]=new int[100];
double tochar[]=new double[100];
char tostring[]=new char[100];
p=13;q=5;tot=p*q;z=(p-1)*(q-1);
d=7;e=7;
///////encrypting//////
while(true){
System.out.println("Enter the Data.....");
br=new BufferedReader(new InputStreamReader(System.in));
str=br.readLine();
len=str.length();
for (int j=0;j<len ;j++ )
{
///decoding
if(str.charAt(j)==' ')tonum[j]=63;
if(str.charAt(j)>=65 &&str.charAt(j)<=90)
tonum[j]=str.charAt(j)-54;
if(str.charAt(j)>=97 &&str.charAt(j)<=122)
tonum[j]=str.charAt(j)-60;
if(str.charAt(j)>=48 &&str.charAt(j)<=57)
tonum[j]=str.charAt(j)-47;
if(str.charAt(j)=='.')tonum[j]=64;
////////////decoding
tochar[j]=(Math.pow(tonum[j],e))%tot;
tostring[j]=(char)(tochar[j]+60);
}
String info=new String(tostring,0,len);
bu=info.getBytes();
try{
ds=new DatagramSocket();
dp=new DatagramPacket(bu,bu.length,InetAddress.getLocalHost(),5000);
ds.send(dp);
if (str.equals("Exit")) break;
System.out.println("Message Encrypted : "+info);
}
catch(Exception eee){System.out.println(eee);}
}
}
}

//DECRYPTING with SUBSTITUTION Using RSA Algorithm

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

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

public class SDecrypt


{
public static void main(String args[])throws Exception
{
DatagramSocket ds;
DatagramPacket dp;
double tot,p,q,d,z,e;
String str=new String();
byte bu[]=new byte[10240];
BufferedReader br;
double tonum[]=new double[100];
char tochar[]=new char[100];
int din[]=new int[100];
ds=new DatagramSocket(5000);
dp=new DatagramPacket(bu,bu.length);
p=13;q=5;tot=p*q;z=(p-1)*(q-1);
d=7;e=7;
while(true){
bu=new byte[10240];
dp=new DatagramPacket(bu,bu.length);
ds.receive(dp);
String ne=new String(dp.getData()).trim();
int dlen=ne.length();
for(int j=0;j<dlen;j++)
{
din[j]=(ne.charAt(j)-60);
tonum[j]=(Math.pow(din[j],d))%tot;
///decode
if(tonum[j]==63)tochar[j]=' ';
if(tonum[j]>=11 &&tonum[j]<=36)
tochar[j]=(char)(tonum[j]+54);
if(tonum[j]>=37 &&tonum[j]<=62)
tochar[j]=(char)(tonum[j]+60);
if(tonum[j]>=1 &&tonum[j]<=10)
tochar[j]=(char)(tonum[j]+47);
if(tonum[j]==64)tochar[j]='.';
////////////decode
}
String info=new String(tochar,0,dlen);
System.out.println("Decrypted message : "+info);
if (info.equals("Exit")) break;
}
}
}

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

SOURCE CODE

// Image Transfer using Socket – CLIENT

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;
public class IClient {
public static void main(String args[]) throws Exception {
Socket soc;

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

BufferedImage img = null;


soc=new
Socket("localhost",4000);
System.out.println("Client is running.");
try {
System.out.println("Reading image from disk. ");
img = ImageIO.read(new File("scan1.jpg"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
byte[] bytes = baos.toByteArray(); baos.close();
System.out.println("Sending image to server.");
OutputStream out = soc.getOutputStream();
DataOutputStream dos = new DataOutputStream(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();
}
}

// Image Transfer using Socket – SERVER

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


import java.awt.image.*; import javax.imageio.*;
import javax.swing.*;
class IServer
{
public static void main(String args[]) throws Exception
{
ServerSocket server=null;
Socket socket;
server=new ServerSocket(4000);
System.out.println("Server Waiting for image");

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

socket=server.accept(); System.out.println("Client connected.");


InputStream in = socket.getInputStream();
DataInputStream dis = new DataInputStream(in);
int len = dis.readInt();
System.out.println("Image Size: " + len/1024 + "KB"); byte[] data = new byte[len];
dis.readFully(data);
dis.close();
in.close();
InputStream ian = new ByteArrayInputStream(data);
BufferedImage bImage = ImageIO.read(ian);
JFrame f = new JFrame("Server");
ImageIcon icon = new ImageIcon(bImage);
JLabel l = new JLabel();
l.setIcon(icon);
f.add(l);
f.pack();
f.setVisible(true);
}
}

SOURCE CODE

// One-way Communication using Swing - CLIENT

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Clientd extends JFrame implements ActionListener {
private JTextField enter;
private JTextArea display;
private DatagramPacket sendPacket, receivePacket;
private DatagramSocket socket;

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

public Clientd() {
super("Clientd");
enter= new JTextField ("Type message here");
enter.addActionListener(this);
getContentPane().add(enter,BorderLayout.NORTH);
display=new JTextArea();
getContentPane().add(new JScrollPane(display),BorderLayout.CENTER);
setSize(400,300);
show();
try
{ socket=new DatagramSocket(); }
catch(SocketException se)
{ se.printStackTrace(); System.exit(1); } }

public void waitForPackets() {


while (true) {
try {
byte data[] = new byte[100];
receivePacket = new DatagramPacket(data,data.length);
socket.receive(receivePacket);
display.append("\nPacket received: " +
"\nFrom Host : " + receivePacket.getAddress() +
"\nHost port : " + receivePacket.getPort() +
"\nLength : " + receivePacket.getLength() +
"\nContaing : \n\t" +
new String (receivePacket.getData(),0,receivePacket.getLength() ) );
display.setCaretPosition(display.getText().length());
}
catch (IOException exception) {
display.append(exception.toString()+ "\n");
exception.printStackTrace();
} } }
public void actionPerformed(ActionEvent e) {
try {
display.append("\nSending packet containing: " + e.getActionCommand() +
"\n");
String s= e.getActionCommand();
byte data[]=s.getBytes();
sendPacket=new DatagramPacket(data,data.length,
InetAddress.getLocalHost(),5000);
socket.send(sendPacket);
display.append("\n Packet sent \n");
display.setCaretPosition(display.getText().length());
}
catch(IOException exception) {
display.append(exception.toString() + "\n");
exception.printStackTrace();

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

}
}
public static void main(String args[]) {
Clientd app= new Clientd();
app.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0); }
}
);
app.waitForPackets(); }
}

// One-way Communication using Swing - SERVER

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Serverd extends JFrame {
private JTextArea display;
private DatagramPacket sendPacket, receivePacket;
private DatagramSocket socket;
public Serverd() {
super("Serverd");
display=new JTextArea();
getContentPane().add(new JScrollPane(display),BorderLayout.CENTER);
setSize(400,300);
show();

try {
socket=new DatagramSocket(5000); }
catch(SocketException se) {
se.printStackTrace();
System.exit(1); }
}
public void waitForPackets() {
while (true) {
try {
byte data[] = new byte[100];
receivePacket = new DatagramPacket(data,data.length);
socket.receive(receivePacket);
display.append("\nPacket received: " +
"\nFrom Host : " + receivePacket.getAddress() +
"\nHost port : " + receivePacket.getPort() +
"\nLength : " + receivePacket.getLength() +

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

"\nContaining : \n\t" +
new String (receivePacket.getData(),0,receivePacket.getLength() ) );

display.append("\n Echo data to client...\n");


sendPacket = new DatagramPacket (receivePacket.getData(),
receivePacket.getLength(), receivePacket.getAddress(),
receivePacket.getPort() );
socket.send(sendPacket);
display.append("\n Packet sent....\n");
display.setCaretPosition(display.getText().length() );
}
catch (IOException io)
{
display.append(io.toString()+ "\n");
io.printStackTrace();
}
}
}
public static void main(String args[])
{
Serverd app= new Serverd();
app.addWindowListener( new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{ System.exit(0); }
} );
app.waitForPackets();
}
}

SOURCE CODE

// TWO-way Communication using Swing - CLIENT

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


import java.awt.*; import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame
{
private JTextField enter;
private JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

String message=" ";


public Client()
{
super ("Client");
Container c=getContentPane();
enter=new JTextField();
enter.setEnabled(false);
enter.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sendData(e.getActionCommand() );
}
}
);
c.add(enter,BorderLayout.NORTH);
display=new JTextArea();
c.add(new JScrollPane (display), BorderLayout.CENTER);
setSize(300,150);
show();
}
public void runClient()
{
Socket client;
try
{
display.setText("Attempting Connection\n");
client = new Socket(InetAddress.getByName("127.0.0.1"), 5000);
display.append("Connected to: " +
client.getInetAddress().getHostName() );
output=new ObjectOutputStream (client.getOutputStream() );
output.flush();
input = new ObjectInputStream (client.getInputStream() );
display.append("\n Got I/O streams \n");
enter.setEnabled(true);
do {
try {
message=(String) input.readObject();
display.append("\n" + message);
display.setCaretPosition( display.getText().length() );
}
catch (ClassNotFoundException cnfex)
{
display.append("\nUnknown object type received");
}
} while( !message.equals("SERVER>>>TERMINATE") );

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

display.append("\n Closing connection. \n");


output.close();
input.close();
client.close();
}
catch(EOFException eof)
{
System.out.println("Server terminated connection");
}
catch(IOException e)
{
e.printStackTrace();
}
}
private void sendData(String s)
{
try
{
message =s;
output.writeObject("CLIENT>>>"+ s);
output.flush();
display.append("\n CLIENT>>>" + s);
}
catch(IOException cnfex)
{
display.append("\n Error writing object");
}
}
public static void main(String args[])
{
Client app=new Client();

app.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
app.runClient();
}
}

// TWO-way Communication using Swing - SERVER

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Server extends JFrame
{
private JTextField enter;
private JTextArea display;
ObjectOutputStream output;
ObjectInputStream input;
public Server()
{
super ("Server");
Container c = getContentPane();
enter = new JTextField();
enter.setEnabled(false);
enter.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
sendData(e.getActionCommand() );
}
}
);
c.add(enter,BorderLayout.NORTH);
display=new JTextArea();
c.add(new JScrollPane (display), BorderLayout.CENTER);
setSize(300,150);
show();
}

public void runServer()


{
ServerSocket server;
Socket connection;
int counter=1;
try
{
server = new ServerSocket(5000, 100);
while (true)
{
display.setText("Waiting for connection \n");
connection=server.accept();
display.append("Connection" + counter + "received from: "+

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

connection.getInetAddress().getHostName() );
output=new ObjectOutputStream ( connection.getOutputStream() );
output.flush();
input = new ObjectInputStream ( connection.getInputStream() );
display.append("\n Got I/O streams \n");
String message= "SERVER>> Connection successful";
output.writeObject(message);
output.flush();
enter.setEnabled(true);
do
{
try
{
message=(String) input.readObject();
display.append("\n" + message);
display.setCaretPosition( display.getText().length() );
}
catch (ClassNotFoundException cnfex)
{
display.append("\nUnknown object type received");
}
} while( !message.equals("CLIENT>>>TERMINATE") );

display.append("\n User terminated connection");


enter.setEnabled(false);
output.close();
input.close();
connection.close();
++counter;
}
}

catch(EOFException eof)
{
System.out.println("Client terminated connection");
}
catch(IOException io) {
io.printStackTrace(); }
}
private void sendData(String s) {
try {
output.writeObject("Server>>>"+s);
output.flush();
display.append("\nServer>>>"+s); }
catch(IOException cnfex) {

DEPARTMENT OF COMPUTER SCIENCE


RAJIV GANDHI ARTS & SCIENCE COLLEGE, PUDUCHERRY ( )

display.append("\n Error writing object"); }


}
public static void main(String args[])
{
Server app=new Server();
app.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
app.runServer();
}
}

DEPARTMENT OF COMPUTER SCIENCE

You might also like