You are on page 1of 31

CN/EXP

LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :
Echo client and Echo server
Aim:
To create a server application capable of handling a client.
Algorithm:
TCP Server:
Step 1: Write a function to read a line from the client. .
Step 2: Create the socket and bind the server port.
Step 3: Connect to server port and receive the arguments.
Step 4: Read the data from the socket.
Step 5: Check if another line is still in buffer.
Step 6: Wait for more data to arrive on socket..
TCP Client:
Step 1: Create a socket and build any port number.
Step 2: Connect to the server.
Step 3: Send data to the server.
Step 4: Close the socket.
Sample Program:
tcp client.c
• Create a socket with a call to socket()
• Create and initialize a socket address structure with the address family
(AF_INET here), the server's remote IP address, and the port the server is list
ening on.
• Actively connect to the server by calling connect()
• Communicate with the server, and (in this case) allow the server to perf
orm the active close.
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{ int cd;
char c[3];
struct sockaddr_in server_address;
int servadd_len;
cd=socket(AF_INET,SOCK_STREAM,0);
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("127.0.0.1");
server_address.sin_port=5678;
servadd_len=sizeof(server_address);
connect(cd,(struct sockaddr*)&server_address,servadd_len);
write(cd,"ABC",3);
read(cd,c,3);
write(1,c,3);
write(1,"\n",1);
close(cd);
}
tcpserver.c
• Create a socket with a call to socket()
• Create and initialize a socket address strucure with the IP address set
to INADDR_ANY (the server will listen on any IP address) and the port to whichev
er one you wish to use.
• Call bind() to bind the socket address to the socket.
• Call listen() to indicate that this is a passive socket, that we want to
accept incoming requests rather than make outgoing ones.
• Enter a loop in which we:
1. Call accept() to wait for an incoming connection
2. Service the request on our new connection
3. close() our connection, and continue the loop to wait for a new one
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
int sd;
void sigint_handler(int i)
{
close(sd);
printf("Closed listening socket sd\n");
signal(SIGINT,SIG_DFL);
kill(getpid(),SIGINT);
}
int main()
{
int sessfd;
char c[3];
struct sockaddr_in server_address,client_address;
int servadd_len,cliadd_len;
sd=socket(AF_INET,SOCK_STREAM,0);
signal(SIGINT,sigint_handler);
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("127.0.0.1");
server_address.sin_port=5678;
servadd_len=sizeof(server_address);
cliadd_len=sizeof(client_address);
bind(sd,(struct sockaddr *)&server_address,servadd_len);
listen(sd,10);
while(1)
{
printf("Server Ready to accept requests.....\n");
sessfd=accept(sd,(struct sockaddr*)&client_address,&cliadd_len);
read(sessfd,c,3);
write(sessfd,c,3);
close(sessfd);
}
return(0);
}

OUTPUT:
SERVER:
SERVER READY TO ACCEPT CONNECTIONS
SERVER ACCEPTED A CONNECTION......
AFTER FIRST CALL RET -1::
Resource temporarily unavailable
Y
CLIENT:
Y
RESULT:
Thus the echo client and echo server program is executed and an
output is verified.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

File Transfer Using TCP protocol


Aim:
To write a program to transfer file using connection oriented service TCP\IP.
Algorithm:
Server:
STEP 1: Create a class for file server.
STEP 2: Create a Socket to accept the data stream.
STEP 3: Accept the stream from client using accept ( ) function.
STEP 4: Get the file name from the client through command line argument.
STEP 5: Display the file name.
STEP 6: Transfer the file content from the server to Client.
Client:
STEP 1: Create a class for file Client.
STEP 2: Create a Socket for client connection with the Server..
STEP 3: Read the content of the file from the server.
STEP 4: Display the content of the file.
STEP 5 Close the socket connection.
Sample Program:
Server:
#include<sys/socket.h> /* these are the needed header files */
#include<sys/types.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<fcntl.h>
#define SERVER_PORT 1500
int main(int argc,char **argv)
{
int sd,newsd,clilen,size,file2,count;
char buffer[200];
struct sockaddr_in cliaddr,servaddr; /client & server address informatio
n */
sd=socket(AF_INET,SOCK_STREAM,0); /*create the socket socket */
if(sd<0)
perror("Cannot create socket");
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERVER_PORT);

