Professional Documents
Culture Documents
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 :
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 :
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 :
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 :
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 :
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 :
CN/EXP
LAB OF EXPERIMENTS
ISSUE NO:
REVISION NO :
ISSUE DATE :
EFFECTIVE DATE :
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.