Networks C Progs
Transcript of Networks C Progs
Network Programming Laboratory CSE Department
//Program 1:Implementation of CRC-CCITT-16 using shift register for // error detection.
#include<stdio.h>#include<stdlib.h>static int R=0,Gr1=0x8810; //G=0x11021
void UpdateCRC(short x){
short i=0, x_msb;while(i++ < 8) { x_msb = (x >> 7) & 1; /* k=msb of x*/
if (R & 0x8000) /* is msb of R == 1? */R = ((R ^ Gr1) << 1) + (x_msb ^ 1); //XOR G & R
elseR = (R << 1) + x_msb;
x <<= 1;} }
int main(){ short c,opt;
FILE *fp;while(1)
{printf("\n\t\t Menu:\n1: Transmit Message\t2: Check CRC\t3: Exit\nEnter your option:");scanf("%d",&opt);switch(opt)
{ case 1: if( (fp = fopen("tmp","w")) == NULL)
printf("cannot open 'tmp' file."), exit(1);R=0; //ResetCRC Registerprintf("Enter the text to transmit:\n");while ((c=getchar()) != EOF)
UpdateCRC(c),putc(c,fp);
UpdateCRC(0); UpdateCRC(0);putc(((R >> 8) & 0xff), fp); //append CRC to fileputc((R & 0xff), fp);printf("\nMessage Transmited Successfully\n");fclose(fp);break;
case 2: if( (fp = fopen("tmp","r")) == NULL)printf("cannot open 'tmp' file."), exit(1);
R=0; //ResetCRC Registerwhile ((c=getc(fp)) != EOF)
UpdateCRC(c);//Check computed vs original CRCprintf(R==0? "No errors detected.\n":"Error in Transmission\n");close(fp);break;
default:exit(0); }
} }
1
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog1-crc.c[user@localhost cnlab]$ ./a.out
Menu:1: Transmit Message 2: Check CRC 3: Exit
enter option:1Enter the text to transmit:hello, how are you?
Message Transmited Successfully
Menu:1: Transmit Message 2: Check CRC 3: ExitEnter your option:2No errors detected.
Menu:1: Transmit Message 2: Check CRC 3: ExitEnter your option:3
2
Network Programming Laboratory CSE Department
// Program 2: Frame sorting technique used in buffers.
#include<stdio.h>#include<string.h>#define FRAM_TXT_SIZ 3#define MAX_NOF_FRAM 127
char str[FRAM_TXT_SIZ*MAX_NOF_FRAM];
struct frame // structure maintained to hold frames
{ char text[FRAM_TXT_SIZ];int seq_no;
}fr[MAX_NOF_FRAM], shuf_ary[MAX_NOF_FRAM];
void display(char* msg,int no_frames){
int i;printf("%s",msg);for(i=0; i<no_frames;i++)
printf("%s",shuf_ary[i].text);}
int assign_seq_no() //function which splits message
{ int k=0,i,j; //into frames and assigns sequence no
for(i=0; i < strlen(str); k++){ fr[k].seq_no = k;
for(j=0; j < FRAM_TXT_SIZ && str[i]!='\0'; j++) fr[k].text[j] = str[i++];}printf("\nAfter assigning sequence numbers:\n");for(i=0; i < k; i++)
printf("%d:%s ",i,fr[i].text);return k; //k gives no of frames
}
void generate(int *random_ary, const int limit) //generate array of random nos{ int r, i=0, j;
while(i < limit){ r = random() % limit;
for(j=0; j < i; j++)if( random_ary[j] == r )
break;if( i==j ) random_ary[i++] = r;
} }
void shuffle( const int no_frames ) // function shuffles the frames
{ int i, k=0, random_ary[no_frames];
generate(random_ary, no_frames);
3
Network Programming Laboratory CSE Department
for(i=0; i < no_frames; i++)shuf_ary[i] = fr[random_ary[i]];
printf("\n\nAFTER SHUFFLING:\n");for(i=0; i < no_frames; i++)
printf("%d:%s ",shuf_ary[i].seq_no,shuf_ary[i].text);}void sort(const int no_frames) // sorts the frames
{ int i,j,flag=1;struct frame hold;
for(i=0; i < no_frames-1 && flag==1; i++) // search for frames in sequence{ flag=0; for(j=0; j < no_frames-1-i; j++) //(based on seq no.)and display
if(shuf_ary[j].seq_no > shuf_ary[j+1].seq_no){
hold = shuf_ary[j];shuf_ary[j] = shuf_ary[j+1];shuf_ary[j+1] = hold;flag=1;
}}
}
int main(){
int no_frames,i;printf("Enter the message: ");gets(str);
no_frames = assign_seq_no(); shuffle(no_frames); sort(no_frames);
printf("\n\nAFTER SORTING\n");for(i=0;i<no_frames;i++)
printf("%s",shuf_ary[i].text);printf("\n\n");
}
4
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog2-frame_sorting.c[user@localhost cnlab]$ ./a.outEnter the message: welcome to P.A College of engineering
After assigning sequence numbers:0:wel 1:com 2:e t 3:o P 4:.A 5:Col 6:leg 7:e o 8:f e 9:ngi 10:nee 11:rin 12:g
AFTER SHUFFLING:0:wel 9:ngi 11:rin 4:.A 1:com 12:g 3:o P 7:e o 2:e t 10:nee 8:f e 5:Col 6:leg
AFTER SORTINGwelcome to P.A College of engineering
5
Network Programming Laboratory CSE Department
//Program 3: Distance Vector Algorithm to find suitable path for transmission.
#include<stdio.h>int n, e, s[20][20], graph[20][20];
void initialize(){ int i, j;
for(i=1; i<=20; i++)for(j=1; j<=20 && (s[i][j]=graph[i][j]=0); j++);
}
void getgraph(){ int i, strt, end;
printf("Enter no. of routers & edges in the graph:");scanf("%d%d",&n, &e);while(e-- > 0){ printf("Enter start router --> end router\n");
scanf("%d%d",&strt, &end);graph[strt][end] = graph[end][strt] = 1;
} }
void gettable(int src){ int i, j;
printf("\nEnter information for Source router %d\n",src);for(i=1; i <= n; i++)
if(graph[src][i] == 1) printf("Enter distance from source router %d to %d :",src,i),scanf("%d",&s[src][i]);
printf("\nEnter the contents of Echo packet of Adjacent routers of %d\n",src);for(i=1; i <= n; i++)
if(graph[src][i] == 1){ printf("Enter the contents of Echo packet of router %d\n",i);
for(j=1; j <= n; j++){ if(i == j) continue;
printf("Enter distance from router %d to %d :",i, j);scanf("%d",&s[i][j]);
} } }
void process(int src, int dest){ int min=999, i, delay, via;
for(i=1; i <= n; i++)if(graph[src][i] == 1){ delay = s[src][i] + s[i][dest];
if(delay < min)min=delay, via=i;
}printf("\nSuitable path from router %d to %d is through router %d " "with delay %d units\n",src, dest, via, min);
}
int main(){ int src,dest;
initialize();
6
Network Programming Laboratory CSE Department
getgraph();printf("\nEnter the Source & Destination router\n");scanf("%d%d",&src, &dest);gettable(src);process(src, dest);
}
OUTPUT:
[user@localhost cnlab]$ cc prog3-distance_vector.c[user@localhost cnlab]$ ./a.outEnter no. of routers & edges in the graph:7 10Enter start router --> end router1 2Enter start router --> end router2 3Enter start router --> end router3 4Enter start router --> end router4 5Enter start router --> end router5 6Enter start router --> end router6 1Enter start router --> end router1 3Enter start router --> end router2 7Enter start router --> end router3 6Enter start router --> end router3 7
Enter the Source & Destination router2 5
Enter information for Source router 2Enter distance from source router 2 to 1 :2Enter distance from source router 2 to 3 :20Enter distance from source router 2 to 7 :7
Enter the contents of Echo packet of Adjacent routers of 2Enter the contents of Echo packet of router 1Enter distance from router 1 to 2 :5Enter distance from router 1 to 3 :11Enter distance from router 1 to 4 :24Enter distance from router 1 to 5 :17Enter distance from router 1 to 6 :10Enter distance from router 1 to 7 :6Enter the contents of Echo packet of router 3
7
Network Programming Laboratory CSE Department
Enter distance from router 3 to 1 :3Enter distance from router 3 to 2 :9Enter distance from router 3 to 4 :7Enter distance from router 3 to 5 :15Enter distance from router 3 to 6 :9Enter distance from router 3 to 7 :2Enter the contents of Echo packet of router 7Enter distance from router 7 to 1 :3Enter distance from router 7 to 2 :16Enter distance from router 7 to 3 :11Enter distance from router 7 to 4 :16Enter distance from router 7 to 5 :8Enter distance from router 7 to 6 :9
Suitable path from router 2 to 5 is through router 7 with delay 15 units
8
Network Programming Laboratory CSE Department
// Program 4: Spanning tree algorithm (Kruskal) to find loopless path.
#include<stdio.h>int n, e, a[20][20], visit[20];
void initialize(){ int i, j;
for(i=1; i<=20 && (visit[i] = i); i++)for(j=1; j<=20 && (a[i][j] = 999); j++);
}
void getdata(){
int v1, v2, wt;printf("Enter the no of Vertices & Edges\n");scanf("%d%d",&n, &e);printf("Enter the graph++++++++++++++\n");while(e-- != 0){ printf("\nEnter start vertex-->end vertex:\n");
scanf("%d%d",&v1, &v2); printf("Enter Weight:");
scanf("%d",&wt);a[v1][v2] = a[v2][v1] = wt;
} }
void mini(int *v1, int *v2){ int minedge=999, i, j;
for(i=1; i<=n; i++)for(j=i+1; j<=n; j++)
if(minedge > a[i][j]) minedge=a[i][j], *v1=i, *v2=j;
}
void update(short v1,short v2){ int i;
for(i=1; i<=n; i++)if(visit[i] == visit[v2])
visit[i] = visit[v1];}
void spanning(){ int v1, v2, ecount=0;
while(ecount < n-1){ mini(&v1, &v2); a[v1][v2] = a[v2][v1] = 999; if(visit[v1] == visit[v2])
continue; else update(v1,v2), ecount++,
printf(" \nEdge %d from %d to %d",ecount, v1, v2);}
}
9
Network Programming Laboratory CSE Department
int main(){ initialize();
getdata();spanning();return 0;
}
OUTPUT:
[user@localhost cnlab]$ cc prog4-kruskal.c[user@localhost cnlab]$ ./a.outEnter the no of Vertices & Edges4 5Enter the graph++++++++++++++
Enter start vertex-->end vertex:1 2Enter Weight:1
Enter start vertex-->end vertex:2 3Enter Weight:2
Enter start vertex-->end vertex:3 4Enter Weight:2
Enter start vertex-->end vertex:4 1Enter Weight:1
Enter start vertex-->end vertex:1 3Enter Weight:5
Edge 1 from 1 to 2Edge 2 from 1 to 4Edge 3 from 2 to 3
10
Network Programming Laboratory CSE Department
// Program 4: Spanning tree algorithm (Prims) to find loopless path.
#include<stdio.h>int n, e, a[20][20], visit[20];
void initialize(){ int i, j;
for(i=1; i<=20 && (visit[i] = 0); i++)for(j=1; j<=20 && (a[i][j] = 999); j++);
}
void getdata(){ int v1, v2, wt; printf("Enter number of Vertices & Edges: \n"); scanf("%d%d",&n, &e);
printf("Enter the graph++++++++++\n"); while(e-- != 0) { printf("\nEnter start vertex --> end vertex\n"); scanf("%d%d",&v1, &v2); printf("Enter Weight:"); scanf("%d",&wt); a[v1][v2] = a[v2][v1] = wt;} }
void spanning(){ int ecount=1, min=0, x, y, i, j; visit[1]=1; while(ecount <= n-1) { min=999; for(i=1; i<=n; i++) for(j=i+1; j<=n; j++)
if(a[i][j] < min)if(visit[i] == 0)
continue; else
min=a[i][j], x=i, y=j; if(visit[x]==0 || visit[y]==0) printf(" \nEdge %d from %d to %d",ecount,x,y), visit[y]=1, ecount++; a[x][y] = a[y][x] = 999;} }
int main(){ initialize(); getdata(); spanning();
return 0;}
11
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog4-prims.c[user@localhost cnlab]$ ./a.outEnter number of Vertices & Edges:4 5Enter the graph++++++++++Enter start vertex --> end vertex1 2Enter Weight:1
Enter start vertex --> end vertex2 3Enter Weight:2
Enter start vertex --> end vertex3 4Enter Weight:2
Enter start vertex --> end vertex4 1Enter Weight:4
Enter start vertex --> end vertex1 3Enter Weight:5
Edge 1 from 1 to 2Edge 2 from 2 to 4Edge 3 from 2 to 3
12
Network Programming Laboratory CSE Department
//Program 5: Using TCP/IP sockets, a client-server program to make client //sending the file name & the server to send back the contents of the //requested file if present.
//-------------------------------CLIENT PROGRAM-------------------------------
#include<stdio.h>#include<string.h>#include<stdlib.h>//include<sys/socket.h> //for sockaddr//include<netinet/in.h> //for sockaddr_in #include<sys/fcntl.h> //for O_RDONLY#include<netdb.h>#define SERVER_PORT 2234#define BUF_SIZE 4096
int main(){ int c,s,bytes; char buf[BUF_SIZE],fname[255]; struct hostent *h;
struct sockaddr_in channel;
printf("Enter the file name:");gets(fname);
h=gethostbyname("localhost"); //get server address if(!h) printf("gethostbyname failed"), exit(0);
memset(&channel,0,sizeof(channel)); //allocate memory for 'channel' channel.sin_family=AF_INET; //assign values memcpy(&channel.sin_addr.s_addr,h->h_addr,h->h_length); channel.sin_port=htons(SERVER_PORT);
s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(s<0) printf("socket creation failed"), exit(0);
c=connect(s,(struct sockaddr*) &channel, sizeof(channel)); if(c<0) printf("connect failed"), exit(0);
write(s, fname, strlen(fname)); //write the file name to channel
while(1){ bytes=read(s,buf,BUF_SIZE); //read file contents form the channel
if (bytes<=0) exit(0); //sent by serverwrite(1,buf,bytes);
}}
13
Network Programming Laboratory CSE Department
//-------------------------------SERVER PROGRAM---------------------------------
#include<stdio.h>#include<string.h>#include<stdlib.h>//include<sys/socket.h> //for sockaddr//include<netinet/in.h> //for sockaddr_in #include<sys/fcntl.h> //for O_RDONLY#include<netdb.h>#define SERVER_PORT 2234#define BUF_SIZE 4096int main(){ int s,b,l,fd,sa,bytes,on=1; char buf[BUF_SIZE],fname[255];
struct sockaddr_in channel;
s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(s<0) printf("socket failed"), exit(0); setsockopt(s,SOL_SOCKET,SO_REUSEADDR,(char*)&on,sizeof(on));
memset(&channel,0,sizeof(channel)); //allocate memory for 'channel'channel.sin_family=AF_INET; //assign values
channel.sin_addr.s_addr=htonl(INADDR_ANY); channel.sin_port=htons(SERVER_PORT);
b=bind(s,(struct sockaddr*)&channel,sizeof(channel)); if(b<0) printf("bind failed"), exit(0);
listen(s,5); //listen channel for any request while(1) { printf("\n\nWaiting for request:\n");
sa=accept(s,0,0); //create a socket for communicationif(sa<0) printf("accept failed");
memset(fname,0,sizeof(fname)); read(sa,fname,BUF_SIZE); //read file name from channel
printf("requested filename: %s",fname);fd=open(fname,O_RDONLY); //open file to READ
if(fd<0){ printf("\nError message sent to client\n");
write(sa,"could not open requested file",40);}else {
while(1) { bytes = read(fd,buf,BUF_SIZE); //read file & store in buf
if(bytes<=0) break; write(sa,buf,bytes); //write the contents to channel }
close(fd); //close connection}
close(sa);}
}
14
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog5-sockets_server.c[user@localhost cnlab]$ ./a.out
Waiting for request:requested filename: abc.txt
[user@localhost cnlab]$ cc prog5-sockets_client.c[user@localhost cnlab]$ ./a.outEnter the file name:abc.txthello,welcome to P.A college of engineering.
15
Network Programming Laboratory CSE Department
//Program 6(a): Using FIFO's as IPC channel, a client-server program to make client //sending the file name & the server to send back the contents of the requested //file if present.
//-------------------------------CLIENT PROGRAM-------------------------------
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/errno.h> //for EEXIST#include<sys/stat.h> //for S_IFIFO#define FIFO1 "fifo1"#define FIFO2 "fifo2"#define MAXBUF 1024#define PERMS 0666
int main(){ int readfd, writefd, n;
char buff[MAXBUF];//open 2 FIFO files created by serverif( (writefd = open(FIFO1,1)) < 0) //FIFO1 for writing
printf("client:can't open write fifo\n"),exit(0);if( (readfd = open(FIFO2,0)) < 0) //FIFO2 for reading printf("client:can't open read fifo\n"),exit(0);
printf("Enter the file name:");if(fgets(buff,MAXBUF,stdin)==NULL) //get name of file form keybrd
printf("client:filename read error\n"),exit(0);n=strlen(buff)-1;
if(write(writefd, buff, n) != n) //write file name to FIFO file printf("client:filename write error\n"),exit(0);
while( (n=read(readfd, buff, MAXBUF)) > 0)//read contents of file fromif(write(1,buff,n)!=n) //FIFO file sent by server
printf("client:data write error\n"),exit(0);
close(readfd);close(writefd);
if(unlink(FIFO1)<0) //unlink all FIFO's printf("client:can't unlink\n"),exit(0);if(unlink(FIFO2)<0) printf("client:can't unlink\n"),exit(0);
}
16
Network Programming Laboratory CSE Department
//-------------------------------SERVER PROGRAM-------------------------------
#include<stdio.h>#include<stdlib.h>#include<string.h>#include<sys/errno.h> //for EEXIST#include<sys/stat.h> //for S_IFIFO#define FIFO1 "fifo1"#define FIFO2 "fifo2"#define MAXBUF 1024#define PERMS 0666
main(){ int readfd,writefd,n,fd;
char buff[MAXBUF];
if( mkfifo(FIFO1,S_IFIFO|PERMS) <0 )printf("can't create fifo.1\n"), exit(0);
if( mkfifo(FIFO2,S_IFIFO|PERMS) <0 )unlink(FIFO1), printf("can't create fifo.2\n"), exit(0);
if( (readfd=open(FIFO1,0))<0) //open FIFO files printf("server:can't open read fifo.1\n"),exit(0);if( (writefd=open(FIFO2,1))<0)
printf("server:can't open write fifo.2\n"),exit(0);
if((n=read(readfd,buff,255))<=0) //read filename from FIFO printf("server:filename read error"); //file sent by client
buff[n]='\0';
if( (fd=open(buff,0)) <0 ) //open the file sent by client{ strcpy(buff,"error:can't open file");
if(write(writefd,buff,strlen(buff))!=strlen(buff))printf("server:errmesg write error");
}else{ while( (n=read(fd,buff,MAXBUF)) >0 ) //read contents of file
if(write(writefd,buff,n)!=n) //write it to FIFO fileprintf("server:data write error");
}close(readfd);close(writefd);
}
OUTPUT:
[user@localhost cnlab]$ cc prog6-fifo_server.c[user@localhost cnlab]$ ./a.out[user@localhost cnlab]$
[user@localhost cnlab]$ cc prog6-fifo_client.c[user@localhost cnlab]$ ./a.outEnter the file name:abc.txthello,welcome to P.A college of engineering.
17
Network Programming Laboratory CSE Department
//Program 6(b): Using Message Queue as IPC channel, a client-server program to //make client sending the file name & the server to send back the contents //of the requested file if present.
//-------------------------------HEADER FILE------------------------------
#include<sys/ipc.h>#include<stdio.h>#include<stdlib.h>#include<string.h>#define MAXMESGDATA (4096-16)#define MKEY1 1234L#define MKEY2 1235L#define PERMS 0666
typedef unsigned int uint;typedef struct{ int mesg_len;
long mesg_type;char mesg_data[MAXMESGDATA];
}Mesg;
mesg_send(uint id,Mesg *mesgptr){ if( msgsnd(id,(char*)&(mesgptr->mesg_type),mesgptr->mesg_len,0)<0 )
printf("msgsnd error"), exit(0);}
mesg_recv(uint id,Mesg *mesgptr){ int n=msgrcv(id,(char *)&(mesgptr->mesg_type),MAXMESGDATA,mesgptr->mesg_type,0);
mesgptr->mesg_data[n]='\0';if((mesgptr->mesg_len=n)<0)
printf("msgrcv error"),exit(0);return(n);
}
18
Network Programming Laboratory CSE Department
//-------------------------------CLIENT PROGRAM-------------------------------
#include "prog6-msgq_header.h"Mesg mesg;client(uint readid,uint writeid){ printf("Enter the file name:");
if(fgets(mesg.mesg_data, MAXMESGDATA, stdin)==NULL)printf("client:filename read error\n"),exit(0);
mesg.mesg_len=strlen(mesg.mesg_data)-1;mesg.mesg_type=1L;mesg_send(writeid, &mesg);int n;while( (n=mesg_recv(readid, &mesg) ) > 0)
if(write(1, mesg.mesg_data, n) != n)printf("client:data write error\n"), exit(0);
}
main(){ uint readid,writeid;
if( (writeid = msgget(MKEY1,0)) < 0) printf("client:can't get msgget que1\n"), exit(0);if( (readid = msgget(MKEY2,0)) < 0)
printf("client:can't get msgget que2\n"), exit(0);client(readid,writeid);if(msgctl(readid, IPC_RMID, (struct msqid_ds *)0) < 0)
printf("\nclient:can't RMID message que1");if(msgctl(writeid, IPC_RMID, (struct msqid_ds *)0) < 0)
printf("\nclient:can't RMID message que2");
}
19
Network Programming Laboratory CSE Department
//-------------------------------SERVER PROGRAM-------------------------------
#include "prog6-msgq_header.h"Mesg mesg;server(uint readid,uint writeid){ int n,fd;
mesg.mesg_type=1L;if((n=mesg_recv(readid,&mesg))<=0)
printf("server:filename read error");
if( (fd=open(mesg.mesg_data,0)) <0 ){ strcpy(mesg.mesg_data,"error:can't open file");
mesg.mesg_len=strlen(mesg.mesg_data);mesg_send(writeid,&mesg);
}else{ while( (n=read(fd,mesg.mesg_data,MAXMESGDATA)) >0 )
mesg.mesg_len=n, mesg_send(writeid,&mesg);
close(fd);if(n<0) printf("server:data read error"),exit(0);
}mesg.mesg_len=0;mesg_send(writeid,&mesg);
}
main(){ uint readid,writeid;
if( (readid=msgget(MKEY1,PERMS|IPC_CREAT)) <0 ) printf("server:can't get mesg que1\n"),exit(0);if( (writeid=msgget(MKEY2,PERMS|IPC_CREAT)) <0 )
printf("server:can't get mesg que2\n"),exit(0);server(readid,writeid);
}
OUTPUT:
[user@localhost cnlab]$ cc prog6-msgq_server.c[user@localhost cnlab]$ ./a.out[user@localhost cnlab]$
[user@localhost cnlab]$ cc prog6-msgq_client.c[user@localhost cnlab]$ ./a.outEnter the file name:a.txtHello Dear
20
Network Programming Laboratory CSE Department
//Progam 7: Simple RSA algorithm to Encrypt & Decrypt the data.
#include<stdio.h>typedef unsigned int uint;uint gcd(uint x,uint y){ return y==0? x:gcd(y,x%y); }
uint multi(uint txt, uint ed, uint n){ uint i,rem=1;
for(i=1; i<=ed; i++)rem=(rem*txt)%n;
return rem;}
short prime(uint no){ uint i;
for(i=2; i<=no/2; i++)if(no%i==0) return 1;
return 0;}
int main(){ char msg[100]; uint pt[100],ct[100],n,d,e,p,q,z,i,len;
do{printf("\nEnter 2 large prime numbers p & q:\n");scanf("%d %d",&p,&q);}while(prime(p) || prime(q));n=p*q;z=(p-1)*(q-1);
do{ printf("\nEnter prime value of e relative to %d(z):",z);
scanf("%d",&e);}while(gcd(e,z)!=1 || e>n);
for(d=2;d<z;d++)
if((e*d)%z == 1)break;
printf("Enter the Message\n"); //get message from keybrd.len=read(1,msg,100)-1;
for(i=0;i<len;i++) //store it in plain text arraypt[i]=msg[i];
printf("\n Cipher Text=");for(i=0;i<len;i++) //convert plain to cipher text
printf("%d ",ct[i]=multi(pt[i],e,n));
printf("\n Plain Text="); for(i=0;i<len;i++) //convert cipher to plain text
printf("%c",multi(ct[i],d,n));}
21
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog7-rsa.c[user@localhost cnlab]$ ./a.out
Enter 2 large prime numbers p & q:1117
Enter prime value of e relative to 160(z):167Enter the Messagehello,how are you?
Cipher Text=179 84 48 48 155 22 179 155 136 76 92 126 84 76 77 155 127 24 Plain Text=hello,how are you?
22
Network Programming Laboratory CSE Department
//Program 8: Program for Hamming Code generation for error detection and correction
#include<stdio.h>#include<stdlib.h>short calcevenparity(short num){ short bitmask=1,countones=0,i;
for(i=0;i<8;i++){ if(num & bitmask) countones++;
bitmask<<=1;}return countones%2 ? 1:0; //1=odd no of ones;0=even no of ones
}
int main(){ short data,code,errpos=0,e,f=1,r1,r2,r3;
printf("SENDER.....\n");printf("Enter the integer b/n 0 n 15:");scanf("%x",&data);
//calculate hamming code =| |d4|d3|d2|r3|d1|r2|r1|r1=calcevenparity (0xb & data); //b=r1=d1+d2+d4r2=calcevenparity (0xd & data); //d=r2=d1+d3+d4r3=calcevenparity (0xe & data); //e=r3=d2+d3+d4
code=data<<3; //place bits d4,d3 n d2 at 7th 6th n 5th posn.if(data%2) code |= 0x4; //place d1 in 3rd positioncode &= 0x74; //clear parity-bit positions.
if(r1) code|=0x01; //if true, odd no of ones, if(r2) code|=0x02; //make it even no. of onesif(r3) code|=0x08; //by setting r positions
printf("The hamming code is:%x(hex)\n",code);
//introducing error in the codeprintf("\nEnter the position to introduce error(1-7):");scanf("%d",&e);if(e>=1 && e<=7)
f<<=(e-1),code^=f, //eth bit is flippedprintf("The errenous code is:%x(hex)\n",code);
//error detection printf("\nRECIEVER......\n");if(calcevenparity(code & 0x55)) errpos++; //55=p1=r1+d1+d2+d4if(calcevenparity(code & 0x66)) errpos+=2; //66=p2=r2+d1+d3+d4if(calcevenparity(code & 0x78)) errpos+=4; //78=p3=r3+d2+d3+d4
if(errpos) printf("Error detected at position %d\n",errpos);else
{printf("Error free code...\n\n");
exit(0);}
23
Network Programming Laboratory CSE Department
//error correctionf=1;f<<=errpos-1;printf("Corrected data is :%x(hex)",f^code);
}
OUTPUT:
[user@localhost cnlab]$ cc prog8-hamming.c[user@localhost cnlab]$ ./a.outSENDER.....Enter the integer b/n 0 n 15:7The hamming code is:34(hex)
Enter the position to introduce error(1-7):5The errenous code is:24(hex)
RECIEVER......Error detected at position 5Corrected data is :34(hex)
24
Network Programming Laboratory CSE Department
//Program 9:Program for congestion control using Leaky Bucket algorithm.
#include<stdio.h>int rand(int a){ int rn=(random()%10)%a;
return rn==0?1:rn;}
int main(){ int packet_sz[5],i,clk,b_size,o_rate,p_sz_rm=0,p_sz,p_time;
for(i=0;i<5;++i)packet_sz[i]=rand(6)*10;
for(i=0;i<5;++i)printf("packet[%d]:%d bytes\t",i,packet_sz[i]);
printf("\nEnter the Output rate:");scanf("%d",&o_rate);printf("Enter the Bucket Size:");scanf("%d",&b_size);for(i=0; i<5; ++i){ if((packet_sz[i]+p_sz_rm) > b_size)
if(packet_sz[i] > b_size)printf("\n\nIncomming packet size (%d) is Greater than bucket capacity-PACKET REJECTED",packet_sz[i]);
elseprintf("\n\nBucket capacity exceeded-REJECTED!!");
else{ p_sz_rm+=packet_sz[i];
printf("\n\nIncomming Packet size: %d",packet_sz[i]);printf("\nBytes remaining to Transmit: %d",p_sz_rm);p_time = rand(4)*10;printf("\nTime left for transmission: %d units",p_time);for(clk=10; clk<=p_time; clk+=10){ sleep(1);
if(p_sz_rm){ if(p_sz_rm <= o_rate)
printf("\n Packet of size %d Transmitted",p_sz_rm),p_sz_rm=0;
elseprintf("\n Packet of size %d Transmitted",o_rate),p_sz_rm -= o_rate;printf("----Bytes Remaining after Transmission: %d",p_sz_rm);
}else
printf("\n No packets to transmit!!");printf(" Time Left:%d",p_time-clk);
} } }}
25
Network Programming Laboratory CSE Department
OUTPUT:
[user@localhost cnlab]$ cc prog9-leakybucket.c[user@localhost cnlab]$ ./a.outpacket[0]:30 bytes packet[1]:10 bytes packet[2]:10 bytes packet[3]:50 bytes packet[4]:30 bytesEnter the Output rate:20Enter the Bucket Size:50
Incomming Packet size: 30Bytes remaining to Transmit: 30Time left for transmission: 10 unitsPacket of size 20 Transmitted----Bytes Remaining after Transmission: 10 Time Left:0
Incomming Packet size: 10Bytes remaining to Transmit: 20Time left for transmission: 20 unitsPacket of size 20 Transmitted----Bytes Remaining after Transmission: 0 Time Left:10 No packets to transmit!! Time Left:0
Incomming Packet size: 10Bytes remaining to Transmit: 10Time left for transmission: 20 unitsPacket of size 10 Transmitted----Bytes Remaining after Transmission: 0 Time Left:10 No packets to transmit!! Time Left:0
Incomming Packet size: 50Bytes remaining to Transmit: 50Time left for transmission: 10 unitsPacket of size 20 Transmitted----Bytes Remaining after Transmission: 30 Time Left:0
Bucket capacity exceeded-REJECTED!!
26