Você está na página 1de 34

STUDY OF SOCKET PROGRAMMING AND CLIENT SERVER MODEL

EXNO:1(a)
A socket is an endpoint of a two-way communication link between two
programs running on the network. Socket is bound to a port number so that the TCP
layer can identify the application that data is destined to be sent. User-level
process/services generally use port number value. TCP provides a reliable, point-topoint communication channel

that

client-server

application

on the Internet use to

communicate with each other. Examples are FTP and Telnet.


To communicate over TCP, a client program and a server program establish
a connection to one another. Each program binds a socket to its end of the connection. A
server runs on a specific computer and has a socket that is bound to a specific
port number. The server waits, listening to the socket for a connection request from
the client.
THE CLIENT SERVER MODEL
Client Process
This is the process which typically makes a request for information. After getting the
response this process may terminate or may do some other processing.
For example: Internet Browser works as a client application which sends a request to
Web Server to get one HTML web page.
Server Process
This is the process which takes a request from the clients. After getting a request from
the client, this process will do required processing and will gather requested information and
will send it to the requestor client. Once done, it becomes ready to serve another client.
Server processes are always alert and ready to serve incoming requests.
For example: Web Server keeps waiting for requests from Internet Browsers and as
soon as it gets any request from a browser, it picks up a requested HTML page and sends it
back to that Browser.
Most interprocess communication uses the client server model. These terms refer to
the two processes which will be communicating with each other. One of the two processes,
the client, connects to the other process, the server, typically to make a request for
information. A good analogy is a person who makes a phone call to another person.
The steps involved in establishing a socket on the client side are as follows:
1.

Create a socket with the socket() system call.

2.

Connect the socket to the address of the server using the connect() system call.

3.

Send and receive data. There are a number of ways to do this, but the simplest
is to use the read() and write() system calls.

The steps involved in establishing a socket on the server side are as follows:
1.

Create a socket with the socket() system call.

2.

Bind the socket to an address using the bind() system call. For a server socket
on the Internet, an address consists of a port number on the host machine.

3.

Listen for connections with the listen() system call.

4.

Accept a connection with the accept() system call. This call typically blocks
until a client connects with the server.

5.

Send and receive data


There are two widely used socket types, stream sockets, and datagram sockets.

Stream sockets use TCP (Transmission Control Protocol), which is a reliable, stream oriented
protocol, and datagram sockets use UDP (Unix Datagram Protocol), which is unreliable and
message oriented.
DESCRIPTION
Socket function:
#include <sys/socket.h>
int socket(int family, int type, int protocol);
The family specifies the protocol family:
Family

Description

AF_INET

IPV4 protocol

AF_INET6

IPV6 protocol

AF_LOCAL

unix domain protocol

AF_ROUTE

routing sockets

AF_KEY

key socket

Type

Description

SOCK_STREAM

Stream description

SOCK_DGRAM

Datagram socket

SOCK_RAW

Raw socket

The protocol argument to the socket function is set to zero except for raw sockets.
Connect function:
The connect function is used by a TCP client to establish a connection with a TCP
server.

int connect(int sockfd, const struct sockaddr *servaddr, socklen_t addrlen);


Bind function:
The bind function assigns a local protocol address to a socket.
int bind(int sockfd, const struct sockaddr *myaddr, s ocklen_t addrlen);
Close function:
The normal UNIX close function is also used to close a socket and terminate a TCP
connection.
#include<unistd.h>
int close(int sockfd);
Return 0 if ok, -1 on error.
Listen function:
The second argument to this function specifies the maximum number of connection
that the kernel should queue for this socket.
int listen(int sockfd,int backlog);
Accept function:
The cliaddr and addrlen argument are used to ret urn the protocol address of the
connected peer processes (client).
int accept(int sockfd, struct sockaddr *cliaaddr, socklen_t *addrlen);
IPv4 Socket Address Structure:
An IPv4 socket address structure, commonly called an Internet socket address
structure, is named sockaddr_in and defined by including the <netinet/in.h> header.
struct in_addr
{
in_addr_t s_addr; /* network byte ordered */
};
struct sockaddr_in
{
uint8_t sin_len;

/* length of structure(16) */

sa_family_t sin_family;

/* AF_INET */

in_port_t sin_port;

/* 16-bit TCP or UDP port number*/ /* network byte ordered */

struct in_addr sin_addr;

/* 32-bit IPv4 address */ /*newtork byte ordered */

char sin_zero[8];

/* unused */

};

RESULT: Thus the socket programming and client server model has been studied.

EXNO:1(b)