if(bind(sd,(struct sockaddr*) &servaddr,sizeof(servaddr)) < 0 ) /*call b


ind */
perror("cannot bind the port");
if(listen(sd,5) < 0)
perror("cannot listen");
clilen=sizeof(cliaddr);
newsd=accept(sd,(struct sockaddr*) &cliaddr,&clilen);/*call accept */
file2=creat(argv[1],O_WRONLY);
printf("file is created");
while(count!=0)
{
count=read(newsd,buffer,sizeof(buffer)); /*read the file
*/
write(file2,buffer,count); /*write the buffer content in
file2 */
}
close(newsd);
close(sd); /* close the socket */
}
Client:
#include<stdio.h> /* these are the needed header files */
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<netdb.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<fcntl.h>
#define SERVER_PORT 1500
int main(int argc,char **argv)
{
int sd,rc,file1,count=1;
char buffer[200];
struct sockaddr_in localaddr; /* client address information */
sd=socket(AF_INET,SOCK_STREAM,0); /* create the socket */
if (sd < 0 )
perror("socket cannot be created");
localaddr.sin_family=AF_INET;
localaddr.sin_port=htons(SERVER_PORT);
if(inet_pton(AF_INET,argv[1],&localaddr.sin_addr) <= 0)
printf("Error in inet_pton");
rc=connect(sd,(struct sockaddr*) &localaddr,sizeof(localaddr));
if(rc<0)
{
perror("Cannot connect");
exit(1);
}
file1=open(argv[2],O_RDONLY); /* open the file for reading */
if(file1<0)
printf("cannot open");
while(count==1)
{
count=read(file1,buffer,sizeof(buffer)); /*read the file */
write(sd,buffer,count);
}
close(sd); /*close the socket */
}

OUTPUT:
CLIENT:
Enter the file in home folder
ctc.c
SERVER:
The message is
Hai
Good morning.

RESULT:
Thus the file transfer using tcp program is executed and output
is verified.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Remote Command Execution


Aim:
To find the square root of a number using remote method invocation.
Algorithm:
RMI Interface:
STEP 1: Create a Remote Server interface that is derived from Remote cla
ss.
STEP 2: Create a method to find the square root of a number.
RMI Server:
STEP 1: Create a server class.
STEP 2: Create a logical name for server using rebind method.
STEP 3: Implement the method to find the square root of a number.
STEP 4: Bound the server.
RMI Client:
STEP 1: Define a class
STEP 2: Using the logical name specified in Remote server and connect client to
server.
STEP 3: Display the square root on client to server in the interface.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :
Develop a client/server application for Chat
Aim:
To develop a client/server application for chat.
Algorithm:
CLIENT:
STEP 1: Create a socket using socket () function to enable communication
between
client and server. The socket () function will return a file descriptor the valu
e of which is 3 when socket is created successfully. Since TCP is used, socket t
ype is specified as SOCK_STREAM.
STEP 2: Initialize the variables of the structure struct sock addr_in.
STEP 3: Connect the TCP client with the server using the connect () function. Th
e
Connect ()
function will return a file descriptor, the value of which is zero
when socket is
connected successfully.
STEP 4: Send the request to the server using write () function.
STEP 5: Receive the reply from the server using read () function.
STEP 6: Close the connection after the client server chat using close () functio
n.
SERVER:
STEP 1: Create a socket using socket () function to enable communication
between
client and server. The socket() function will return a file descriptor the value
of which is 3 when socket is created successfully. Since TCP is used socket t
ype is specified as SOCK_STREAM.
STEP 2: Initialise the variables of the structure struct sock addr_in.
STEP 3: The local protocol address is assigned to the socket using bind(
) function. It
will return zero if it is successfully binded to the client else it will return
-1.
STEP 4: listen() function makes the unconnected sockets to passive soc
kets so that
client’s requests for connection are accepted by the server. Backlog refers to
the maximum
Number of socket connections, the server can accept.
STEP 5: accept () function is used to accept the request from the client
. The accept ()
function will return a file descriptor the value of which is 4 when the reques
t
is accepted.
STEP 6: Receive the request from the client using read () function
STEP 7: Send the reply to the client using write () function.
STEP 8: Close the connection after the client server chat using close()
function.
Sample Program:
CLIENT-SERVER PROGRAM FOR CHATTING
SERVER:
#include<sys/socket.h>
#include<sys/types.h>
#include<unistd.h> /*These are the usual needed header files*/
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#define SERVER_PORT 1510
int main(int argc,char **argv)
{
int sd,newsd,clilen,rc,a=1; /* Socket file discriptor */
char msg[30],ser[30];
struct sockaddr_in cliaddr,servaddr;
sd=socket(AF_INET,SOCK_STREAM,0); /* Socket Creation */
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
servaddr.sin_port=htons(SERVER_PORT); /* Assigning th port number */
if(bind(sd,(struct sockaddr*) &servaddr,sizeof(servaddr)) < 0 )
perror("cannot bind the port"); /* socket binding */
if(listen(sd,5) < 0)
perror("cannot listen");
for(;;)
{
clilen=sizeof(cliaddr); /*Listen the requests from clients */
newsd=accept(sd,(struct sockaddr*) &cliaddr,&clilen);
if(newsd<0)
perror("cannot create new socket");
rc=recv(newsd,msg,30,0); /* Receives message from client */
msg[rc]= \0 ;
printf("client message = %s\n" ,msg);
printf("Enter message =");
scanf("%s",ser);
send(newsd,ser,50,0); /* Sends messages to the client */
close(newsd);
}
close (sd); /* Closing the socket */
}

