Sei sulla pagina 1di 64

TO IMPLEMENT SLIDING WINDOW PROTOCOL SLIDING WINDOW

//slireceiver.java
import java.io.*;
import java.net.*;
class sliclient
{
public static void main(String aafhbasgj[])throws Exception
{
Socket s=new Socket("localhost",6483);
String opmsg;
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
DataInputStream in=new DataInputStream(s.getInputStream());
PrintStream dos=new PrintStream(s.getOutputStream());
int iterations=Integer.parseInt(in.readLine());
String msg=in.readLine();
int no=Integer.parseInt(msg);
int i=0,intr=0,iframe=0;
int framecounter=0;
while(intr<iterations)
{
msg=in.readLine();
System.out.println(msg);
i++;
framecounter++;
if(framecounter%no==0)
{
System.out.println("sending ack to server");
opmsg="ACK : FRAME "+iframe+" RECIEVED";

dos.println(opmsg);
iframe++;
}
if(i==8)
{
i=0;
intr++;
}
}
s.close();
}
}
/*
java slisender
Enter number of iterations
5
Enter window size
2
ACK : FRAME 0 RECIEVED
ACK : FRAME 1 RECIEVED
ACK : FRAME 2 RECIEVED
ACK : FRAME 3 RECIEVED
ACK : FRAME 4 RECIEVED
*/
TO IMPLEMENT SLIDING WINDOW PROTOCOL
slisender.java
*/
import java.io.*;
import java.net.*;
class slisender
{

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


{
ServerSocket ss=new ServerSocket(6483);
Socket s=ss.accept();
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
DataInputStream in=new DataInputStream(s.getInputStream());
String str1;
System.out.println("Enter number of iterations");
int it=Integer.parseInt(br.readLine());
int intr=0;
int msg[]=new int[8];
for(int i=0;i<8;i++)
msg[i]=i;
PrintStream p;
int no;
p=new PrintStream(s.getOutputStream());
p.println(it);
System.out.println("Enter window size");
no=Integer.parseInt(br.readLine());
p.println(no);
int i=0;
while(intr<it)
{
p.println(msg[i]);
i++;
if(i==no)
{
str1=in.readLine();

System.out.println(str1);
}
if(i==8)
{
i=0;
intr++;
}
}
ss.close();
s.close();
}
}
/*
java sliclient
0
1
sending ack to server
2
3
sending ack to server
4
5
sending ack to server
6
7
sending ack to server
0
1
sending ack to server
2
3

sending ack to server


4
5
sending ack to server
6
7
sending ack to server
0
1
sending ack to server
2
3
sending ack to server
4
5
sending ack to server
6
7
sending ack to server
0
1
sending ack to server
2
3
sending ack to server
4
5
sending ack to server
6
7
sending ack to server

0
1
sending ack to server
2
3
sending ack to server
4
5
sending ack to server
6
7
sending ack to server
*/
Implementing stop wait protocol in java
//SENDER PROGRAM
import java.io.*;
import java.net.*;
public class Sender{
Socket sender;
ObjectOutputStream out;
ObjectInputStream in;
String packet,ack,str, msg;
int n,i=0,sequence=0;
Sender(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));

System.out.println("Waiting for Connection....");