APPLICATION USING TCP SOCKETS

MESSAGE TRANSFER USING TCP


AIM:
To write a TCP Socket program using C for message transfer between client and server.
ALGORITHM:SERVER:
1.Create a server socket using system call.
int socket(int family,int type,int protocol);
2.Bind the local IP address and port number using bind function.
int bind(int sockfd,(struct sockaddr*)addr,socklen_t len);
3.Select the number of clients who can can access the server using listen function.
int listen(sockfd,int backlog);
4.Accept the message bysetting length as sizeof and accept function.
int accept(int sockfd,struct sockaddr* address,socklen_len);
5.Receive the message using receive function.
int recv(int fd,char*buff,int size,int flag);
6.Close the server socket and connection socket.
close(int fd);

CLIENT:
1.create a socket using soicket function.
Int socket(int family,int type,int protocol);
2.connect the client with server using connection function.
int connect(int sockfd,struct sockaddr*addr,socklen_t len);
3.send the message to server using send function.
send(int fd,char*buff,int size,int flag);
4.close the client socket.
close(int fd);
SERVER PROGRAM:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
struct sockaddr_in serv,cli;
void main()
{
int sockfd,connfd,len;
char msg[20];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv.sin_family=AF_INET;
serv.sin_port=7786;
serv.sin_addr.s_addr=INADDR_ANY;
bind (sockfd,(struct sockaddr*)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
len=sizeof(struct sockaddr);
connfd=accept(sockfd,(struct sockaddr*)&cli,&len);
recv(connfd,msg,sizeof(msg),0);
printf(message received is%s,msg);
close(connfd);
}
CLIENT PROGRAM:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
void main()
{
struct sockaddr_in serv,cli;
int sockfd;
char msg[20];
sockfd=socket(AF_INET,SOCK_STREAM,0);

cli.sin_family=AF_INET;
cli.sin_port=7786;
cli.sin_addr.s_addr=INADDR_ANY;
connect(sockfd,(struct sockaddr*)&cli,sizeof(struct sockaddr));
printf("enter the data");
scanf("%s",&msg);
send(sockfd,msg,sizeof(msg),0);
close(sockfd);
}
OUTPUT:
CLIENT
sam@boss[share]$vi cli.c
sam@boss[share]$cc cli.c
sam@boss[share]$./a.out
enter the data welcome
SERVER
sam@boss[share]$vi serv.c
sam@boss[share]$cc serv.c
sam@boss[share]$./a.out
message received is welcome

RESULT:
Thus the client server message transfer using C is executed successfully.
EX NO:1(c)
APPLICATION USING UDP SOCKETS
FILE TRANSFER USING UDP
AIM:
To design UDP client and server application to transfer file.
ALGORITHM:
SERVER:
1)Declare the variable and structure for a server datagram socket using socket function
socket(int family,int type,int protocol);
2)Bind the local IP address to the port number using bind function
int bind(int sockfd,const struct.sockaddr* addr,socklen_t len);
3)Specify the number of client that the server can connect using listen function
int listen(int sockfd,int backlog);
4)After accepting,receive the message sent by the client using recv function
recvfrom(sockfd,rmsg,sizeof(rmsg),0,(struct sockaddr *)&cli,&len);
5)The charaters are fetched from file using 'fopen' and 'fgetc' function.
6)Then send the characters to the client using 'send' function.
sendto(sockfd,ch,sizeof(ch),0,(struct sockaddr *)&cli,len);
7)Close the server socket and connection socket
close(int fd);
CLIENT:
1)Create a datagram socket for client using socket function
int socket(int family,int type,int protocol);
2)Send the message to the server using send function
sendto(sockfd,ch,sizeof(ch),0,(struct sockaddr *)&cli,len);
3)Close the client socket
close(int fd);

4)The file name that is to be transferred is specified in the client side