CLIENT:
#include<stdio.h> /*These are the usual needed header fi
les*/
#include<sys/socket.h>
#include<netinet/in.h>
#include<sys/types.h>
#include<netdb.h> /* Needed for struct hostent */
#include<unistd.h>
#include<arpa/inet.h>
#define SERVER_PORT 1510
int main(int argc,char **argv)
{
int sd,rc,i,a=1,n;
char msg[30],loop[30];
struct sockaddr_in localaddr;
while(1)
{
sd=socket(AF_INET,SOCK_STREAM,0); /* creating socket system call */
if (sd < 0 )
perror("socket cannot be created");
localaddr.sin_family=AF_INET;
localaddr.sin_port=htons(SERVER_PORT); /* Server IP Address*/
if(inet_pton(AF_INET,argv[1],&localaddr.sin_addr) <= 0)
printf("Error in inet_pton"); /* connection establishment */
rc=connect(sd,(struct sockaddr*) &localaddr,sizeof(localaddr));
if(rc<0)
{
perror("Cannot connect");
exit(1);
}
printf("\nEnter :");
scanf("%s",loop);
send(sd,loop,30,0); /* Sends messages to the server */
printf("Client message:");
n=recv(sd,msg,30,0); /* Receives message from server */
msg[n]= \0 ;
printf("%s",msg);
close(sd); /* closes the connection */
}
}
Sample Input and Output
Server side
Icsenserv it2k266]$ ./chatserv
Waiting for data on the port TCP 1510
Client message = hai
Enter message = hai
Client message = welcome
Enter message = same
Client message = bye
Enter message =

Client side
[cse006]$. /chatcli 127.0.0.1
Enter: hai
Client message: hai
Enter: welcome
Client message: same
Enter: bye

RESULT:
Thus the client and server for chating is executed and the
output is verified.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Concurrent Echo Client/Server Using Socket


Aim:
To create a server application capable of handling multiple clients simultaneous
ly.
Definition: Concurrent server
A concurrent server has to be able to serve more than one client at a time.
Algorithm:
STEP1. Create an ECHO Server socket for handling multiple clients.
STEP2. Enter the server into an infinite loop that can receive the new connectio
n
request, creates a thread to handle the new connection and
then continues waiting for the
next connection.
STEP3: implement a client to send multiple requests to the server by running the
client server times.
STEP 4. Have one of the clients issue a request for a large message to be echoed
While the first client is being served, have the second request co
mpletes
while the first continues to run.
STEP 5. Close the connection.
tcp_ser_concur.c
• Create a socket with a call to socket()
• Create and initialize a socket address structure with the IP address set
to INADDR_ANY (the server will listen on any IP address) and the port to whiche
ver one you wish to use.
• Call bind() to bind the socket address to the socket.
• Call listen() to indicate that this is a passive socket, that we want to
accept incoming requests rather than make outgoing ones.
• Enter a loop in which we:
1. Call accept() to wait for an incoming connection
2. Service the request on our new connection
3. close() our connection, and continue the loop to wait for a new one
Sample Program:
Server:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <stdlib.h>
int sd;

void sigint_handler(int i)
{ close(sd);
printf("Closed listening socket sd\n");
signal(SIGINT,SIG_DFL);
kill(getpid(),SIGINT);
}
int main()
{i
nt sessfd;
char c[3];
struct sockaddr_in server_address,client_address;
int servadd_len,cliadd_len;
int rpid;
sd=socket(AF_INET,SOCK_STREAM,0);
signal(SIGINT,sigint_handler);
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("127.0.0.1");
server_address.sin_port=5678;
servadd_len=sizeof(server_address);
cliadd_len=sizeof(client_address);
bind(sd,(struct sockaddr *)&server_address,servadd_len);
listen(sd,10);
while(1)
{
printf("Server Ready to accept requests.....\n");
sessfd=accept(sd,(struct sockaddr*)&client_address,&cliadd_len);
rpid=fork();
if(rpid > 0)
{
close(sessfd);
continue;
} else if(rpid == 0)
{ read(sessfd,c,3);
write(sessfd,c,3);
close(sessfd);
exit(0);
}//ifelse
} //while
return(0);
}

