Network Lab by Armstrong
Network Lab by Armstrong
PERUMALPATTU
Prepared by Asst.Prof J.Armstrong Joseph
Network Lab
TCP - CHAT PROGRAM
Ex.1
AIM:
To implement TCP client-server chat.
ALGORITHM:
Server:
1. Start
2. Create a socket with address family AF_INET, type SOCK_STREAM and
default protocol.
3. Initialize the socket and set its attributes. Assign any port
number as desired.
4. Bind the server to the socket using bind() function.
5. Establish the listen queue using the listen() function.
6. Wait for the client request. On request, establish a connection
using accept() function.
7. Repeat steps 8-10 until the server sends "bye"
8. Read the message from the client using read() function. Display
the message.
9. If the client message is "bye", go to step 11
10.Accept the server message and write it to the client using write()
function.
11.Close the connection.
12.Go to step 6.
Client:
1. Start
2. Create a socket with address family AF_INET, type SOCK_STREAM and
default protocol.
3. Initialize the socket and set its attributes. Set the required
port number.
4. Connect to the server using connect() function to initiate the
request.
5. Repeat steps 6-8 until the server sends "bye"
6. Accept the client message and write it to the server using write()
function.
7. If the client message is "bye", go to step 9
8. Read the message from the server using read() function. Display
the message.
CODE:
Server:
#include<stdio.h>
#include<sys/socket.h>
#include<iostream.h>
1
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<time.h>
# define MAX 100
int cwork(int);
int main()
{
int socketmain,socketclient,child,port=4567;
struct sockaddr_in serv;
char str[100];
if((socketmain = socket(AF_INET,SOCK_STREAM,0))<0)
{
cout <<" server cannot open the main socket ";
exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(port);
if(bind(socketmain,(struct sockaddr *) &serv,sizeof(serv)) < 0 )
{
cout << " server bin fail";
exit(0);
}
listen(socketmain,15);
for(;;)
{
if((socketclient = accept(socketmain,0,0)) < 0 )
{
cout << "client is bad ";
exit(0);
}
if((child=fork()) < 0)
{
cout << "failed to create child";
exit(1);
}
else if( child ==0)
{
close(socketmain);
cwork(socketclient);
2
close(socketclient);
exit(0);
}
close(socketclient);
}
}
int cwork(int socketclient)
{
char buf[81];
int msglen;
bzero(buf,81);
cout << " socket used " << socketclient;
for(;;)
{
if((msglen = recv(socketclient,buf,81,0)) < 0)
{
cout << " error during the child reception";
exit(1);
}
if(msglen == 81)
{
buf[msglen] = '\0';
cout << " \n message " << buf;
}
if(strcmp(buf,"bye") == 0)
{
strcpy(buf,"bye");
send(socketclient,buf,strlen(buf),0);
break;
}
else
{
cout << " \nenter the message for the client";
cin >> buf;
send(socketclient,buf,strlen(buf),0);
msglen=0;
Client:
3
#include<stdio.h>
#include<sys/socket.h>
#include<iostream.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<errno.h>
#include<time.h>
# define MAX 100
# define len 81
int cwork(int);
int main(int argc,char **argv)
{
int sockfd,n;
struct sockaddr_in serv;
char str[100];
if(argc != 3)
{
cout << " erroe message ";
exit(0);
}
if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
{
cout <<" socket not created ";
exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port=htons(atoi(argv[2]));
if(inet_pton(AF_INET,argv[1],&serv.sin_addr) <= 0)
{
cout << " conversion error " ;
exit(0);
}
if(connect(sockfd,(struct sockaddr *) &serv,sizeof(serv)) < 0 )
{
cout << " connect fail";
exit(0);
}
cout << " connected ";
for(;;)
4
{
while(strcmp(str,"bye")!=0)
{
cout << "\n enter the message to sever ";
cin>>str;
write(sockfd,str,sizeof(str));
n=read(sockfd,str,100);
str[n] = '\0';
cout << " from server " << str << endl;
}
break;
OUTPUT:
In server terminal
[armstrong@cseserver~]$c++ tcpser.cpp –o tcpser
[armstrong@cseserver~]$../tcpser
Socket used 4
message hey
Enter the message for client: hi
message bye
Enter the message for client:bye
In Client terminal
[armstrong@cseserver~]$c++ tcpcli.cpp –o tcpcli
Result:
Thus the program was executed successfully.
5
TCP - DATE AND TIME
Ex.2
AIM:
To display date and time of server from client using TCP.
ALGORITHM:
Server:
1. Start
2. Create a socket with address family AF_INET, type SOCK_STREAM
and default protocol.
3. Initialize the socket and set its attributes. Assign a specific
port number as desired.
4. Bind the server to the socket using bind() function.
5. Wait for the client request. On request, establish a connection
using accept() function.
6. Fork a child process. Perform steps 7-10 for each process.
7. read the message (indicates ‘ctime’) from the client through the
connection.
8. Display the client’s message.
9. Send an acknowledgement message(‘time’ and ‘date’) to the client.
10.Exit the child process.
11.Close the connection and go to step 5.
Client:
1. Start
2. Create a socket with address family AF_INET, type SOCK_STREAM and
default protocol.
3. Initialize the socket and set its attributes. Set the required
port number.
4. Connect to the server using connect() function to initiate the
request.
5. Send the message (request of ‘time’ and ‘date’) to the server.
6. Receive the acknowledgement from the server
7. Stop
Code:-
Server:-
#include<stdio.h>
#include<sys/socket.h>
#include<iostream.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
6
#include<time.h>
# define MAX 100
# define len 81
int cwork(int);
int main()
{
int socketmain,socketclient,child,port=2000;
struct sockaddr_in serv;
char str[100];
if((socketmain = socket(AF_INET,SOCK_STREAM,0))<0)
{
cout <<" server cannot open the main socket ";
exit(0);
}
bzero(&serv,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port=htons(port);
if(bind(socketmain,(struct sockaddr *) &serv,sizeof(serv)) < 0 )
{
cout << " server bind fail";
exit(0);
}
listen(socketmain,15);
for(;;)
{
if((socketclient = accept(socketmain,0,0)) < 0 )
{
cout << "client is bad ";
exit(0);
}
if((child=fork()) < 0)
{
cout << "failed to create child";
exit(1);
}
7
}
Client:-
#include<stdio.h>
#include<sys/socket.h>
#include<iostream.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<netdb.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<errno.h>
#include<time.h>
# define MAX 100
int cwork(int);
8
{
cout <<"Conversion error " ;
exit(0);
}
if(connect(sockfd,(struct sockaddr *) &serv,sizeof(serv)) < 0 )
{
cout <<"Connect fail";
exit(0);
}
cout << " connected ";
cout << " enter the message to server ";
gets(str);
write(sockfd,str,sizeof(str));
n=read(sockfd,str,100);
str[n] = '\0';
cout << " from server " << str << endl;
}
OUTPUT:
In server terminal
[armstrong@cseserver~]$c++ dateserv.cpp –o dateserv
[armstrong@cseserver~]$../ dateserv
Socket used 4
message abcd
In Client terminal
[armstrong@cseserver~]$c++ dateclient.cpp –o dateclient
Result:
Thus the program was executed successfully.
9
DOMAIN NAME SERVER using TCP
Ex.3
AIM: To implement Domain name server using TCP client server program.
ALGORITHM
Server:
1. Create a socket on server side using socket routine.
2. Assign IP address ,port number and the protocol family to the
members of struct sockaddr_in
3. Bind IP address, port number and protocol family to the socket.
4. Listen for request from the client.
5 Accept connection from the client application
6. Obtain the Hostname and retrieve address using gethostbyname
function.
7. Write the host address to the client side.
8. Close socket.
Client:
1. Create socket on client side using socket routine.
2. Assign IP address, Port number and Protocol family.
3. Connect to the server using connect routine.
4. Enter the hostname and write to the server.
5. Read the IP address and display it.
6. Close the socket.
Code:-
server:
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define SER_PORT 6022
int main()
{
int a, sersock, newsock;
char str2[100], host[25];
void *buf, *buf2;
struct sockaddr_in seraddr;
struct sockaddr_in clinfo;
10
struct hostent *hp;
socklen_t size=sizeof(clinfo);
seraddr.sin_family=AF_INET;
seraddr.sin_port=htons(SER_PORT);
seraddr.sin_addr.s_addr=htonl(INADDR_ANY);
if((sersock=socket(AF_INET, SOCK_STREAM,0))<0)
{
cout<<"\n Socket";
exit(0);
}
if(bind(sersock,(struct sockaddr *) &seraddr,sizeof(seraddr)) <0 )
{
cout<<"\n Bind";
exit(0);
}
if(listen(sersock,1)<0)
{
cout<<"\nListen";
exit(0);
}
if((newsock=accept(sersock,(struct sockaddr *)&clinfo,&size))<0)
{
cout<<"\n Accept";
exit(0);
}
else
cout<<"\n Connected to :" << inet_ntoa(clinfo.sin_addr);
read(newsock,host,sizeof(host));
cout<<host;
hp=gethostbyname(host);
inet_ntop(AF_INET,hp->h_addr,str2,sizeof(str2));
cout<< str2;
write(newsock,str2,strlen(str2)+1);
close(newsock);
close(sersock);
return 0;
}
CLIENT:
#include<iostream.h>
11
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#define SER_PORT 6022
int main(int count, char *arg[])
{
int a, clisock, x;
char str2[25], host[25];
struct sockaddr_in cliaddr;
cliaddr.sin_family=AF_INET;
cliaddr.sin_port=htons(SER_PORT);
cliaddr.sin_addr.s_addr=inet_addr(arg[1]);
clisock=socket(AF_INET, SOCK_STREAM,0);
if(clisock<0)
{
cout<<"\nSocket";
exit(0);
}
if((x=connect(clisock, (struct sockaddr *)&cliaddr, sizeof(cliaddr)))<0)
{
cout<<"\nConnect";
exit(0);
}
cout<<" \nEnter the domain name:";
cin>> host;
write(clisock, host, strlen(host)+1);
read(clisock, str2, sizeof(str2));
cout<< str2;
close(clisock);
return 0;
}
OUTPUT:
12
[armstrongl@cseserver ~]$ ./a.out
Result:
Thus the program was executed successfully.
13
DOMAIN NAME SERVER using UDP
Ex.4
AIM: To implement Domain name server using UDP client server program.
ALGORITHM
Server:
1. Create a socket on server side using socket routine.
2. Assign IP address ,port number and the protocol family to the
members of struct sockaddr_in
3. Bind IP address, port number and protocol family to the socket.
4. Listen for request from the client.
5 Accept connection from the client application
6. Obtain the Hostname and retrieve address using gethostbyname
function.
7. Write the host address to the client side.
8. Close socket.
Client:
1. Create socket on client side using socket routine.
2. Assign IP address, Port number and Protocol family.
3. Connect to the server using connect routine.
4. Enter the hostname and write to the server.
5. Read the IP address and display it.
6. Close the socket.
Code:-
server:
#include<iostream.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
void dg_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t
clilen);
int main(int argc,char **argv)
{
int sockfd;
char mesg2[100];
struct hostent *hp;
14
struct sockaddr_in servaddr,cliaddr;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(9877);
bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr));
dg_echo(sockfd,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
}
void dg_echo(int sockfd,struct sockaddr* pcliaddr,socklen_t
clilen)
{
int n;
socklen_t len;
struct hostent *hp;
char mesg[100];
for(;;)
{
len=clilen;
n=recvfrom(sockfd,mesg,100,0,pcliaddr,&len);
cout<<mesg;
hp=gethostbyname(mesg);
inet_ntop(AF_INET,hp->h_addr,mesg,sizeof(mesg));
cout<<mesg;
sendto(sockfd,mesg,n,0,pcliaddr,len);
}
}
client:
#include<iostream.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
void dg_cli(FILE *fp,int sockfd,struct sockaddr*
pservaddr,socklen_t servlen);
int main(int argc,char **argv)
{
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2)
{
cout<<"\n usage: updcli ";
15
exit(0);
}
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(9877);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
sockfd=socket(AF_INET,SOCK_DGRAM,0);
cout<<"\n enter the host name:";
dg_cli(stdin,sockfd,(struct sockaddr*)
&servaddr,sizeof(servaddr));
exit(0);
}
void dg_cli(FILE *fp,int sockfd,struct sockaddr*
pservaddr,socklen_t servlen)
{
int n;
char sendline[100], recvline[101];
while(fgets(sendline,100,fp)!=NULL)
{
sendto(sockfd,sendline,strlen(sendline),0,pservaddr,servlen)
;
n=recvfrom(sockfd,recvline,100,0,NULL,NULL);
recvline[n]=0;
fputs(recvline,stdout);
}
}
OUTPUT:
Result:
Thus the program was executed successfully.
16
Create a RAW socket with UDP protocol
Ex.5
ALGORITHM
Server:
1. Create a raw socket using socket routine.
2. Assign IP address ,port number and the protocol family to the
members of struct sockaddr_in for source and destination addresses.
3. Fabricate the IP header with standard header structures but assign
our own values.
4. Fabricate the UDP header with source port number and destination port
number.
5. Calculate the checksum for integrity.
6. Build our own packet structure using setsockopt().
7. send for every 2 second for 100 count
8. Close socket.
Code:-
#include <unistd.h>
#include <iostream.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/ip.h>
#include <netinet/udp.h>
// The packet length
#define PCKT_LEN 8192
// Can create separate header file (.h) for all headers'
structure
// The IP header's structure
struct ipheader {
unsigned char iph_ihl:5, iph_ver:4;
unsigned char iph_tos;
unsigned short int iph_len;
unsigned short int iph_ident;
unsigned char iph_flag;
unsigned short int iph_offset;
unsigned char iph_ttl;
unsigned char iph_protocol;
unsigned short int iph_chksum;
unsigned int iph_sourceip;
unsigned int iph_destip;
17
};
// UDP header's structure
struct udpheader {
unsigned short int udph_srcport;
unsigned short int udph_destport;
unsigned short int udph_len;
unsigned short int udph_chksum;
};
// total udp header length: 8 bytes (=64 bits)
// Function for checksum calculation. From the RFC,
// the checksum algorithm is:
// "The checksum field is the 16 bit one's complement
of //the one's complement sum of all 16 bit words in
the //header. For purposes of computing the checksum,
the //value of the checksum field is zero."
unsigned short csum(unsigned short *buf, int nwords)
{ //
18
cout<<"- Invalid parameters!!!\n";
cout<<"- Usage %s <source hostname/IP> <source port> <target
hostname/IP> <target port>\n"<< argv[0];
exit(-1);
}
// Create a raw socket with UDP protocol
sd = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
if(sd < 0)
{
cout<<"socket() error";
// If something wrong just exit
exit(-1);
}
else
cout<<"socket() - Using SOCK_RAW socket and UDP protocol is
OK.\n";
// The source is redundant, may be used later if needed
// The address family
sin.sin_family = AF_INET;
din.sin_family = AF_INET;
// Port numbers
sin.sin_port = htons(atoi(argv[2]));
din.sin_port = htons(atoi(argv[4]));
// IP addresses
sin.sin_addr.s_addr = inet_addr(argv[1]);
din.sin_addr.s_addr = inet_addr(argv[3]);
// Fabricate the IP header or we can use the
// standard header structures but assign our own values.
ip->iph_ihl = 5;
ip->iph_ver = 4;
ip->iph_tos = 16; // Low delay
ip->iph_len = sizeof(struct ipheader) + sizeof(struct
udpheader);
ip->iph_ident = htons(54321);
ip->iph_ttl = 64; // hops
ip->iph_protocol = 17; // UDP
// Source IP address, can use spoofed address here!!!
ip->iph_sourceip = inet_addr(argv[1]);
// The destination IP address
ip->iph_destip = inet_addr(argv[3]);
// Fabricate the UDP header. Source port number, redundant
udp->udph_srcport = htons(atoi(argv[2]));
// Destination port number
udp->udph_destport = htons(atoi(argv[4]));
19
udp->udph_len = htons(sizeof(struct udpheader));
// Calculate the checksum for integrity
ip->iph_chksum = csum((unsigned short *)buffer,
sizeof(struct ipheader) + sizeof(struct udpheader));
// Inform the kernel do not fill up the packet structure. we
will build our own...
if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one))
< 0)
{
cout<<"setsockopt() error";
exit(-1);
}
else
cout<<"setsockopt() is OK.\n";
// Send loop, send for every 2 second for 100 count
cout<<"Trying...\n";
cout<<"Using raw socket and UDP protocol\n");
cout<<"Using Source IP: “<< arv[1]<<”
port:”<<atoi(argv[2])<<” Target IP:”<<argv[3]<<” port:”<<
atoi(argv[4]) \n;
int count;
for(count = 1; count <=20; count++)
{
if(sendto(sd, buffer, ip->iph_len, 0, (struct sockaddr
*)&sin, sizeof(sin)) < 0)
// Verify
{
Cout<<"sendto() error";
exit(-1);
}
else
{
Cout<<"Count #%u - sendto() is OK.\n" << count);
sleep(2);
}
}
close(sd);
return 0;
}
OUTPUT:-
20
- Usage ./rawudp <source hostname/IP> <source port> <target
hostname/IP> <target port>
[root@bakawali testraw]# ./rawudp 192.168.2.222 21
192.168.1.10 8080
socket() - Using SOCK_RAW socket and UDP protocol is OK.
setsockopt() is OK.
Trying...
Using raw socket and UDP protocol
Using Source IP: 192.168.10.10 port: 21, Target IP:
203.106.93.91 port: 8080.
Count #1 - sendto() is OK.
Count #2 - sendto() is OK.
Count #3 - sendto() is OK.
Count #4 - sendto() is OK.
Count #5 - sendto() is OK.
Count #6 - sendto() is OK.
Count #7 - sendto() is OK.
...
Result:
Thus the program was executed successfully.
21
Client server application Using RPC
Ex.6
AIM: To implement client server application (generating Fibonacci series) using RPC
ALGORITHM
1. Enter and compile the source codes. This application uses four
source files.
(i) The first code fie, intf.java defines the remote interface that is
provided by the server. It contains the method that accepts the number to generate
Fibonacci series. All remote methods can throw a RemoteException.
(ii) The second source file is, impl.java implements the remote interface,
which provides functionality that is needed to make objects available from remote
machines.
(iii) The third source file is rmis.java, contains main program of the server
machine. Its primary function is to update the RMI registry on that machine. This is done
by using the rebind() method of the Naming class. The first argument to the rebind()
method is a string that names the server as “rmis”. Its second argument is a reference to
an instance of “impl”.
(iv) The fourth source file is, rmic.java implements the client side of this
distributed application
2. Generate Stubs and skeletons
(i) A stub is a java object that resides on the client machine. Its function is
to represent the same interfaces as the remote server. Remote method
calls initiated by the client are actually directed to the stub.
(ii) A skeleton is a Java object that resides on the server machine. It works
with other parts of the 1.1 RMI system to receive requests, perform
deserialization, and invoke the appropriate code on the server. The
skeleton mechanism is not required for Java2 code.
(iii) To generate stubs and skeletons, use a tool called RMI complier,
which is invoked from the command tool as
rmic impl
This command generates two new lines impl_Skel.class(skeleton) and
impl_Stub.class(stub).
3. Install files on the client and server machines. (Note:- Client and server is in a
single machine, this step is not necessary)
(i) Copy rmic.class, impl_Stub.class and intf.class to a directory on the
client machine.
(ii) Copy rmis.class, impl.class, impl_Skel.class and intf.class to a
directory on the server machine
4. Start the RMI registry on the server machine (it maps names to object reference
accessing the remote names registered on the server and a security
manager for RMI(Remote Method Invocation)
start rmiregistry
5. Start the serve
java rmis
22
Recall that rmis code instantiates impl and registers that object with the name
“impl”
6. Start the client
java rmic
Enter the number to generate Fibonacci series, the server receives this
request from client, processes it, and returns a result to client.
INTERFACE
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface intf extends Remote
{
int[] fib(int a)throws RemoteException;
}
IMPLEMENTATION
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
public class impl extends UnicastRemoteObject implements intf
{
public impl() throws RemoteException
{
}
public int[] fib(int n)throws RemoteException
{
int fi=0,a=0,b=1,i;
int ab[]=new int[50];
for(i=0;i<n;i++)
{
fi=fi+a;
a=b;
b=fi;
ab[i]=fi;
}
return(ab); } }
CLIENT
import java.rmi.*;
import java.io.*;
public class rmic
{
23
public static void main(String ar[])
{
try
{
int i;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the server host name");
String serip=br.readLine();
String url="rmi://"+serip+"/rmis";
intf ref=(intf)Naming.lookup(url);
while(true)
{
System.out.println("Enter a number:");
String st=br.readLine();
if(st.equals("end"))
{
break;
}
else
{
int n=Integer.parseInt(st);
int aa[]=ref.fib(n);
for(i=0;i<n;i++)
{
System.out.println(aa[i]);
}
}
}
}
catch(Exception e)
{
}
}
}
SERVER
import java.net.UnknownHostException;
import java.rmi.Naming;
public class rmis
{
public static void main(String ar[])
{
try
{
impl im=new impl();
24
Naming.rebind("rmis",im);
System.out.println("Binding complete");
}
catch(Exception e)
{
}
}
}
OUTPUT:-
SERVER OUTPUT
C:\Java\jdk1.5.0\bin>javac intf.java
C:\Java\jdk1.5.0\bin>javac impl.java
C:\Java\jdk1.5.0\bin>javac rmis.java
C:\Java\jdk1.5.0\bin>rmic impl
C:\Java\jdk1.5.0\bin>start rmiregistry
C:\Java\jdk1.5.0\bin>java rmis
Binding complete
CLIENT OUTPUT
C:\Java\jdk1.5.0\bin>javac rmic.java
C:\Java\jdk1.5.0\bin>java rmic
Enter the server host name
localhost
Enter a number:
5
0
1
1
2
3
Enter a number:
exit
C:\Java\jdk1.5.0\bin>
Result:
Thus the program was executed successfully.
25
Ping command using RAW socket
Ex.7
ALGORITHM
Code:-
#include<iostream.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netdb.h>
#include<netinet/in.h>
#include<netinet/in_systm.h>
#include<netinet/ip.h>
#include<netinet/ip_icmp.h>
#include<string.h>
#include<arpa/inet.h>
int main(int argc, char *argv[])
{
int s, i;
char buf[400];
struct ip *ip = (struct ip *)buf;
struct icmphdr *icmp = (struct icmphdr *)(ip + 1);
struct hostent *hp, *hp2;
struct sockaddr_in dst;
int offset;
int on;
int num = 100;
if(argc < 3)
{
cout<<"\nUsage: <saddress> <dstaddress> [number]\n"<<
argv[0];
cout<<"- saddress is the spoofed source address\n";
26
cout<<"- dstaddress is the target\n";
cout<<"- number is the number of packets to send, 100
is the default\n";
exit(1);
}
/* If enough argument supplied */
if(argc == 4)
/* Copy the packet number */
num = atoi(argv[3]);
/* Loop based on the packet number */
for(i=1;i<=num;i++)
{
on = 1;
bzero(buf, sizeof(buf));
/* Create RAW socket */
if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
{
cout<<"socket() error";
/* If something wrong, just exit */
exit(1);
}
/* socket options, tell the kernel we provide the IP
structure */
if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on,
sizeof(on)) < 0)
{
cout<<"setsockopt() for IP_HDRINCL error";
exit(1);
}
if((hp = gethostbyname(argv[2])) == NULL)
{
if((ip->ip_dst.s_addr = inet_addr(argv[2])) == -1)
{
fprintf(stderr, "%s: Can't resolve, unknown
host.\n", argv[2]);
exit(1);
}
}
else
bcopy(hp->h_addr_list[0], &ip->ip_dst.s_addr, hp-
>h_length);
/* The following source address just redundant for
target to collect */
if((hp2 = gethostbyname(argv[1])) == NULL)
{
if((ip->ip_src.s_addr = inet_addr(argv[1])) == -1)
{
27
fprintf(stderr, "%s: Can't resolve, unknown
host\n", argv[1]);
exit(1);
}
}
else
bcopy(hp2->h_addr_list[0], &ip->ip_src.s_addr,
hp->h_length);
cout<<"Sending to" << inet_ntoa(ip->ip_dst)<<" from
spoofed "<< argv[1];
/* Ip structure, check the ip.h */
ip->ip_v = 4;
ip->ip_hl = sizeof*ip >> 2;
ip->ip_tos = 0;
ip->ip_len = htons(sizeof(buf));
ip->ip_id = htons(4321);
ip->ip_off = htons(0);
ip->ip_ttl = 255;
ip->ip_p = 1;
ip->ip_sum = 0; /* Let kernel fills in */
dst.sin_addr = ip->ip_dst;
dst.sin_family = AF_INET;
icmp->type = ICMP_ECHO;
icmp->code = 0;
/* Header checksum */
icmp->checksum = htons(~(ICMP_ECHO << 8));
for(offset = 0; offset < 65536; offset +=
(sizeof(buf) - sizeof(*ip)))
{
ip->ip_off = htons(offset >> 3);
if(offset < 65120)
ip->ip_off |= htons(0x2000);
else
ip->ip_len = htons(418); /* make total 65538 */
/* sending time */
if(sendto(s, buf, sizeof(buf), 0, (struct sockaddr
*)&dst, sizeof(dst)) < 0)
{
fprintf(stderr, "offset %d: ", offset);
perror("sendto() error");
}
else
printf("sendto() is OK.\n");
/* IF offset = 0, define our ICMP structure */
if(offset == 0)
{
icmp->type = 0;
28
icmp->code = 0;
icmp->checksum = 0;
}
}
/* close socket */
close(s);
usleep(30000);
}
return 0;
}
OUTPUT:-
sendto() is OK.
29
sendto() is OK.
...
...
sendto() is OK.
sendto() is OK.
sendto() is OK.
...
Result:
Thus the program was executed successfully.
30
Packet Capturing and Monitoring
Ex.8
ALGORITHM
import jpcap.*;
import jpcap.packet.Packet;
31
System.out.print(Integer.toHexString(b&0xff) + ":");
System.out.println();
for (NetworkInterfaceAddress a : devices[i].addresses)
System.out.println(" address:"+a.address + " " + a.subnet +
" "
+ a.broadcast);
}
}else{
JpcapCaptor jpcap =
JpcapCaptor.openDevice(devices[Integer.parseInt(args[0])],
2000, false, 20);
import java.net.InetAddress;
import jpcap.*;
import jpcap.packet.EthernetPacket;
import jpcap.packet.IPPacket;
import jpcap.packet.TCPPacket;
class SendTCP
{
public static void main(String[] args) throws
java.io.IOException{
NetworkInterface[] devices = JpcapCaptor.getDeviceList();
if(args.length<1){
System.out.println("Usage: java SentTCP <device index (e.g.,
0, 1..)>");
for(int i=0;i<devices.length;i++)
System.out.println(i+":"+devices[i].name+"("+devices[i].desc
ription+")");
System.exit(0);
}
int index=Integer.parseInt(args[0]);
JpcapSender sender=JpcapSender.openDevice(devices[index]);
TCPPacket p=new
TCPPacket(12,34,56,78,false,false,false,false,true,true,true
,true,10,10);
p.setIPv4Parameter(0,false,false,false,0,false,
false,false,0,1010101,100,IPPacket.IPPROTO_TCP,
InetAddress.getByName("www.microsoft.com"),
32
InetAddress.getByName("www.google.com"));
p.data=("data").getBytes();
for(int i=0;i<10;i++)
sender.sendPacket(p);
}
}
Output
1282048961:530746 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:530979 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:531203 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:531425 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:531641 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:531862 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:532080 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:532301 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:532520 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
33
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
1282048961:532740 /207.46.19.254->/209.85.231.104
protocol(6) priority(0) hop(1
00) offset(0) ident(27061) TCP 12 > 34 seq(56) win(10) S F
Other Window
C:\Program Files\Java\jdk1.6.0\bin>
Result:
Thus the program was executed successfully.
34
CBR over UDP and CBR over TCP
Ex.9
AIM: To simulate CBR over UDP and CBR over TCP using NS2
ALGORITHM
35
#Close the NAM trace file
close $nf
close $tracefile
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
$ns simplex-link $n0 $n1 1Mb 10ms DropTail
$ns run
36
OUTPUT:-
37
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
$ns simplex-link $n0 $n1 1Mb 10ms DropTail
$ns run
38
OUTPUT:-
Result:
Thus the program was executed successfully.
39
Implementing Routing protocols using NS2
Ex.10
ALGORITHM
1. Create a simulator object and Define different colors for data flows
(for NAM)
2. Open the NAM trace file
3. Define a 'finish' procedure for Close the trace file and Execute NAM
on the trace file
4. Create topology as four nodes n0, n1, n2 and n3 with a duplex link
between them.
5. Give node position (for NAM)
6. Set Queue Size of link (n2-n3) to 10
7. Monitor the queue for link (n2-n3). (for NAM)
8. Setup TCP connection and UDP connection
8. Setup a FTP over TCP connection and CBR over UDP connection
9. Schedule events for the CBR and FTP agents
10. Call the finish procedure after 5 seconds of simulation time
11. Print CBR packet size and interval
12. Run the simulation
Code:-
40
#Create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
41
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 1mb
$cbr set random_ false
42
OUTPUT:-
Result:
Thus the program was executed successfully.
43
Performance comparison of routing protocols
Ex.11
ALGORITHM
1. Create a simulator object and Define different colors for data flows
(for NAM)
2. Open the NAM trace file
3. Define a 'finish' procedure for Close the trace file and Execute NAM
on the trace file.
4. Call xgraph to display the results.
5. Create topology as five nodes as n0, n1, n2, n3 and n4. Connect a
duplex link between them.
6. Define a procedure 'attach-expoo-traffic' that attaches a UDP agent
to a previously created node 'node' and attaches an Expoo traffic
generator to the agent with the characteristic values 'size' for packet
size 'burst' for burst time, 'idle' for idle time and 'rate' for burst
peak rate. The procedure connects the source with the previously defined
traffic sink 'sink' and returns the source object.
7. Define a procedure 'record' which periodically records the bandwidth
received by the three traffic sinks sink0/1/2 and writes it to the three
files f0/1/2.
8. Calculate the bandwidth (in MBit/s) and write it to the files.
9. Re-schedule the procedure 'record' at regular intervals(0.5 seconds).
10. Create three traffic sources, start and stop traffic sources at
regular intervals respectively.
11. Call the finish procedure after 60 seconds of simulation time
12. Run the simulation
Code:-
44
#Define a 'finish' procedure
proc finish {} {
global f0 f1 f2
#Close the output files
close $f0
close $f1
close $f2
#Call xgraph to display the results
exec xgraph out0.tr out1.tr out2.tr -geometry 800x400 &
exit 0
}
45
#three traffic sinks sink0/1/2 and writes it to the three
#files f0/1/2.
proc record {} {
global sink0 sink1 sink2 f0 f1 f2
#Get an instance of the simulator
set ns [Simulator instance]
#Set the time after which the procedure should be called
#again
set time 0.5
#How many bytes have been received by the traffic sinks?
set bw0 [$sink0 set bytes_]
set bw1 [$sink1 set bytes_]
set bw2 [$sink2 set bytes_]
#Get the current time
set now [$ns now]
#Calculate the bandwidth (in MBit/s) and write it to the
files
puts $f0 "$now [expr $bw0/$time*8/1000000]"
puts $f1 "$now [expr $bw1/$time*8/1000000]"
puts $f2 "$now [expr $bw2/$time*8/1000000]"
#Reset the bytes_ values on the traffic sinks
$sink0 set bytes_ 0
$sink1 set bytes_ 0
$sink2 set bytes_ 0
#Re-schedule the procedure
$ns at [expr $now+$time] "record"
}
46
$ns at 50.0 "$source0 stop"
$ns at 50.0 "$source1 stop"
$ns at 50.0 "$source2 stop"
#Call the finish procedure after 60 seconds simulation time
$ns at 60.0 "finish"
#Run the simulation
$ns run
OUTPUT:-
Result:
Thus the program was executed successfully.
47
Ex.12
Sliding Window Protocol using NS2
ALGORITHM
CODE:-
#
Agent/TCP set tcpTick_ 0.1
# The default for tcpTick_ is being changed to reflect a changing
reality.
Agent/TCP set rfc2988_ false
# The default for rfc2988_ is being changed to true.
# FOR UPDATING GLOBAL DEFAULTS:
Agent/TCP set precisionReduce_ false ; # default changed on 2006/1/24.
Agent/TCP set rtxcur_init_ 6.0 ; # Default changed on 2006/01/21
Agent/TCP set updated_rttvar_ false ; # Variable added on 2006/1/21
Agent/TCP set minrto_ 1
# default changed on 10/14/2004.
Agent/TCP set useHeaders_ false
# The default is being changed to useHeaders_ true.
Agent/TCP set windowInit_ 1
# The default is being changed to 2.
48
Agent/TCP set singledup_ 0
# The default is being changed to 1
Class TestSuite
proc usage {} {
global argv0
puts stderr "usage: ns $argv0 <tests> "
puts "Valid <tests> : sliding-normal sliding-loss"
exit 1
}
49
}
$ns_ flush-trace
if { !$quiet } {
puts "running nam..."
exec nam temp.rands.nam &
}
exit 0
}
50
$self instvar ns_ testName_ flag_
set testName_ sliding-loss
set flag_ $flag
$self next
}
51
set t [new Test/$test 1]
}
default {
stderr "Unknown test $test"
exit 1
}
}
$ns run
}
global argv arg0
runtest $argv
OUTPUT:-
[root@localhost root]#
Result:
Thus the program was executed successfully.
52