5)The contents of the file is verified from the server side.
SERVER:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
void main()
{
struct sockaddr_in serv,cli;
int sockfd,len,i=0;
char rec[50],ch[50];
FILE *fp;
sockfd=socket(AF_INET,SOCK_DGRAM,0);
serv.sin_family=AF_INET;
serv.sin_port=3261;
serv.sin_addr.s_addr=INADDR_ANY;
bind(sockfd,(struct sockaddr *)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
len=sizeof(struct sockaddr);
recvfrom(sockfd,rec,sizeof(rec),0,(struct sockaddr *)&cli,&len);
printf("the file name is\n"); printf("%s\n",rec);
fp=fopen(rec,"r");
if(fp==NULL) {
printf("error"); exit(0); }
while(fgets(ch,50,fp)!=NULL) {
printf("%s",ch); }
fcloseall();
sendto(sockfd,ch,sizeof(ch),0,(struct sockaddr *)&cli,sizeof(struct sockaddr));
close(sockfd);
}
CLIENT:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
void main()
{
struct sockaddr_in cli,serv;
int sockfd,len;
char msg[50],rec[100];
sockfd=socket(AF_INET,SOCK_DGRAM,0);
cli.sin_family=AF_INET;

cli.sin_port=3261;
cli.sin_addr.s_addr=INADDR_ANY;
printf("enter the file name\n");
scanf("%s",msg);
sendto(sockfd,msg,sizeof(msg),0,(struct sockaddr *)&cli,sizeof(struct sockaddr));
printf("the received file content is\n");
len=sizeof(struct sockaddr);
recvfrom(sockfd,rec,sizeof(rec),0,(struct sockaddr *)&cli,&len);
printf("%s",rec);
close(sockfd);
}
OUTPUT:
SERVER:
sam@boss[share]$cc su.c
sam@boss[share]$./a.out
the file name is
test.txt
hi, welcome.
sam@boss[share]$
CLIENT:
sam@boss[share]$cc cu.c
sam@boss[share]$./a.out
enter the file name
test.txt
the received file content is
hi, welcome.
sam@boss[share]$

RESULT:
Thus the client-server communication has been executed successfully using UDP sockets.

EX NO:2

SOCKET PROGRAM FOR ECHO CLIENT SERVER USING TCP

AIM:
To implement echo client and server in C using TCP sockets.
ALGORITHM:
SERVER:
1.Create a server socket using system call.
int socket(int family,int type,int protocol);
2.bind the local IP address and port number using bind function.
int bind(int sockfd,(struct sockaddr*)addr,socklen_t len);
3.select the number of clients who can can access the server using listen function.
int listen(sockfd,int backlog);
4.accept the message bysetting length as sizeof and accept function.
int accept(int sockfd,struct sockaddr* address,socklen_len);
5.receive the message using receive function.
int recv(int fd,char*buff,int size,int flag);
6.close the server socket and connection socket.
close(int fd);
CLIENT:
1.create a socket using soicket function.
Int socket(int family,int type,int protocol);
2.connect the client with server using connection function.
int connect(int sockfd,struct sockaddr*addr,socklen_t len);
3.send the message to server using send function.
send(int fd,char*buff,int size,int flag);
4.close the client socket.
close(int fd);
SERVER PROGRAM:
#include<sys/socket.h>
#include<sys/types.h>

#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
main()
{
struct sockaddr_in serv,cli;
int sockfd,connfd,len;
char recvmsg[20],msg[15];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv.sin_family=AF_INET;
serv.sin_port=7823;
serv.sin_addr.s_addr=INADDR_ANY;
bind(sockfd,(struct sockaddr*)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
len=sizeof(struct sockaddr);
connfd=accept(sockfd,(struct sockaddr*)&cli,&len);
recv(connfd,recvmsg,sizeof(recvmsg),0);
printf("the received msg is %s",recvmsg);
send(connfd,recvmsg,sizeof(recvmsg),0);
close(connfd);
close(sockfd);
}
CLIENT PROGRAM:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
struct sockaddr_in cli;
void main()
{
int sockfd;
char msg[20],rmsg[15];
sockfd=socket(AF_INET,SOCK_STREAM,0);
cli.sin_family=AF_INET;
cli.sin_port=7823;
cli.sin_addr.s_addr=INADDR_ANY;
connect(sockfd,(struct sockaddr*)&cli,sizeof(struct sockaddr));
printf("enter the data ");
scanf("%s",&msg);
send(sockfd,msg,sizeof(msg),0);
recv(sockfd,&rmsg,sizeof(rmsg),0);
printf("the echo msg received from server is %s",rmsg);
close(sockfd);
}

OUTPUT:
CLIENT
sam@boss[share]$vi ecli.c
sam@boss[share]$cc ecli.c
sam@boss[share]$./a.out
enter the data Networks
echo message received from server is Networks
SERVER
sam@boss[share]$vi eser.c
sam@boss[share]$cc eser.c
sam@boss[share]$./a.out
the received message is Networks

RESULT:
Thus the echo client-server communication has been executed successfully using TCP
sockets.
EX.NO:3

IMPLEMENTATION OF SLIDING WINDOW

AIM:
To write a program to simulate a sliding window protocol that uses Selective repeat and
Go back-ARQ.
ALGORITHM:
CLIENT:
1) Create a socket for client using socket function
int socket(int family,int type,int protocol);
2)Indicate to sender, the readiness to accept frames.
3)Initialize receiver's expected frame sequence to 0.
4)Accept the incoming frame
5)If frame's sequence == receiver's sequence then go to step 6
6)Send an acknowledgement
7)Repeat step 3-6 until all frames are received in sequence and go to step 8
8)Discard frame, thereby force the sender to retransmit. Go to step 3.
9)Stop
SERVER:
1)Create a server socket using socket function
socket(int family,int type,int protocol);
2)Assume the sending window size as 6 (m=3)
3)If the receiver is ready, initialize sender's frame sequence to 0
4)Get data from user.
5)Send it to the receiver along with sequence number
6)Increment sequence number by 1.
7)Repeat step 4-6 until all frames have been sent.
8)Wait for acknowledgement
9)If all acknowledgements have arrived then go to step 11.
10)Set sequence number to earliest outstanding frame for which there is no ACK . Go to step
4.
11)Stop