Client:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main()
{ int cd;
char c[3];
struct sockaddr_in server_address;
int servadd_len;
cd=socket(AF_INET,SOCK_STREAM,0);
server_address.sin_family=AF_INET;
server_address.sin_addr.s_addr=inet_addr("127.0.0.1");
server_address.sin_port=5678;
servadd_len=sizeof(server_address);
connect(cd,(struct sockaddr*)&server_address,servadd_len);
write(cd,"ABC",3);
read(cd,c,3);
write(1,c,3);
write(1,"\n",1);
close(cd);
}

Sample Output:
OUTPUT:
SERVER:
SERVER READY TO ACCEPT CONNECTIONS
SERVER ACCEPTED A CONNECTION......
AFTER FIRST CALL RET -1::
Resource temporarily unavailable
Y
CLIENT:
Y
CLIENT:
Y

RESULT:
Thus the concurrent client server program is executed and an ou
tput is verified.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Applications using UDP Sockets


Develop a client that contacts a given DNS server to resolve a given hos
t name
Aim:
Developing a client application program that contacts a given DNS Server to reso
lve a given host name.
Algorithm:
1. Create a UDP socket in the client program.
2. Get the name of the host whose IP address is to resolve using DNS.
3. Pass this name to the DNS server through this socket.
4. The server will respond with the IP address of the host.
5. Receive the IP address and print it.
Sample Program:
DNS Server
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include"string.h"
#include"stdlib.h"
#include<unistd.h>
int main(int argc,char *argv[])
{
int sd,newsd,clilen,rd,bi,rs;
char ip[30];
struct sockaddr_in client,server,ipaddr;
struct hostent *h;
char msg[100],buff[100];
sd=socket(AF_INET,SOCK_STREAM,0);
server.sin_family=AF_INET;
server.sin_addr.s_addr=htonl(INADDR_ANY);
server.sin_port=htons(3002);
bind(sd,(struct sockaddr*)&server,sizeof(server));
listen(sd,1);
clilen=sizeof(client);
newsd=accept(sd,(struct sockaddr*)&client,&clilen);
rd=recv(newsd,msg,100,0);
h=gethostbyname(msg);
if(h==NULL)
{
strcpy(buff,"Enter valid host name");
send(newsd,buff,sizeof(buff),0);
close(sd);
exit(0);
}
ipaddr.sin_addr.s_addr=*(unsigned long*)h->h_addr_list[0];
sprintf(buff,"%s\n",inet_ntoa(ipaddr.sin_addr));
rs=send(newsd,buff,sizeof(buff),0);
close(newsd);
close(sd);
return 0;
}
DNS Client
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>
#include<stdio.h>
#include<unistd.h>
int main(int argc,char *argv[])
{
int sd,rs,ine,rc;
char buff[100];
int ip[30];
struct sockaddr_in local;
sd=socket(AF_INET,SOCK_STREAM,0);
local.sin_family=AF_INET;
local.sin_port=htons(3002);
inet_pton(AF_INET,"127.0.0.1",&local.sin_addr);
rc=connect(sd,(struct sockaddr*)&local,sizeof(local));
printf("Enter the host name to be resolved\n");
scanf("%s",buff);
rs=send(sd,buff,sizeof(buff),0);
rc=recv(sd,ip,sizeof(ip),0);
printf("IP address of the host is:%s\n",ip);
close(sd);
}
Sample output:

OUTPUT:
CLIENT:
Enter the host name to be resolved
stuserver-cc5-20
IP address of the host is : 192.168.5.24
SERVER:
Enter the host name to be resolved
stuserver-cc5-20
IP address of the host is : 192.168.5.24

RESULT:
Thus echo server and echo client program is executed and output is
verified.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Develop a client that contacts a given SNMP server to resolve a given host name

Aim:
Developing a client application program that contacts a given SNMP Server to res
olve a given host name.
Algorithm:
1. Create a UDP socket in the client program.
2. Get the name of the host whose IP address is to resolve using SNMP.
3. Pass this name to the SNMP server through this socket.
4. The server will respond with the IP address of the host.
5. Receive the IP address and print it.
Sample Program:
It initializes a session, adds a MIB in the current working directory to the MIB
tree, creates a GET PDU, packs 2 OIDs into the PDU, then sends a synchronous re
quest and returns the response and is finally processed.
#include <net-snmp/net-snmp-config.h>
#include <net-snmp/net-snmp-includes.h>
#include <string.h>
int main(int argc, char ** argv)
{
struct snmp_session session;
struct snmp_session *sess_handle;
struct snmp_pdu *pdu;
struct snmp_pdu *response;
struct variable_list *vars;
oid id_oid[MAX_OID_LEN];
oid serial_oid[MAX_OID_LEN];
size_t id_len = MAX_OID_LEN;
size_t serial_len = MAX_OID_LEN;
int status;
struct tree * mib_tree;
/*********************/

if(argv[1] == NULL){
printf("Please supply a hostname\n");
exit(1);
}
init_snmp("APC Check");
snmp_sess_init( &session );
session.version = SNMP_VERSION_1;
session.community = "public";
session.community_len = strlen(session.community);
session.peername = argv[1];
sess_handle = snmp_open(&session);
add_mibdir(".");
mib_tree = read_mib("PowerNet-MIB.txt");
pdu = snmp_pdu_create(SNMP_MSG_GET);
read_objid("PowerNet-MIB::upsBasicIdentModel.0", id_oid, &id_len);
snmp_add_null_var(pdu, id_oid, id_len);
read_objid("PowerNet-MIB::upsAdvIdentSerialNumber.0", serial_oid, &serial_len)
;
snmp_add_null_var(pdu, serial_oid, serial_len);
status = snmp_synch_response(sess_handle, pdu, &response);
for(vars = response->variables; vars; vars = vars->next_variable)
print_value(vars->name, vars->name_length, vars);
snmp_free_pdu(response);
snmp_close(sess_handle);
return (0);
}