sender = new Socket("localhost",2004);
sequence=0;
out=new ObjectOutputStream(sender.getOutputStream());
out.flush();
in=new ObjectInputStream(sender.getInputStream());
str=(String)in.readObject();
System.out.println("reciver

> "+str);

System.out.println("Enter the data to send....");


packet=br.readLine();
n=packet.length();
do{
try{
if(i<n){
msg=String.valueOf(sequence);
msg=msg.concat(packet.substring(i,i+1));
}
else if(i==n){
msg="end";out.writeObject(msg);break;
}
out.writeObject(msg);
sequence=(sequence==0)?1:0;
out.flush();
System.out.println("data sent>"+msg);
ack=(String)in.readObject();
System.out.println("waiting for ack.....\n\n");
if(ack.equals(String.valueOf(sequence))){
i++;
System.out.println("receiver > "+" packet recieved\n\n");
}

else{
System.out.println("Time out resending data....\n\n");
sequence=(sequence==0)?1:0;
}
}catch(Exception e){}
}while(i<n+1);
System.out.println("All data sent. exiting.");
}catch(Exception e){}
finally{
try{
in.close();
out.close();
sender.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Sender s=new Sender();
s.run();
}
}
//RECEIVER PROGRAM
import java.io.*;
import java.net.*;
public class Reciever{
ServerSocket reciever;
Socket connection=null;
ObjectOutputStream out;

ObjectInputStream in;
String packet,ack,data="";
int i=0,sequence=0;
Reciever(){}
public void run(){
try{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
reciever = new ServerSocket(2004,10);
System.out.println("waiting for connection...");
connection=reciever.accept();
sequence=0;
System.out.println("Connection established :");
out=new ObjectOutputStream(connection.getOutputStream());
out.flush();
in=new ObjectInputStream(connection.getInputStream());
out.writeObject("connected

.");

do{
try{
packet=(String)in.readObject();
if(Integer.valueOf(packet.substring(0,1))==sequence){
data+=packet.substring(1);
sequence=(sequence==0)?1:0;
System.out.println("\n\nreceiver

>"+packet);

}
else
{
System.out.println("\n\nreceiver

>"+packet +" duplicate data");

}
if(i<3){
out.writeObject(String.valueOf(sequence));i++;

}
else{
out.writeObject(String.valueOf((sequence+1)%2));
i=0;
}
}
catch(Exception e){}
}while(!packet.equals("end"));
System.out.println("Data recived="+data);
out.writeObject("connection ended

.");

}
catch(Exception e){}
finally{
try{
in.close();
out.close();
reciever.close();
}
catch(Exception e){}
}
}
public static void main(String args[]){
Reciever s=new Reciever();
while(true){
s.run();
}
}
}
OUTPUT:
//SENDER OUTPUT

Waiting for Connection....


reciver > connected

Enter the data to send....


myname
data sent>0m
waiting for ack.....
receiver

> packet recieved

data sent>1y
waiting for ack.....
receiver

> packet recieved

data sent>0n
waiting for ack.....
receiver

> packet recieved

data sent>1a
waiting for ack.....
Time out resending data....
data sent>1a
waiting for ack.....
receiver

> packet recieved

data sent>0m
waiting for ack.....
receiver

> packet recieved

data sent>1e
waiting for ack.....
receiver

> packet recieved

All data sent. exiting.


//RECEIVER OUTPUT
waiting for connection...
Connection established :
receiver

>0m

receiver

>1y

receiver

>0n

receiver

>1a

receiver

>1a duplicate data

receiver

>0m

receiver

>1e

Data recived=myname
waiting for connection...

CLIENT-SERVER APPLICATION FOR CHAT


AIM:
To write a client-server application for chat using TCP
ALGORITHM: CLIENT
1.start the program
2. Include necessary package in java
3. To create a socket in client to server.
4. The client establishes a connection to the server.
5. The client accept the connection and to send the data from client to server
and vice versa
6. The client communicate the server to send the end of the message
7. Stop the program.
ALGORITHM: SERVER
1.start the program
2. Include necessary package in java
3. To create a socket in server to client
4. The server establishes a connection to the client.
5. The server accept the connection and to send the data from server to
client and vice versa
6. The server communicate the client to send the end of the message
7. Stop the program.

TCPserver1.java
import java.net.*;
import java.io.*;
public class TCPserver1
{
public static void main(String arg[])
{
ServerSocket s=null;
String line;
DataInputStream is=null,is1=null;
PrintStream os=null;
Socket c=null;
try
{
s=new ServerSocket(9999);
}
catch(IOException e)
{
System.out.println(e);
}
try
{
c=s.accept();
is=new DataInputStream(c.getInputStream());
is1=new DataInputStream(System.in);
os=new PrintStream(c.getOutputStream());
do
{
line=is.readLine();
System.out.println("Client:"+line);
System.out.println("Server:");

line=is1.readLine();
os.println(line);
}while(line.equalsIgnoreCase("quit")==false);
is.close();
os.close();
}
catch(IOException e)
{
System.out.println(e);
}
}
}
TCPclient1.java
import java.net.*;
import java.io.*;
public class TCPclient1
{
public static void main(String arg[])
{
Socket c=null;
String line;
DataInputStream is,is1;
PrintStream os;
try
{
c=new Socket("10.0.200.36",9999);
}
catch(IOException e)
{
System.out.println(e);

}
try
{
os=new PrintStream(c.getOutputStream());
is=new DataInputStream(System.in);
is1=new DataInputStream(c.getInputStream());
do
{
System.out.println("Client:");
line=is.readLine();
os.println(line);
System.out.println("Server:" + is1.readLine());
}while(line.equalsIgnoreCase("quit")==false);
is1.close();
os.close();
}
catch(IOException e)
{
System.out.println("Socket Closed!Message Passing is
over");
}
}
OUT PUT :
Server
C:\Program Files\Java\jdk1.5.0\bin>javac TCPserver1.java
Note: TCPserver1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPserver1
Client: Hai Server

Server:
Hai Client
Client: How are you
Server:
Fine
Client: quit
Server:
quit
Client
C:\Program Files\Java\jdk1.5.0\bin>javac TCPclient1.java
Note: TCPclient1.java uses or overrides a deprecated API.
Note: Recompile with -deprecation for details.
C:\Program Files\Java\jdk1.5.0\bin>java TCPclient1
Client:
Hai Server
Server: Hai Client
Client:
How are you
Server: Fine
Client:
quit
Server: quit
RESULT:
Thus the above program a client-server application for chat using TCP
/ IP was executed and successfully.

PROGRAM USING UDP SOCKET

AIM:
To write a client-server application for chat using UDP
ALGORITHM: CLIENT
1. Include necessary package in java
2. To create a socket in client to server.
3. The client establishes a connection to the server.
4. The client accept the connection and to send the data from client to server
and vice versa
5. The client communicate the server to send the end of the message
6. Stop the program.
ALGORITHM: SERVER
1. Include necessary package in java
2. To create a socket in server to client
3. The server establishes a connection to the client.
4. The server accept the connection and to send the data from server to
client and vice versa
5. The server communicate the client to send the end of the message
6. Stop the program.

Program :
UDPserver.java
import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;

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


{
ds=new DatagramSocket(clientport);
System.out.println("press ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new
InputStreamReader(System.in));
InetAddress ia=InetAddress.getByName("localhost");
while(true)
{
DatagramPacket p=new
DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Client:" + psx);
System.out.println("Server:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new
DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
UDPclient.java
import java .io.*;
import java.net.*;
class UDPclient
{
public static DatagramSocket ds;

public static int clientport=789,serverport=790;


public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("server waiting");
InetAddress ia=InetAddress.getByName("10.0.200.36");
while(true)
{
System.out.println("Client:");
String str=dis.readLine();
if(str.equals("end"))
break;
buffer=str.getBytes();
ds.send(new
DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new
DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Server:" + psx);
}
}
}
Output
Server
C:\Program Files\Java\jdk1.5.0\bin>javac UDPserver.java

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 what about you

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

RESULT:
Thus the above program a client-server application for chat using UDP
was executed and successfully

ARP Client/Server
Aim
To know the physical address of a host when its logical address is known
using ARP
protocol.
Algorithm
Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read IP address from the client request
4. Check its configuration file and compare with its logical address.
5. If there is a match, send the host physical address.
6. Stop
Client
1. Create a socket.
2. Send IP address to the target machine
3. Receive target's response
4. If it is a MAC address then display it and go to step 6
5. Display "Host not found"
6. Stop
Result
Thus using ARP protoocl MAC address is obtained.
Program
//ARP Server -- arpserver.java
import java.io.*;
import java.net.*;
class arpserver
{
public static void main(String args[])throws IOException

{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin=new BufferedReader(new
InputStreamReader(p.getInputStream()));
String haddr = "";
String ipaddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if((str.indexOf("HWaddr")) != -1)
{
int tlen = str.length();
int hlen = tlen - 19;
haddr = str.substring(hlen,tlen);
}
else if ((str.indexOf(ipaddr)) != -1)
{
flag = 1;

}
}
if (flag == 1)
ps.println(haddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
//ARP Client -- arpclient.java
import java.io.*;
import java.net.*;
class arpclient
{
public static void main(String args[])
{
try
{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String ipaddr,haddr = null;

BufferedReader sin = new BufferedReader(new


InputStreamReader(client.getInputStream()));
System.out.print("Enter the IP address : ");
ipaddr = br.readLine();
ps.println(ipaddr);
haddr = sin.readLine();
if (haddr == null)
System.out.println("Host does not exist");
else
System.out.println("Physical Address " + haddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}
}
}
Output
Server
$ javac arpserver.java
$ java arpserver
Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.6.21 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0

collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16
Client
$ javac arpclient.java
$ java arpclient
Enter the IP address : 172.16.6.21
Physical Address B8:AC:6F:1B:AB:06
5D RARP Client/Server
Aim
To know the logical address of a host when its physical address is known
using RARP
protocol.
Algorithm
Target/Server
1. Create a server socket.
2. Accept client connection.
3. Read MAC address from the client request
4. Check its configuration file and compare with its physical address.
5. If there is a match, send the host logical address.
6. Stop
Client
1. Create a socket.
2. Send physical address to the target machine
3. Receive target's response
4. If it is a IP address then display it and go to step 6
5. Display "Host not found"
6. Stop
Result
Thus using RARP protocol, IP address is obtained.

//RARP Server -- rarpserver.java


import java.io.*;
import java.net.*;
class rarpserver
{
public static void main(String args[])throws IOException
{
try
{
ServerSocket soc = new ServerSocket(2500);
System.out.println("Server started");
Socket client = null;
client = soc.accept();
String str;
PrintStream ps = new
PrintStream(client.getOutputStream());
BufferedReader br = new BufferedReader(new
InputStreamReader(client.getInputStream()));
Runtime r = Runtime.getRuntime();
Process p = r.exec("ifconfig eth0");
BufferedReader pin = new BufferedReader(new
InputStreamReader(p.getInputStream()));
String ipaddr = "";
String haddr = br.readLine();
int flag = 0;
while((str = pin.readLine())!=null)
{
System.out.println(str);
if ((str.indexOf(haddr)) != -1)
{

flag = 1;
}
else if((str.indexOf("inet addr")) != -1)
{
int pos = str.indexOf("inet addr:") + 10;
int offset = pos + 13;
ipaddr = str.substring(pos,offset);
}
}
if (flag == 1)
ps.println(ipaddr);
ps.close();
br.close();
pin.close();
client.close();
soc.close();
}
catch(IOException io)
{
System.err.println("Exception : " + io.toString());
}
}
}
// RARP Client -- rarpclient.java
import java.io.*;
import java.net.*;
class rarpclient
{
public static void main(String args[])
{
try

{
Socket client = new Socket("localhost", 2500);
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
PrintStream ps = new
PrintStream(client.getOutputStream());
String haddr,ipaddr = null;
BufferedReader sin = new BufferedReader(new
InputStreamReader(client.getInputStream()));
System.out.print("Enter the physical address : ");
haddr = br.readLine();
ps.println(haddr);
ipaddr = sin.readLine();
if (ipaddr == null)
System.out.println("Host does not exist");
else
System.out.println("Logical Address " + ipaddr);
ps.close();
br.close();
client.close();
}
catch(IOException io)
{
System.err.println(io.toString());
}
}
}
Output
Server
$ javac rarpserver.java
$ java rarpserver

Server started
eth0 Link encap:Ethernet HWaddr B8:AC:6F:1B:AB:06
inet addr:172.16.6.21 Bcast:172.255.255.255 Mask:255.0.0.0
inet6 addr: fe80::baac:6fff:fe1b:ab06/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:450 errors:0 dropped:0 overruns:0 frame:0
TX packets:127 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:48118 (46.9 KiB) TX bytes:21025 (20.5 KiB)
Interrupt:16
Client
$ javac rarpclient.java
$ java rarpclient
Enter the physical address : B8:AC:6F:1B:AB:06
Logical Address 172.16.6.21
Ping server and client
package in.techdive.java;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class PingPoller
{
public static void main(String[] args)
{
System.out.println("Ping Poller Starts...");
String ipAddress = "localhost";

try
{
InetAddress inet = InetAddress.getByName(ipAddress);
System.out.println("Sending Ping Request to " + ipAddress);
boolean status = inet.isReachable(5000); //Timeout = 5000 milli
seconds
if (status)
{
System.out.println("Status : Host is reachable");
}
else
{
System.out.println("Status : Host is not reachable");
}
}
catch (UnknownHostException e)
{
System.err.println("Host does not exists");
}
catch (IOException e)
{
System.err.println("Error in reaching the Host");
}
}
}

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

public class HTTPFileUploadServer extends


Thread {

static final String


HTML_START =
"<html>"
+

"<title>HTTP POST Server in


java</title>" +
"<body
>";

static final String


HTML_END =
"</body
>" +
"</html
>";

Socket connectedClient =
null;
DataInputStream inFromClient
= null;
DataOutputStream outToClient
= null;

public HTTPFileUploadServer(Socket
client) {
connectedClient =
client;

void closeStreams() throws


Exception {
inFromClient.clos
e();
outToClient.clos
e();
connectedClient.clo
se();

Remote procedure call


Program
// Declares remote method interfaces--CalcInf.java
import java.rmi.*;

public interface CalcInf extends Remote


{
public long add(int a, int b) throws RemoteException;
public int sub(int a, int b) throws RemoteException;
public long mul(int a, int b) throws RemoteException;
public int div(int a, int b) throws RemoteException;
public int rem(int a, int b) throws RemoteException;
}
// Implement Remote behavior--CalcImpl.java
import java.rmi.*;
import java.rmi.server.*;
public class CalcImpl extends UnicastRemoteObject implements
CalcInf
{
public CalcImpl() throws RemoteException { }
public long add(int a, int b) throws RemoteException
{
return a + b;
}
public int sub(int a, int b) throws RemoteException
{
int c = a > b ? a - b : b - a;
return c;
}
public long mul(int a, int b) throws RemoteException
{
return a * b;
}
public int div(int a, int b) throws RemoteException
{
return a / b;

}
public int rem(int a, int b) throws RemoteException
{
return a % b;
}
}
// Server that names the service implemented-CalcServer.java
import java.rmi.*;
public class CalcServer
{
public static void main(String args[])
{
try {
CalcInf C = new CalcImpl();
Naming.rebind("CalcService", C);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
// Client that invokes remote host methods--CalcClient.java
import java.rmi.*;
import java.net.*;
public class CalcClient
{
public static void main(String[] args) throws Exception
{
try {
CalcInf C = (CalcInf) Naming.lookup("rmi://" +

args[0] + "/CalcService");
int a, b;
if (args.length != 3)
{
System.out.println("Usage: java CalcClient
<remoteip> <operand1> <operand2>");
System.exit(-1);
}
a = Integer.parseInt(args[1]);
b = Integer.parseInt(args[2]);
System.out.println( "\nBasic Remote Calc\n" );
System.out.println("Summation : " + C.add(a, b));
System.out.println("Difference : " + C.sub(a, b));
System.out.println("Product : " + C.mul(a, b));
System.out.println("Quotient : " + C.div(a, b));
System.out.println("Remainder : " + C.rem(a, b));
}
catch (Exception E) {
System.out.println(E.getMessage());
}
}
}
Output
Server
C:\>javac CalcInf.java
C:\>javac CalcImpl.java
C:\>javac CalcServer.java
C:\>javac CalcClient.java
C:\>rmic CalcImpl
C:\>start rmiregistry
C:\>java CalcServer

Client
C:\>java CalcClient 172.16.6.45 6 8
Basic Remote Calc
Summation : 14
Difference : 2
Product : 48
Quotient : 0
Remainder :
Program for subnetting and subnet masking in java.
import java.util.Scanner;
class Subnet{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
System.out.print(Enter the ip address: );
String ip = sc.nextLine();
String split_ip[] = ip.split(\\.); //SPlit the string after every .
String split_bip[] = new String[4]; //split binary ip
String bip = ;
for(int i=0;i<4;i++){
split_bip[i] =
appendZeros(Integer.toBinaryString(Integer.parseInt(split_ip[i]))); // 18 =>
18 => 10010 => 00010010
bip += split_bip[i];
}
System.out.println(IP in binary is +bip);
System.out.print(Enter the number of addresses: );
int n = sc.nextInt();
//Calculation of mask
int bits = (int)Math.ceil(Math.log(n)/Math.log(2)); /*eg if address = 120, log

120/log 2 gives log to the base 2 => 6.9068, ceil gives us upper integer */
System.out.println(Number of bits required for address = +bits);
int mask = 32-bits;
System.out.println(The subnet mask is = +mask);
//Calculation of first address and last address
int fbip[] = new int[32];
for(int i=0; i<32;i++) fbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to
integer 0,1
for(int i=31;i>31-bits;i)//Get first address by ANDing last n bits with 0
fbip[i] &= 0;
String fip[] = {,,,};
for(int i=0;i<32;i++)
fip[i/8] = new String(fip[i/8]+fbip[i]);
System.out.print(First address is = );
for(int i=0;i<4;i++){
System.out.print(Integer.parseInt(fip[i],2));
if(i!=3) System.out.print(.);
}
System.out.println();
int lbip[] = new int[32];
for(int i=0; i<32;i++) lbip[i] = (int)bip.charAt(i)-48; //convert cahracter 0,1 to
integer 0,1
for(int i=31;i>31-bits;i)//Get last address by ORing last n bits with 1
lbip[i] |= 1;
String lip[] = {,,,};
for(int i=0;i<32;i++)
lip[i/8] = new String(lip[i/8]+lbip[i]);
System.out.print(Last address is = );
for(int i=0;i<4;i++){

System.out.print(Integer.parseInt(lip[i],2));
if(i!=3) System.out.print(.);
}
System.out.println();
}
static String appendZeros(String s){
String temp = new String(00000000);
return temp.substring(s.length())+ s;
}
}
/*Output
Enter the ip address: 100.110.150.10
IP in binary is 01100100011011101001011000001010
Enter the number of addresses: 7
Number of bits required for address = 3
The subnet mask is = 29
First address is = 100.110.150.8
Last addressis = 100.110.150.15
*/
Echo server and chat server
TCP Echo Server/Client
Aim
To implement echo server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket.
2. Wait for client to be connected.
3. Read text from the client

4. Echo the text back to the client.


5. Repeat steps 4-5 until bye or null is read.
6. Close the I/O streams
7. Close the server socket
8. Stop
Client
1. Create a socket and establish connection with the server
2. Get input from user.
3. If equal to bye or null, then go to step 7.
4. Send text to the server.
5. Display the text echoed by the server
6. Repeat steps 2-4
7. Close the I/O streams
8. Close the client socket
9. Stop
Result
Thus data from client to server is echoed back to the client to check
reliability/noise level of
the channel.
Program

TCP Echo Server--tcpechoserver.java


import java.net.*;
import java.io.*;
public class tcpechoserver
{
public static void main(String[] arg) throws IOException
{
ServerSocket sock = null;
BufferedReader fromClient = null;

OutputStreamWriter toClient = null;


Socket client = null;
try
{
sock = new ServerSocket(4000);
System.out.println("Server Ready");
client = sock.accept();
System.out.println("Client Connected");
fromClient = new BufferedReader(new
InputStreamReader(client.getInputStream()));
toClient = new
OutputStreamWriter(client.getOutputStream());
String line;
while (true)
{
line = fromClient.readLine();
if ( (line == null) || line.equals("bye"))
break;
System.out.println ("Client [ " + line + " ]");
toClient.write("Server [ "+ line +" ]\n");
toClient.flush();
}
fromClient.close();
toClient.close();
client.close();
sock.close();
System.out.println("Client Disconnected");
}
catch (IOException ioe)
{
System.err.println(ioe);

}
}
}
//TCP Echo Client--tcpechoclient.java
import java.net.*;
import java.io.*;
public class tcpechoclient
{
public static void main(String[] args) throws IOException
{
BufferedReader fromServer = null, fromUser = null;
PrintWriter toServer = null;
Socket sock = null;
try
{
if (args.length == 0)
sock = new Socket(InetAddress.getLocalHost(),
4000);
else
sock = new Socket(InetAddress.getByName(args[0]),
4000);
fromServer = new BufferedReader(new
InputStreamReader(sock.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
toServer = new PrintWriter(sock.getOutputStream(),
true
String Usrmsg, Srvmsg;
System.out.println("Type \"bye\" to quit");
while (true)
{

System.out.print("Enter msg to server : ");


Usrmsg = fromUser.readLine();
if (Usrmsg==null || Usrmsg.equals("bye"))
{
toServer.println("bye");
break;
}
else
toServer.println(Usrmsg);
Srvmsg = fromServer.readLine();
System.out.println(Srvmsg);
}
fromUser.close();
fromServer.close();
toServer.close();
sock.close();
}
catch (IOException ioe)
{
System.err.println(ioe);
}
Output
Server Console
$ javac tcpechoserver.java
$ java tcpechoserver
Server Ready
Client Connected
Client [ hello ]
Client [ how are you ]
Client [ i am fine ]
Client [ ok ]

Client Disconnected
Client Console
$ javac tcpechoclient.java
$ java tcpechoclient
Type "bye" to quit
Enter msg to server : hello
Server [ hello ]
Enter msg to server : how are you
Server [ how are you ]
Enter msg to server : i am fine
Server [ i am fine ]
Enter msg to server : ok
Server [ ok ]
Enter msg to server : bye

TCP Date Server/Client


Aim
To implement date server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket.
2. Wait for client to be connected.
3. Display the client details.
4. Send servers date and time to the client
5. Repeat steps 2-4 until the server is terminated
6. Close all streams
7. Close the server socket
8. Stop
Client
1. Create a client socket and establish connection with the server

2. Display the date & time sent by the server


3. Close the input and output streams
4. Close the client socket
5. Stop
Result
Thus every time a client connects to the server, servers date/time will be
returned to the
client for synchronization.
Program
//TCP Date Server--tcpdateserver.java
import java.net.*;
import java.io.*;
import java.util.*;
class tcpdateserver
{
public static void main(String arg[])
{
ServerSocket ss = null;
Socket cs;
PrintStream ps;
BufferedReader dis;
String inet;
try
{
ss = new ServerSocket(4444);
System.out.println("Press Ctrl+C to quit");
while(true)
{
cs = ss.accept();
ps = new PrintStream(cs.getOutputStream());
Date d = new Date();

ps.println(d);
dis = new BufferedReader(new
InputStreamReader(cs.getInputStream()));
inet = dis.readLine();
System.out.println("Client System/IP address is :"
+ inet);
ps.close();
dis.close();
}
}
catch(IOException e)
{
System.out.println("The exception is :" + e);
}
}
}
// TCP Date Client--tcpdateclient.java
import java.net.*;
import java.io.*;
class tcpdateclient
{
public static void main (String args[])
{
Socket soc;
BufferedReader dis;
String sdate;
PrintStream ps;
try
{
InetAddress ia = InetAddress.getLocalHost();
if (args.length == 0)

soc = new Socket(InetAddress.getLocalHost(),4444);


else
soc = new Socket(InetAddress.getByName(args[0]),
4444);
dis = new BufferedReader(new
InputStreamReader(soc.getInputStream()));
sdate=dis.readLine();
System.out.println("The date/time on server is : " +
sdate);
ps = new PrintStream(soc.getOutputStream());
ps.println(ia);
ps.close();
}
catch(IOException e)
{
System.out.println("THE EXCEPTION is :" + e);
}
}
}
Output
Server Console
$ javac tcpdateserver.java
$ java tcpdateserver
Press Ctrl+C to quit
Client System/IP address is : localhost.localdomain/127.0.0.1
Client System/IP address is : localhost.localdomain/127.0.0.1
Client Console
$ javac tcpdateclient.java
$ java tcpdateclient
The date/time on server is : Wed Jul 04 07:12:03 GMT 2012

Client Console
$ java tcpdateclient
The date/time on server is : Wed Jul 04 07:19:48 GMT 2012

TCP Chat Server/Client


Aim
To implement a chat server and client in java using TCP sockets.
Algorithm
Server
1. Create a server socket
2. Wait for client to be connected.
3. Read Client's message and display it
4. Get a message from user and send it to client
5. Repeat steps 3-4 until the client sends "end"
6. Close all streams
7. Close the server and client socket
8. Stop
Client
1. Create a client socket and establish connection with the server
2. Get a message from user and send it to server
3. Read server's response and display it
4. Repeat steps 2-3 until chat is terminated with "end" message
5. Close all input/output streams
6. Close the client socket
7. Stop
Result
Thus both the client and server exchange data using TCP socket
programming.
Program

// TCP Chat Server--tcpchatserver.java


import java.io.*;
import java.net.*;
class tcpchatserver
{
public static void main(String args[])throws Exception
{
PrintWriter toClient;
BufferedReader fromUser, fromClient;
try
{
ServerSocket Srv = new ServerSocket(5555);
System.out.print("\nServer started\n");
Socket Clt = Srv.accept();
System.out.println("Client connected");
toClient = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromClient = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
while(true)
{
CltMsg= fromClient.readLine();
if(CltMsg.equals("end"))
break;
else
{
System.out.println("\nServer <<< " +
CltMsg);

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


SrvMsg = fromUser.readLine();
toClient.println(SrvMsg);
}
}
System.out.println("\nClient Disconnected");
fromClient.close();
toClient.close();
fromUser.close();
Clt.close();
Srv.close();
}
catch (Exception E)
{
System.out.println(E.getMessage());
}
}
}
// TCP Chat Client--tcpchatclient.java
import java.io.*;
import java.net.*;
class tcpchatclient
{
public static void main(String args[])throws Exception
{
Socket Clt;
PrintWriter toServer;
BufferedReader fromUser, fromServer;
try
{
if (args.length > 1)

{
System.out.println("Usage: java hostipaddr");
System.exit(-1);
}
if (args.length == 0)
Clt = new Socket(InetAddress.getLocalHost(),5555);
else
Clt = new Socket(InetAddress.getByName(args[0]),
5555);
toServer = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(Clt.getOutputStream())), true);
fromServer = new BufferedReader(new
InputStreamReader(Clt.getInputStream()));
fromUser = new BufferedReader(new
InputStreamReader(System.in));
String CltMsg, SrvMsg;
System.out.println("Type \"end\" to Quit");
while (true)
{
System.out.print("\nMessage to Server : ");
CltMsg = fromUser.readLine();
toServer.println(CltMsg);
if (CltMsg.equals("end"))
break;
SrvMsg = fromServer.readLine();
System.out.println("Client <<< " + SrvMsg);
}
}
catch(Exception E)
{
System.out.println(E.getMessage());

}
}
}
Output
Server Console
$ javac tcpchatserver.java
$ java tcpchatserver
Server started
Client connected
Server <<< hi
Message to Client : hello
Server <<< how r u?
Message to Client : fine
Server <<< me too
Message to Client : bye
Client Disconnected
Client Console
$ javac tcpchatclient.java
$ java tcpchatclient
Type "end" to Quit
Message to Server : hi
Client <<< hello
Message to Server : how r u?
Client <<< fine
Message to Server : me too
Client <<< bye
Message to Server : end

File transfer using ftp

import java.net.*;
import java.io.*;
class tcpip_server
{
public static void main(String args[]) throws IOException
{
ServerSocket n1=null;
try
{
n1=new ServerSocket(98);
}
catch(IOException e)
{
System.err.println("Port 98 could not be found");
System.exit(1);
}
Socket c=null;
try
{
c=n1.accept();
System.out.println("Connection from "+c);
}
catch(IOException e)
{
System.out.println("Accept failed");
System.exit(1);
}

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


BufferedReader in=new BufferedReader(new
InputStreamReader(c.getInputStream()));
String n;
BufferedReader sin=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Ready to type now");
while((n=sin.readLine())!=null)
{
out.println(n);
}
out.close();
c.close();
n1.close();
}
}
import java.net.*;
import java.io.*;
class tcpip_client
{
public static void main(String args[]) throws IOException
{
Socket s=null;
BufferedReader b=null;
try
{
s=new Socket(InetAddress.getLocalHost(),98);
b=new BufferedReader(new

InputStreamReader(s.getInputStream()));
}
catch(UnknownHostException u)
{
System.err.println("I don't know host");
System.exit(0);
}
String inp;
while((inp=b.readLine())!=null)
{
System.out.println(inp);
}
b.close();
s.close();
}
}
File transfer using udp.
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String args[]) throws Exception
{
DatagramSocket serverSocket = new DatagramSocket(9876);
byte[] receiveData = new byte[1024];
byte[] sendData = new byte[1024];
while(true)

{
DatagramPacket receivePacket = new
DatagramPacket(receiveData, receiveData.length);
serverSocket.receive(receivePacket);
String sentence = new String( receivePacket.getData());
System.out.println("RECEIVED: " + sentence);
InetAddress IPAddress = receivePacket.getAddress();
int port = receivePacket.getPort();
String capitalizedSentence = sentence.toUpperCase();
sendData = capitalizedSentence.getBytes();
DatagramPacket sendPacket =
new DatagramPacket(sendData, sendData.length, IPAddress,
port);
serverSocket.send(sendPacket);
}
}
}
Dns using udp
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String args[]) throws Exception
{
BufferedReader inFromUser =
new BufferedReader(new InputStreamReader(System.in));
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = new byte[1024];

byte[] receiveData = new byte[1024];


String sentence = inFromUser.readLine();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData,
sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData,
receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
Client:
import java.io.*;
import java.net.*;
import java.util.*;
class Clientdns12
{
public static void main(String args[])
{
try
{
DatagramSocket client=new DatagramSocket();
InetAddress addr=InetAddress.getByName("127.0.0.1");
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];

BufferedReader in=new BufferedReader(new


InputStreamReader(System.in));
System.out.println("Enter the DOMAIN NAME or IP adress:");
String str=in.readLine();
sendbyte=str.getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,1309);
client.send(sender);
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
client.receive(receiver);
String s=new String(receiver.getData());
System.out.println("IP address or DOMAIN NAME:
"+s.trim());
client.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Server:
import java.io.*;
import java.net.*;
import java.util.*;
class Serverdns12
{
public static void main(String args[])
{
try

{
DatagramSocket server=new DatagramSocket(1309);
while(true)
{
byte[] sendbyte=new byte[1024];
byte[] receivebyte=new byte[1024];
DatagramPacket receiver=new
DatagramPacket(receivebyte,receivebyte.length);
server.receive(receiver);
String str=new String(receiver.getData());
String s=str.trim();
//System.out.println(s);
InetAddress addr=receiver.getAddress();
int port=receiver.getPort();
String ip[]={"165.165.80.80","165.165.79.1"};
String
name[]={"www.aptitudeguru.com","www.downloadcyclone.blogspot.com"};
for(int i=0;i<ip.length;i++)
{
if(s.equals(ip[i]))
{
sendbyte=name[i].getBytes();
DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
else if(s.equals(name[i]))
{
sendbyte=ip[i].getBytes();

DatagramPacket sender=new
DatagramPacket(sendbyte,sendbyte.length,addr,port);
server.send(sender);
break;
}
}
break;

}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
Output
I:\ex>java Serverdns12
I:\ex>java Clientdns12
Enter the DOMAIN NAME or IP adress:
165.165.80.80
IP address or DOMAIN NAME: www.aptitudeguru.com
I:\ex>java Clientdns12
Enter the DOMAIN NAME or IP adress:
www.downloadcyclone.blogspot.com
IP address or DOMAIN NAME: 165.165.79.1
Snmp using udp

import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* UDP Server listening to receive data from UDP Clients
*/
public class UDPServer
{
public static void main(String args[])
{
int server_port = 1111;
System.out.println("UDP Server Listening in " + server_port);
try
{
// DatagramSocket created and listening in Port 1111
DatagramSocket socket = new DatagramSocket(server_port);
byte[] msgBuffer = new byte[1024];
// DatagramPacket for receiving the incoming data from UDP
Client
DatagramPacket packet = new DatagramPacket(msgBuffer,
msgBuffer.length);
while (true)
{
socket.receive(packet);
String message = new String(msgBuffer, 0,
packet.getLength());
System.out.println("UDPServer: Message received = " +
message);

packet.setLength(msgBuffer.length);
}
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error in getting the Data from UDP
Client");
}
}
}
package in.techdive.udp.client;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* UDP Client for sending message
*/
public class UDPClient
{
public static void main(String args[])
{
try
{
String server_address = "localhost";
int server_port = 1111;
String message = "Techdive.in";

InetAddress address =
InetAddress.getByName(server_address);
// Create Datagram packet with the UDP Server Ipaddress/
Port and Message to be sent
DatagramPacket packet = new
DatagramPacket(message.getBytes(), message.getBytes().length, address,
server_port);
// Create DatagramSocket socket and send the Message
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
System.out.println("UDPClient: Sent data to Server ; Message
= " + message);
socket.close();
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Error in sending the Data to UDP Server");
}
}
}
Testing
In order to test the above UDP Client and Server, perform the below steps,
1. Execute the UDPServer.java class.
This will create the Datagram Socket and it will listen continuously in the port
1111.

2. Execute the UDPClient.java class which will send the data using Datagram
Socket to the local host in port 1111.
Output
UDP Server Listening in 1111
UDPServer: Message received = Techdive.in