PROGRAM:
CLIENT:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
main()
{
int sockfd,amount,i,w,a,ch;
char data[10][100],lost[20],st[10],si[10],s,g,choice[10];
struct sockaddr_in serv,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
cli.sin_family=AF_INET;
cli.sin_port=9960;
cli.sin_addr.s_addr=INADDR_ANY;
connect(sockfd,(struct sockaddr *)&cli,sizeof(struct sockaddr));
printf("enter the total amount of data to be send \n");
scanf("%d",&amount);
for(i=1;i<=amount;i++)
{
printf("enter the %d data to be send \n",i);
scanf("%s",data[i]);
}
printf("enter the window size");
scanf("%s",si);
send(sockfd,si,sizeof(si),0);
sscanf(si,"%d",&w);
for(i=0;i<w;i++)
{
send(sockfd,data[i],sizeof(data[i]),0);
}
read(sockfd,lost,sizeof(lost));
printf("lost frame is %s \n",lost);
sscanf(lost,"%d",&a);
printf("enter the choice \1.selective repeat \n 2.go back ARQ \n");
scanf("%s",choice);
send(sockfd,choice,sizeof(choice),0);
sscanf(choice,"%d",&ch);
switch(ch)
{
case 1:
send(sockfd,data[a],sizeof(data[a]),0);
break;
case 2:
for(i=a;i<=(w+(a-1));i++)
{

send(sockfd,data[i],sizeof(data[i]),0);
}
printf("the lost data is sent again \n");
break;
}
close(sockfd);
}
SERVER:
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
main()
{
int len,sockfd,connfd,i,n,c;
char rdata[10][100],rmsg[10][100],win[10],los[20],temp[10][100],ch[10],recmsg[10];
struct sockaddr_in serv,cli;
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv.sin_family=AF_INET;
serv.sin_port=9960;
serv.sin_addr.s_addr=INADDR_ANY;
bind(sockfd,(struct sockaddr*)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
len=sizeof(struct sockaddr);
connfd=accept(sockfd,(struct sockaddr*)&cli,&len);
read(connfd,win,sizeof(win));
sscanf(win,"%d",&n);
printf("%d",n);
for(i=1;i<=n;i++)
{
recv(connfd,rdata[i],sizeof(rdata[i]),0);
printf("the %d data send by the client is %s \n",i,rdata[i]);
}
printf("enter the lost data");
scanf("%s",&los);
write(connfd,los,sizeof(ch));
sscanf(ch,"%d",&c);
if(c==1)
{
recv(connfd,recmsg,sizeof(recmsg),0);
printf("the data received using selective repeat is %s",recmsg);
}
else
{
for(i=1;i<=n;i++)
{

recv(connfd,recmsg[i],sizeof(recmsg[i]),0);
strcpy(temp[i],rmsg[i]);
printf("the data recv is %s \n",temp[i]);
}
}
close(connfd);
close(sockfd);
}
OUTPUT:
CLIENT:
sam@boss[sha]$./a.out
enter the total amount of data to be send
5
enter the 1 data to be send
shali
enter the 2 data to be send
akshaya
enter the 3data to be send
raji
enter the 4 data to be send
jeni
enter the 5 data to be send
arvi
enter the window size 3
lost frame is 2
enter the choice 1-selective repeat 2-goback ARQ
2
the lost data is sent again
SERVER
sam@boss[sha]$./a.out
the 1 data sent by client is shali
the 2 data sent by the client is akshaya
the 3 data sent by the client is raji
enter the lost data 2
the data recv is shali
the data recv is akshaya
the data recv is raji

RESULT:
Thus sliding window protocol is simulated using Selective repeat and Go back-ARQ.
EX.NO:4

IMPLEMENTATION OF STOP AND WAIT

AIM:
To write a C program to simulate a Stop and Wait protocol.
ALGORITHM:
Sender
1. Create a server socket usimg socket system call
2. If the receiver is ready,initialize senders frame sequence.
3. Get data from user.
4. Send it to the receiver along with sequence number
5. Wait for acknowledgements.
6. If acknowledgements is received ,send the next frame of data.
7. Stop
Receiever
1. Indicate to sendr .the readiness to accept frames.
2. Initialize receievrs expected frmae sequence.
3. Accept the incoming frame
4. Send an acknowledgement.
5. Repeat stepd 3 and 4 until all frames are received in sequence.
6. Discard frame,thereby force the sender to retransmit
7. Stop.
PROGRAM:
SERVER:
#include<sys/socket.h>
#include<sys/types.h>
#include<stdlib.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
void main()
{
struct sockaddr_in cli,serv;
int sockfd,connfd,len,i,n,flag,x;
char ms[10][50],ack[40];

len=sizeof(struct sockaddr);
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv.sin_family=AF_INET;
serv.sin_port=9960;
serv.sin_addr.s_addr=INADDR_ANY;
bind(sockfd,(struct sockaddr*)&serv,sizeof(struct sockaddr));
listen(sockfd,5);
connfd=accept(sockfd,(struct sockaddr *)&cli,&len);
printf("Enter the limit\n");scanf("%d",&n);
printf("Enter the data\n");for(i=1;i<=n;i++)
{printf("%d",i);
scanf("%s",ms[i]);}//printf("Enter the num");//scanf("%d",x);
printf("End of Data");
for(i=1;i<=n;i++)
printf("%s",ms[i]);
flag=1;
for(i=1;i<=n;i++)
{
if(flag==1)
{
send(connfd,ms[i],sizeof(ms[i]),0);
flag=0;
}
recv(connfd,ack,sizeof(ack),0);
printf("%s",ack);
if((strcmp(ack,"yes"))==0)
flag=1;
else
{printf("Acknowlegment is not given\n");
flag=1;
continue;
}}
close(sockfd);
}
CLIENT:
#include<sys/types.h>
#include<netinet/in.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
int a[3];
struct sockaddr_in cli,serv;
int sockfd,c,i,n;
char msg[50][50],ac[10];
sockfd=socket(AF_INET,SOCK_STREAM,0);
cli.sin_family=AF_INET; cli.sin_port=9960; cli.sin_addr.s_addr=INADDR_ANY;
connect(sockfd,(struct sockaddr*)&cli,sizeof(struct sockaddr));

printf("Enter the limit\n");


scanf("%d",&n);
printf("The received data\n");
for(i=1;i<=n;i++) {recv(sockfd,msg[i],sizeof(msg[i]),0);
printf("%s",msg[i]);
printf("Enter the ack\n");
scanf("%s",ac);
send(sockfd,ac,sizeof(ac),0);
}
close(sockfd);
}