This example can be compiled like this and run like this:
$ gcc `net-snmp-config --cflags` `net-snmp-config --libs` \
> `net-snmp-config --external-libs` snmp_test.c -o snmp_test
$ ./snmp_test apc
STRING: "Silcon DP340E"
STRING: "SE00XXXXXX "
CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Application using RAW Sockets


PING APPLICATION USING RAW SOCKET
Aim:
Developing a client application program that contacts a given ICMP Server to pin
g the client.
Algorithm:
1. Create a RAW socket in the client program.
2. Get the name of the host whose IP address is to resolve using ICMP.
3. Pass this name to the ICMP server through this socket.
4. The server will respond with the IP address of the host.
5. Receive the response and print it.
Sample Program:
/*****************************************************************************/
/*** myping.c ***/
/*** ***/
/*** Use the ICMP protocol to request "echo" from destination. ***/
/*****************************************************************************/
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#define PACKETSIZE 64
struct packet
{
struct icmphdr hdr;
char msg[PACKETSIZEsizeof(
struct icmphdr)];
};
int pid=1;
struct protoent *proto=NULL;
/*checksum standard 1s complement checksum */
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b;
unsigned int sum=0;
unsigned short result;
for ( sum = 0; len > 1; len =2 )
sum += *buf++;
if ( len == 1 )
sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
/**/
/*display
present
echo info */
/**/
void display(void *buf, int bytes)
{ int i;
struct iphdr *ip = buf;
struct icmphdr *icmp = buf+ip>
ihl*4;
/* printf("\
n");
for ( i = 0; i < bytes; i++ )
{
if ( !(i & 15) ) printf("\n#X: ", i);
printf("#X ", ((unsigned char*)buf)[i]);
}*/
printf("\n");
printf("IPv%d: hdrsize=%
d pktsize=%
d protocol=%d TTL=%d src=%s ",
ip>
version, ip>
ihl*4, ntohs(ip>
tot_len), ip>
protocol,
ip>
ttl, inet_ntoa(ip>
saddr));
printf("dst=%s\n", inet_ntoa(ip>
daddr));
if ( icmp>
un.echo.id == pid )
{
printf("ICMP: type[%d/%d] checksum[%d] id[%d] seq[%d]\n",
icmp>
type, icmp>
code, ntohs(icmp>
checksum),
icmp>
un.echo.id, icmp>
un.echo.sequence);
}
}
/**/
/*listener separate process to listen for and collect messages*/
/**/
void listener(void)
{ int sd;
struct sockaddr_in addr;
unsigned char buf[1024];
sd = socket(PF_INET, SOCK_RAW, proto>
p_proto);
if ( sd < 0 )
{
perror("socket");
exit(0);
} for (;;)
{ int bytes, len=sizeof(addr);
bzero(buf, sizeof(buf));
bytes = recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr*)&addr, &len);
if ( bytes > 0 )
display(buf, bytes);
else
perror("recvfrom");
} exit(0);
}
/**/
/*ping Create message and send it. */
/**/
void ping(struct sockaddr_in *addr)
{ const int val=255;
int i, sd, cnt=1;
struct packet pckt;
struct sockaddr_in r_addr;
sd = socket(PF_INET, SOCK_RAW, proto>
p_proto);
if ( sd < 0 )
{
perror("socket");
return;
}
if ( setsockopt(sd, SOL_IP, IP_TTL, &val, sizeof(val)) != 0)
perror("Set TTL option");
if ( fcntl(sd, F_SETFL, O_NONBLOCK) != 0 )
perror("Request nonblocking I/O");
for (;;)
{ int len=sizeof(r_addr);
printf("Msg #%d\n", cnt);
if ( recvfrom(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)&r_addr, &len) > 0 )
printf("***Got message!***\n");
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = ICMP_ECHO;
pckt.hdr.un.echo.id = pid;
for ( i = 0; i < sizeof(pckt.msg)1;
i++ )
pckt.msg[i] = i+ 0 ;
pckt.msg[i] = 0;
pckt.hdr.un.echo.sequence = cnt++;
pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)addr, sizeof(*addr)) <
= 0 )
perror("sendto");
sleep(1);
}
}
/**/
/*main look up host and start ping processes. */
/**/
int main(int count, char *strings[])
{ struct hostent *hname;
struct sockaddr_in addr;
if ( count != 2 )
{
printf("usage: %s <addr>\n", strings[0]);
exit(0);
}
if ( count > 1 )
{
pid = getpid();
proto = getprotobyname("ICMP");
hname = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = hname>
h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname>
h_addr;
if ( fork() == 0 )
listener();
else
ping(&addr);
wait(0);
}
else
printf("usage: myping <hostname>\n");
return 0;}
CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

TRACE ROUTE APPLICATION USING RAW SOCKET

Aim:
Developing a client application program that contacts a given ICMP Server to tra
ce a route from the given host name.
Algorithm:
1. Create a RAW socket in the client program.
2. Get the name of the host whose IP address is to resolve using ICMP.
3. Write a traceroute() function to reach the destination
4. The server will respond with the Port number of the host.
5. Receive the IP address and print it.
Sample Program
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/socket.h>
#include <resolv.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/ip_icmp.h>
#define PACKETSIZE 64
struct packet
{
struct icmphdr hdr;
char msg[PACKETSIZE-sizeof(struct icmphdr)];
};
int pid=-1;
struct protoent *proto=NULL;
/*---------------------------------------------------------------------*/
/*--- checksum - standard 1s complement checksum ---*/
/*---------------------------------------------------------------------*/
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b;
unsigned int sum=0;
unsigned short result;
for ( sum = 0; len > 1; len -= 2 )
sum += *buf++;
if ( len == 1 )
sum += *(unsigned char*)buf;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
result = ~sum;
return result;
}
/*---------------------------------------------------------------------*/
/*--- traceroute - incrementally try to reach the destination ---*/
/*---------------------------------------------------------------------*/
void traceroute(struct sockaddr_in *addr)
{ const int yes=1;
int TTL=0;
int i, sd, cnt=1;
struct packet pckt;
unsigned char buf[1024];
struct sockaddr_in r_addr;
sd = socket(PF_INET, SOCK_RAW, proto->p_proto);
if ( sd < 0 )
{
perror("socket");
return;
}
if ( setsockopt(sd, SOL_IP, SO_ERROR, &yes, sizeof(yes)) != 0 )
perror("Set getting socket errors");
do
{ int len=sizeof(r_addr);
struct iphdr *ip;
TTL++;
if ( setsockopt(sd, SOL_IP, IP_TTL, &TTL, sizeof(TTL)) != 0)
perror("Set TTL option");
bzero(&pckt, sizeof(pckt));
pckt.hdr.type = ICMP_ECHO;
pckt.hdr.un.echo.id = pid;
for ( i = 0; i < sizeof(pckt.msg)-1; i++ )
pckt.msg[i] = i+ 0 ;
pckt.msg[i] = 0;
pckt.hdr.un.echo.sequence = cnt++;
pckt.hdr.checksum = checksum(&pckt, sizeof(pckt));
if ( sendto(sd, &pckt, sizeof(pckt), 0, (struct sockaddr*)addr,
sizeof(*addr)) <= 0 )
perror("sendto");
if ( recvfrom(sd, buf, sizeof(buf), 0, (struct sockaddr*)&r_addr
, &len) > 0 )
{ struct hostent *hname;
ip = (void*)buf;
printf("Host #%d: %s \n", cnt-1, inet_ntoa(ip->saddr));
hname = gethostbyaddr((void*)&r_addr, len, r_addr.sin_fa
mily);
if ( hname != NULL )
printf("(%s)\n", hname->h_name);
else
perror("Name");
}
else
perror("recvfrom");
}
while ( r_addr.sin_addr.s_addr != addr->sin_addr.s_addr );
close(sd);
}
/*---------------------------------------------------------------------*/
/*--- main - set up port and run. ---*/
/*---------------------------------------------------------------------*/
int main(int count, char *strings[])
{ struct hostent *hname;
struct sockaddr_in addr;
if ( count != 2 )
{
printf("usage: %s <addr>\n", strings[0]);
exit(0);
}
if ( count > 1 )
{
pid = getpid();
proto = getprotobyname("ICMP");
hname = gethostbyname(strings[1]);
bzero(&addr, sizeof(addr));
addr.sin_family = hname->h_addrtype;
addr.sin_port = 0;
addr.sin_addr.s_addr = *(long*)hname->h_addr;
traceroute(&addr);
}
else
printf("usage: myping <hostname>\n");
return 0;
}
CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Remote Procedure Call (RPC)