OUTPUT:
SERVER:
sam@boss[share]$vi sandws.c
sam@boss[share]$cc sandws.c
sam@boss[share]$cc sandws.c
sam@boss[share]$./a.out
Enter the limit 4
Enter the data
1a
2b
3c
4d
End of Data
abcd
yes
yes
yes
yes
CLIENT:
Enter the limit4
The received data a
Enter the ack yes b
Enter the ack yes c
Enter the ack yes d
Enter the ack yes

RESULT:
Thus the stop & wait program was executed successfully.

EX.NO:5

IMPLEMENTATION OF ERROR DETECTION AND CORRECTION


TECHNIQUES

AIM:
To write a C program to implement Error Detection and Correction Techniques.
PROGRAM:
#include<stdlib.h>
#include<stdio.h>
char data[5];
int encoded[8], edata[7], syndrome[3];
int hmatrix[3][7]= { 1,0,0,0,1,1,1,0,1,0,1,0,1,1,0,0,1,1,1,0,1};
char gmatrix[4][8]={ "0111000", "1010100", "1100010", "1110001"};
int main()
{
int i,j;
system("clear");
printf("Hamming Code --- Encoding\n");
printf("Enter 4 bit data : ");
scanf("%s",data);
printf("Generator Matrix\n");
for(i=0;i<4;i++)
printf("\t %s \n",gmatrix[i]);
printf("Encoded Data : ");
for(i=0;i<7;i++)
{
for(j=0;j<4;j++)
encoded[i]+=((data[j]- '0')*(gmatrix[j][i]- '0'));
encoded[i]=encoded[i]%2;
printf("%d",encoded[i]);
}
printf("\nHamming code --- Decoding\n");
printf("Enter Encoded bits as received : ");
for(i=0;i<7;i++)

scanf("%d",&edata[i]);
for(i=0;i<3;i++)
{
for(j=0;j<7;j++)
syndrome[i]=syndrome[i]+(edata[j]*hmatrix[i][j]);
syndrome[i]=syndrome[i]%2;
}
for(j=0;j<7;j++)
if ((syndrome[0]==hmatrix[0][j])&&(syndrome[1]==hmatrix[1][j])&&
(syndrome[2]==hmatrix[2][j]))
break;
if(j==7)
printf("Data is error free!!\n");
else {
printf("Error received at bit number %d of the data\n",j+1);
edata[j]=!edata[j];
printf("The Correct data Should be : ");
for(i=0;i<7;i++) printf(" %d ",edata[i]);
}
}
Output:
Hamming Code --- Encoding
Enter 4 bit data : 1001
Generator Matrix
0111000
1010100
1100010
1110001
Encoded Data : 1001001
Hamming code --- Decoding
Enter Encoded bits as received : 1
001001
Data is error free!!
Hamming Code --- Encoding
Enter 4 bit data : 1011
Generator Matrix
0111000
1010100
1100010
1110001
Encoded Data : 0101011
Hamming code --- Decoding
Enter Encoded bits as received : 0 1 0 1 0 1 0
Error received at bit number 7 of the data
The Correct data Should be : 0 1 0 1 0 1 1