Introduction
What Is RPC?
RPC is a powerful technique for constructing distributed, client-server based ap
plications. It is based on extending the notion of conventional, or local proced
ure calling, so that the called procedure need not exist in the same address spa
ce as the calling procedure. The two processes may be on the same system, or the
y may be on different systems with a network connecting them. By using RPC, prog
rammers of distributed applications avoid the details of the interface with the
network. The transport independence of RPC isolates the application from the phy
sical and logical elements of the data communications mechanism and allows the a
pplication to use a variety of transports.
RPC makes the client/server model of computing more powerful and easier to progr
am. When combined with the ONC RPCGEN protocol compiler clients transparently ma
ke remote calls through a local procedure interface.
Objective:
To establish an serve on the remote machine that can respond to queries.
Procedure:
A client/server lookup in a personal database on a remote machine. Assuming that
we cannot access the database from the local machine (via NFS).
We use UNIX to run a remote shell and execute the command this way. There are so
me problems with this method:
• the command may be slow to execute.
• You require an login account on the remote machine.
The RPC alternative is to
• establish an server on the remote machine that can repond to queries.
• Retrieve information by calling a query which will be quicker than previ
ous approach.
To develop an RPC application the following steps are needed:
• Specify the protocol for client server communication
• Develop the client program
• Develop the server program
The programs will be compiled seperately. The communication protocol is achieved
by generated stubs and these stubs and rpc (and other libraries) will need to b
e linked in.

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

Study of Network Simulators like NS2.


Aim:
To perform a case study on Network simulator
Description:
The purpose of these pages is to make it easier for new ns users to use ns and
nam, to create their own simulation scenarios for these tools and to eventually
add new functionality to ns. I have found the existing documentation to be rathe
r useful for users who already know the basic features of ns, while it can be a
bit tedious for new users to extract the necessary information from the manuals
and the example scripts. In this tutorial I will lead you through some simple ex
amples, introducing more and more new features as we go along. The ultimate goal
is that after a short time you are able to efficiently use ns and to find any f
urther information you might need in the existing documentation. For this purpos
e I will also try to tell you where I found the information in this tutorial mys
elf, so you not only learn how to use ns, but also how to use its documentation.
Starting ns
You start ns with the command ns <tclscript> (assuming that you are in the dir
ectory with the ns executable, or that your path points to that directory), wher
e <tclscript> is the name of a Tcl script file which defines the simulation sc
enario (i.e. the topology and the events). You could also just start ns without
any arguments and enter the Tcl commands in the Tcl shell, but that is definitel
y less comfortable. Everything else depends on the Tcl script. The script might
create some output on stdout, it might write a trace file or it might start nam
to visualize the simulation. Or all of the above. These possibilities will all b
e discussed in later sections.
Starting nam
You can either start nam with the command nam <nam-file> where <nam-file> is
the name of a nam trace file that was generated by ns, or you can execute it di
rectly out of the Tcl simulation script for the simulation which you want to vis
ualize.

The first Tcl script


Now we are going to write a template that you can use for all of the first Tcl
scripts. You can write your Tcl scripts in any text editor like joe or emacs. I
suggest that you call this first example example1.tcl .
First of all, you need to create a simulator object. This is done with the comma
nd
set ns [new Simulator]
Now we open a file for writing that is going to be used for the nam trace data.
set nf [open out.nam w]
$ns namtrace-all $nf
The first line opens the file out.nam for writing and gives it the file handle
nf . In the second line we tell the simulator object that we created above to
write all simulation data that is going to be relevant for nam into this file.
The next step is to add a finish procedure that closes the trace file and star
ts nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
You don t really have to understand all of the above code yet. It will get clear
er to you once you see what the code does.
The next line tells the simulator object to execute the finish procedure after
5.0 seconds of simulation time.
$ns at 5.0 "finish"
You probably understand what this line does just by looking at it. ns provides y
ou with a very simple way to schedule events with the at command.
The last line finally starts the simulation.
$ns run
You can actually save the file now and try to run it with ns example1.tcl .
CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :

PERFORMANCE COMPARISON OF MAC PROTOCOLS


AIM:
To write a program to perform comparison of MAC protocols
ALGORITHM:
Step 1: Start the program
Step 2: First run the server program.
Step 3: Then run the client program
Step 4: Enter the Host Address
Step 5: Get the IP Address.
Step 6: Execute the program.
Step 7: Stop the program
CLIENT PROGRAM:
import java.io.*;
import java.net.*;
class clientmac
{
public static void main(String args[]) throws Exception
{
String mac[]={"00-Do-09-Do-22-48"};
String ip[]={"192.168.0.42"};
DatagramSocket ds=new DatagramSocket(1234);
DatagramPacket udp=new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),
1235);
ds.receive(udp);
String s=new String(udp.getData(),0,udp.getLength());
int i=0;
while(i<=2)
{
if(ip[i].compareTo(s)==0)
{
buf=mac[i].getBytes();
udp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127.0.0.255"),12
35);
ds.send(udp);
}
i++;
}}}