RESULT:
Thus the Error detection and correction technique is implemented successfully.

EX.NO:6

IMPLEMENTATION OF ENCRYPTION AND DECRYPTION

AIM:
To write a C program to implement Encryption and Decryption.
PROGRAM:
#include <stdio.h>
#include <string.h>
void encrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] - key;
}
}
void decrypt(char password[],int key)
{
unsigned int i;
for(i=0;i<strlen(password);++i)
{
password[i] = password[i] + key;
}
}
int main()
{
char password[20] ;
printf("Enter the password: \n ");
scanf("%s",password);
printf("Passwrod = %s\n",password);
encrypt(password,0xFACA);
printf("Encrypted value = %s\n",password);
decrypt(password,0xFACA);

printf("Decrypted value = %s\n",password);


return 0;
}
Output:
Enter the password: Hello
Encrypted value = h
Decrypted value=Hello
RESULT:
Thus the encryption and decryption program was executed successfully.
EX.NO:7
IMPLEMENTATION OF HIGH LEVEL DATA LINK CONTROL
AIM:
To write a C program to implement High Level Data Link Control.
PROGRAM:
#include<stdio.h>
#include<string.h>
void main()
{
int i, j,count=0,nl;
char str[100];
printf("enter the bit string: ");
gets(str);
for (i=0;i<strlen(str);i++)
{
count=0;
for (j=i;j<=(i+5);j++)
{
if(str[j]=='1')
{
count++;
}
}
if(count==6)
{
nl=strlen(str)+2;
for (;nl>=(i+5);nl--)
{
str[nl]=str[nl-1];
}
str[i+5]='0';
i=i+7;
}
}

puts(str);
}
Output:
Enter the bit string: 0111101111101111110
01111011111011111010
RESULT:
Thus the High Level Data Link program was executed successfully.

EXNO: 8

STUDY OF NETWORK SIMULATOR (NS)

NS2 SIMULATOR
A simulator is a device, software or system which behaves or operates like a given
system when provided with a set of controlled inputs. The need for simulators is,
Provide users with practical feedback such as accuracy, efficiency, cost, etc., when
designing real world systems.
Permit system designers to study at several different levels of abstraction
Simulation can give results that are not experimentally measurable with our current
level of technology.
Simulations take the building/rebuilding phase out of the loop by using the model
already created in the design phase.
Effective means for teaching or demonstrating concepts to students.
A few popular network simulators are NS-2, OPNET, GLOMOSIM, etc. Network Simulator
NS2
NS2 is an object-oriented, discrete event driven network simulator developed at
UC Berkley written in C++ and OTcl. NS is primarily useful for simulating local and wide
area networks. NS2 is an open-source simulation tool that primarily runs on Linux
(cygwin for Windows). The features of NS2 are
Is a discrete event simulator for networking research
Works at packet level.
Provide support to simulate bunch of protocols like TCP, UDP, FTP, etc.
Simulate wired and wireless network.
Is a standard experiment environment in research community.
How to start:
First of all, you need to create a simulator object. This is done with the command.
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 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 starts nam.

proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0}
The next line tells the simulator object to execute the 'finish' procedure after 5.0 seconds of
simulation time.
$ns at 5.0 "finish"
ns provides you 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'. You are going to
get an error message like 'nam: empty trace file out.nam' though, because until now we haven't
defined any objects (nodes, links, etc.) or events.
You will have to use the code from this section as starting point in the other sections.
#Create a simulator object
set ns [new Simulator]
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the trace file
close $nf
#Execute nam on the trace file
exec nam out.nam &
exit 0
}
# Insert your own code for topology creation
# and agent definitions, etc. here
#Call the finish procedure after 5 seconds simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run
set n0 [$ns node]
set n1 [$ns node]
A new node object is created with the command '$ns node'. The above code creates two
nodes and assigns them to the handles 'n0' and 'n1'.

The next line connects the two nodes.


$ns duplex-link $n0 $n1 1Mb 10ms DropTail
This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with
the bandwidth 1Megabit, a delay of 10ms and a DropTail queue. Now you can save your file and
start the script with 'ns example1.tcl'. nam will be started automatically and you should see an
output that resembles the picture below.

Commands to create a link between nodes:


$ns_ simplex-link <node1> <node2> <bw> <delay> <qtype> <args>
This command creates an unidirectional link between node1 and node2 with specified
bandwidth (BW) and delay characteristics. The link uses a queue type of <qtype> and depending
on the queue type different arguments are passed through <args>.
$ns_ duplex-link <node1> <node2> <bw> <delay> <qtype> <args>
This creates a bi-directional link between node1 and node2. This procedure essentially
creates a duplex-link from two simplex links, one from node1 to node2 and the other from node2 to
node1. The syntax for duplex-link is same as that of simplex-link described above.
$ns_ simplex-link-op <n1> <n2> <op> <args>
This is used to set attributes for a simplex link. The attributes may be the orientation, color,
label, or queue-position.
$ns_ duplex-link-op <n1> <n2> <op> <args>
This command is used to set link attributes (like orientation of the links, color, label, or
queue-position) for duplex links.
Sending data:
The next step is to send some data from node n0 to node n1. In ns, data is always being sent
from one
'agent' to another. So the next step is to create an agent object that sends data from
node n0, and another agent object that receives the data on node n1.
#Create a UDP agent and attach it to node n0
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
# Create a CBR traffic source and attach it to udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic
generator to the UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be selfexplaining. The packet Size is being set to 500 bytes and a packet will be sent every 0.005 seconds
(i.e. 200 packets per second).
The next lines create a Null agent which acts as traffic sink and attach it to node n1.
set null0 [new Agent/Null]
$ns attach-agent $n1 $null0
Now the two agents have to be connected with each other.

$ns connect $udp0 $null0


And now we have to tell the CBR agent when to send data and when to stop sending. Note: It's
probably best to put the following lines just before the line '$ns at 5.0 "finish"'.
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
This code should be self-explaining again. Now you can save the file and start the
simulation again. When you click on the 'play' button in the nam window, you will see that after 0.5
simulation seconds, node 0 starts sending data packets to node 1. You might want to slow nam
down then with the 'Step' slider.

Now you start some experiments with nam and the Tcl script. You can click on any packet in
the nam window to monitor it, and you can also click directly on the link to get some graphs with
statistics. Try to change the 'packetsize_' and 'interval_' parameters in the Tcl script to see what
happens.

Agents
Agents represent endpoints where network-layer packets are constructed or consumed, and
are used in the implementation of protocols at various layers.
ns_ attach-agent <node> <agent>
This command attaches the <agent> to the <node>. We assume here that the <agent> has
already been created. An agent is typically created by
set agent [new Agent/AgentType]
where Agent/AgentType defines the class definiton of the specified agent type.
Topology
You will always have to create a simulator object, you will always have to start the
simulation with the same command, and if you want to run nam automatically, you will always
have to open a trace file, initialize it, and define a procedure which closes it and starts nam.
Now insert the following lines into the code to create four nodes.
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
The following piece of Tcl code creates three duplex links between the nodes.
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n3 $n2 1Mb 10ms DropTail
You can save and start the script now. You might notice that the topology looks a bit

awkward in nam. You can hit the 're-layout' button to make it look better, but it would be nice to
have some more control over the layout. Add the next three lines to your Tcl script and start it
again.
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right