SERVER PROGRAM:
import java.io.*;
import java.net.*;
class mac
{
public static void main(String args[]) throws Exception
{
DataInputStream dis=new DataInputStream(System.in);
byte buf[]=new byte[1028];
String s="192.168.0.42",s2="192.168.0.42";
buf=s.getBytes();
DatagramPacket udp=new DatagramPacket(buf,buf.length,InetAddress.getByName("127
.0.0.25"),(1235));
DatagramSocket ds=new DatagramSocket(1235);
ds.send(udp);
buf=new byte[1024];
udp=new DatagramPacket(buf,buf.length,InetAddress.getLocalHost(),1234);
ds.receive(udp);
s=new String(udp.getData(),0,udp.getLength());
System.out.println("The mac address of ip"+s2+"is"+s);
}
}
OUTPUT:

CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :
CLIENT SERVER CHAT USING UDP

Aim:
To write a C program to implement User Datagram Protocol for client server
chatting.
Algorithm:
CLIENT:
Step 1 : Create a socket using socket() function to enable communication between
client and server. The socket() function will return a file descriptor
the value of
which is 3 when socket is created successfully.Since UDP is used socket
type is
specified as SOCK_DGRAM.
Step 2 : Initialise the variables of the structure struct sock addr_in.
Step 3 : Send the request to the server using sendto() function.
Step 4 : Receive the reply from the server using recvfrom() function.
Step 5 : Close the connection after the client server chat using close() functio
n.
SERVER:
Step 1 : Create a socket using socket() function to enable communication between
client and server. The socket() function will return a file descriptor the val
ue of which is 3 when socket is created successfully. Since UDP is used socket t
ype is specified as SOCK_ DGRAM.
Step 2 : Initialise the variables of the structure struct sock addr_in.
Step 3 : The local protocol address is assigned to the socket using bind() funct
ion. It will return zero if it is successfully binded to the client else it will
return -1.
Step 4 : Receive the request from the client using recvfrom() function
Step 5 : Send the reply to the client using sendto() function.
Step 6 : Close the connection after the client server chat using close() functio
n.

Program:
CLIENT
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdio.h>
#include<unistd.h>
#include<arpa/inet.h>
int main()
{
int sid,cid,i;
struct sockaddr_in a;
char msg1[100],msg2[100];
socklen_t len;
sid=socket(AF_INET,SOCK_DGRAM,0);
if(sid<0)
printf("Socket not created");
else
a.sin_family=AF_INET;
a.sin_port=htons(5229);
a.sin_addr.s_addr=htonl(INADDR_ANY);
printf("Socket Created\n");
for(;;)
{
printf("\nClient:");
fgets(msg1,sizeof(msg1),stdin);
len=sizeof(a);
sendto(sid,msg1,sizeof(msg1),0,(struct sockaddr *)&a,len);
recvfrom(sid,msg2,sizeof(msg2),0,(struct sockaddr *)&a,&len);
printf("\nServer:");
fputs(msg2,stdout);
}
close(sid);
}
SERVER
#include<sys/socket.h>
#include<stdio.h>
#include<unistd.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{
int sid,aid,bid,i;
struct sockaddr_in a,c;
char msg1[100],msg2[100];
socklen_t len;
sid=socket(AF_INET,SOCK_DGRAM,0);
if(sid<0)
printf("Socket not created");
else
printf("\nSID=%d\t",sid);
a.sin_family=AF_INET;
a.sin_port=htons(5227);
a.sin_addr.s_addr=htonl(INADDR_ANY);
bid=bind(sid,(struct sockaddr *)&a,sizeof(a));
printf("BID=%d\t",bid);
for(;;)
{
len=sizeof(a);
recvfrom(sid,msg2,sizeof(msg2),0,(struct sockaddr *)&c,&len);
printf("\nClient:");
fputs(msg2,stdout);
printf("\nServer:");
fgets(msg1,sizeof(msg1),stdin);
sendto(sid,msg1,sizeof(msg1),0,(struct sockaddr *)&c,len);
}
close(sid);
}
Output:
Server:
SID=3 BID=0
Client:hai
Server:hello
Client:Bye
Client:
Socket Created
Client: hai
Server: hello
Client :Bye

Result:
Thus a program is written to implement User Datagram Protocol for client
server chatting using UNIX operating system.

You might also like