After successful installation, path setting and validation, execute NS2 programs.
$ ns filename.tcl

RESULT:
Thus the introduction of network simulator was studied.

EX NO: 9

DISTANCE VECTOR PROTOCOL

AIM:
To simulate a link failure and to observe distance vector routing protocol in action.
ALGORITHM:
1. Create a simulator object.
2. Set routing protocol to Distance vector routing.
3. Trace packets on all links on to NAM trace and text trace file.
4. Define finish procedure to close files, flash tracing and run NAM.
5. Create 5 nodes.
6. Specify the link characteristics between the nodes.
7. Describe their layout topology as a octagon.
8. Add UDP agent for node n0.
9. Create CBR traffic on the top of UDP and set traffic parameters.
10. Add NULL agent to node n3.
11. Connect source and sink.
12. Schedule as follow:
a. Start traffic flow at 1.0
b. Down the link n1- n2 at 15.0.
c. Up the link n1- n2 at 25.0.
d. Call finish procedure at 35.0.
13. Start the scheduler.
14. Observe the traffic route when the link is up and down.
15. View the simulated events and trace file analyze it.
16. Stop.
PROGRAM:
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file

exec nam out.nam &


exit 0
}
for { set i 0 } { $i < 5} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 4} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(1) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 1Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 1Mb 10ms DropTail
$ns duplex-link $n(4) $n(1) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
$ns rtproto DV
$ns rtmodel-at 15.0 down $n(1) $n(2)
$ns rtmodel-at 25.0 up $n(1) $n(2)
$udp0 set fid_ 1
$ns color 1 Green
$ns at 1.0 "$cbr0 start"
$ns at 35 "finish"
#Run the simulation
$ns run

EXNO:10

LINK STATE ROUTING

AIM:
To simulate a link failure and to observe Link state routing protocol in action.
ALGORITHM:
1. Create a simulator object.
2. Set routing protocol to Distance vector routing.
3. Trace packets on all links on to NAM trace and text trace file.
4. Define finish procedure to close files, flash tracing and run NAM.
5. Create 5 nodes.
6. Specify the link characteristics between the nodes.
7. Describe their layout topology as a octagon.
8. Add UDP agent for node n0.
9. Create CBR traffic on the top of UDP and set traffic parameters.
10. Add NULL agent to node n3.
11. Connect source and NULL.
12. Schedule as follow:
a. Start traffic flow at 1.0
b. Down the link n1- n2 at 15.0.
c. Up the link n1- n2 at 2.0.
d. Stop traffic at 35.0.
e. Call finish procedure at 35.0.
13. Start the scheduler.

14. Observe the traffic route when the link is up and down.
15. View the simulated events and trace file analyze it.
16. Stop.

PROGRAM:
#Create a simulator object
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the NAM trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a 'finish' procedure
proc finish {} {
global ns nf
$ns flush-trace
#Close the NAM trace file
close $nf
#Execute NAM on the trace file
exec nam out.nam &
exit 0
}
for { set i 0 } { $i < 5} { incr i 1 } {
set n($i) [$ns node]}
for {set i 0} {$i < 4} {incr i} {
$ns duplex-link $n($i) $n([expr $i+1]) 1Mb 10ms DropTail }
$ns duplex-link $n(0) $n(1) 1Mb 10ms DropTail
$ns duplex-link $n(1) $n(2) 1Mb 10ms DropTail
$ns duplex-link $n(2) $n(3) 1Mb 10ms DropTail
$ns duplex-link $n(3) $n(4) 1Mb 10ms DropTail
$ns duplex-link $n(4) $n(1) 1Mb 10ms DropTail
set udp0 [new Agent/UDP]
$ns attach-agent $n(0) $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null]
$ns attach-agent $n(3) $null0
$ns connect $udp0 $null0
#set udp1 [new Agent/UDP]
#$ns attach-agent $n(1) $udp1
#set cbr1 [new Application/Traffic/CBR]
#$cbr1 set packetSize_ 500
#$cbr1 set interval_ 0.005
#$cbr1 attach-agent $udp1

#set null0 [new Agent/Null]


#$ns attach-agent $n(3) $null0
#$ns connect $udp1 $null0
$ns rtproto LS
$ns rtmodel-at 15.0 down $n(1) $n(2)
$ns rtmodel-at 25.0 up $n(1) $n(2)
$udp0 set fid_ 1
$ns color 1 Green
$ns at 1.0 "$cbr0 start"
$ns at 35 "finish"
#Run the simulation
$ns run

RESULT:
Thus the LINK STATE Routing program was executed successfully.

Você também pode gostar