You are on page 1of 39

#include <stdio.

h>
#include <unistd.h>
#include <string.h>

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>

int main()
{
unsigned char ip_address[15];
int fd;
struct ifreq ifr;

/*AF_INET - to define network interface IPv4*/


/*Creating soket for it.*/
fd = socket(AF_INET, SOCK_DGRAM, 0);

/*AF_INET - to define IPv4 Address type.*/


ifr.ifr_addr.sa_family = AF_INET;

/*eth0 - define the ifr_name - port name


where network attached.*/
memcpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);

/*Accessing network interface information by


passing address using ioctl.*/
ioctl(fd, SIOCGIFADDR, &ifr);
/*closing fd*/
close(fd);

/*Extract IP Address*/
strcpy(ip_address,inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr));

printf("System IP Address is: %s\n",ip_address);

return 0;
}

Output
System IP Address is: 152.167.0.71
Classful Addressing

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <unistd.h>
#include <arpa/inet.h>

int main()
{
int n;
struct ifreq ifr;
char array[] = "eth0";

n = socket(AF_INET, SOCK_DGRAM, 0);


//Type of address to retrieve - IPv4 IP address
ifr.ifr_addr.sa_family = AF_INET;
//Copy the interface name in the ifreq structure
strncpy(ifr.ifr_name , array , IFNAMSIZ - 1);
ioctl(n, SIOCGIFADDR, &ifr);
close(n);
//display result
printf("IP Address is %s - %s\n" , array , inet_ntoa(( (struct sockaddr_in *)&ifr.ifr_addr )->sin_addr)
);
return 0;
}

Output

IP Address is eth0 - 192.168.225.135


Mask is 255.255.255.0
Find Class

#include <stdio.h>
#include <string.h>

/*
Function : extractIpAddress
Arguments :
1) sourceString - String pointer that contains ip address
2) ipAddress - Target variable short type array pointer that will store ip address octets
*/
void extractIpAddress(unsigned char *sourceString,short *ipAddress)
{
unsigned short len=0;
unsigned char oct[4]={0},cnt=0,cnt1=0,i,buf[5];

len=strlen(sourceString);
for(i=0;i<len;i++)
{
if(sourceString[i]!='.'){
buf[cnt++] =sourceString[i];
}
if(sourceString[i]=='.' || i==len-1){
buf[cnt]='\0';
cnt=0;
oct[cnt1++]=atoi(buf);
}
}
ipAddress[0]=oct[0];
ipAddress[1]=oct[1];
ipAddress[2]=oct[2];
ipAddress[3]=oct[3];
}

int main()
{
unsigned char ip[20]={0};
short ipAddress[4];

printf("Enter IP Address (xxx.xxx.xxx.xxx format): ");


scanf("%s",ip);

extractIpAddress(ip,&ipAddress[0]);

printf("\nIp Address: %03d. %03d. %03d.


%03d\n",ipAddress[0],ipAddress[1],ipAddress[2],ipAddress[3]);

if(ipAddress[0]>=0 && ipAddress[0]<=127)


printf("Class A Ip Address.\n");
if(ipAddress[0]>127 && ipAddress[0]<191)
printf("Class B Ip Address.\n");
if(ipAddress[0]>191 && ipAddress[0]<224)
printf("Class C Ip Address.\n");
if(ipAddress[0]>224 && ipAddress[0]<=239)
printf("Class D Ip Address.\n");
if(ipAddress[0]>239)
printf("Class E Ip Address.\n");

return 0;
}

Output
Enter IP Address (xxx.xxx.xxx.xxx format): 145.160.017.001

Ip Address: 145. 160. 017. 001


Class B Ip Address.
Client Server Model

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>

// the port client will be connecting to


#define PORT 3490
// max number of bytes we can get at once
#define MAXDATASIZE 300

int main(int argc, char *argv[])


{
int sockfd, numbytes;
char buf[MAXDATASIZE];
struct hostent *he;
// connector’s address information
struct sockaddr_in their_addr;

// if no command line argument supplied


if(argc != 2)
{
fprintf(stderr, "Client-Usage: %s the_client_hostname\n", argv[0]);
// just exit
exit(1);
}

// get the host info


if((he=gethostbyname(argv[1])) == NULL)
{
perror("gethostbyname()");
exit(1);
}
else
printf("Client-The remote host is: %s\n", argv[1]);

if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)


{
perror("socket()");
exit(1);
}
else
printf("Client-The socket() sockfd is OK...\n");
// host byte order
their_addr.sin_family = AF_INET;
// short, network byte order
printf("Server-Using %s and port %d...\n", argv[1], PORT);
their_addr.sin_port = htons(PORT);
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
// zero the rest of the struct
memset(&(their_addr.sin_zero), '\0', 8);

if(connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1)


{
perror("connect()");
exit(1);
}
else
printf("Client-The connect() is OK...\n");

if((numbytes = recv(sockfd, buf, MAXDATASIZE-1, 0)) == -1)


{
perror("recv()");
exit(1);
}
else
printf("Client-The recv() is OK...\n");

buf[numbytes] = '\0';
printf("Client-Received: %s", buf);

printf("Client-Closing sockfd\n");
close(sockfd);
return 0;
}
 Compile and link the program.
[bodo@bakawali testsocket]$ gcc -g clientprog.c -o clientprog
 Run the program without argument.
[bodo@bakawali testsocket]$ ./clientprog
Client-Usage: ./clientprog the_client_hostname
 Run the program with server IP address or name as an argument. Here we use IP address.
 Make sure your previous serverprog program is running. We will connect using the same
server. You can try running the server and client program at different machines.
[bodo@bakawali testsocket]$ ./clientprog 203.106.93.94
...
[bodo@bakawali testsocket]$ ./clientprog bakawali
Client-The remote host is: bakawali
Client-The socket() sockfd is OK...
Server-Using bakawali and port 3490...
Client-The connect() is OK...
Client-The recv() is OK...
Client-Received: This is the test string from server!
Client-Closing sockfd
 Verify the connection.
[bodo@bakawali testsocket]$ netstat -a | grep 3490
tcp 0 0 *:3490 *:* LISTEN
tcp 0 0 bakawali.jmti.gov.my:3490 bakawali.jmti.gov.my:1358 TIME_WAIT
[bodo@bakawali testsocket]$
 At server’s console, we have the following messages.
[bodo@bakawali testsocket]$ ./serverprog
Server-socket() sockfd is OK...
Server-setsockopt() is OK...
Server-Using 0.0.0.0 and port 3490...
Server-bind() is OK...
Server-listen() is OK...Listening...
Server-sigaction() is OK...
Server-accept() is OK...
Server-new socket, new_fd is OK...
Server: Got connection from 203.106.93.94
Server-send() is OK...!
Server-new socket, new_fd closed successfully...
Stop And Wait

#include <stdio.h>
#include <stdlib.h>

#define BIDIRECTIONAL 0 /* change to 1 if you're doing extra credit */


/* and write a routine called B_output */

/* a "msg" is the data unit passed from layer 5 (teachers code) to layer */
/* 4 (students' code). It contains the data (characters) to be delivered */
/* to layer 5 via the students transport level protocol entities. */
struct msg {
char data[20];
};

/* a packet is the data unit passed from layer 4 (students code) to layer */
/* 3 (teachers code). Note the pre-defined packet structure, which all */
/* students must follow. */
struct pkt {
int seqnum;
int acknum;
int checksum;
char payload[20];
};

int seq_A;
struct pkt pkt_A2B;

/* called from layer 5, passed the data to be sent to other side */


A_output(message)
struct msg message;
{
int i;
int checksumA=0;

printf("Now we are in A_output, seq_a= %d\n", seq_A);


seq_A++ ;

printf("now transfering message to packet\n");


for ( i=0; i< 20; i++)
{
pkt_A2B.payload[i]=message.data[i];
checksumA+=(int)(pkt_A2B.payload[i]);
printf("%c", pkt_A2B.payload[i]);
}
printf("\n character %c is in ascii %d check sum is %d transfer complete\n",
pkt_A2B.payload[0], pkt_A2B.payload[0], checksumA);

}
B_output(message) /* need be completed only for extra credit */
struct msg message;
{
/*do nothing */
}

/* called from layer 3, when a packet arrives for layer 4 */


A_input(packet)
struct pkt packet;
{
/* stop timer*/
stoptimer(0);
/* check if ack is ok*/

/*check if ack no == send no */

/*if not resent last packet */

/*if yes increment seq_no and exit */

/* called when A's timer goes off */


A_timerinterrupt()
{
}

/* the following routine will be called once (only) before any other */
/* entity A routines are called. You can use it to do any initialization */
A_init()
{
}

/* Note that with simplex transfer from a-to-B, there is no B_output() */

/* called from layer 3, when a packet arrives for layer 4 at B*/


B_input(packet)
struct pkt packet;
{
}

/* called when B's timer goes off */


B_timerinterrupt()
{
}

/* the following rouytine will be called once (only) before any other */
/* entity B routines are called. You can use it to do any initialization */
B_init()
{
}

struct event {
float evtime; /* event time */
int evtype; /* event type code */
int eventity; /* entity where event occurs */
struct pkt *pktptr; /* ptr to packet (if any) assoc w/ this event */
struct event *prev;
struct event *next;
};
struct event *evlist = NULL; /* the event list */

/* possible events: */
#define TIMER_INTERRUPT 0
#define FROM_LAYER5 1
#define FROM_LAYER3 2

#define OFF 0
#define ON 1
#define A 0
#define B 1

int TRACE = 1; /* for my debugging */


int nsim = 0; /* number of messages from 5 to 4 so far */
int nsimmax = 0; /* number of msgs to generate, then stop */
float time = 0.000;
float lossprob; /* probability that a packet is dropped */
float corruptprob; /* probability that one bit is packet is flipped */
float lambda; /* arrival rate of messages from layer 5 */
int ntolayer3; /* number sent into layer 3 */
int nlost; /* number lost in media */
int ncorrupt; /* number corrupted by media*/

main()
{
struct event *eventptr;
struct msg msg2give;
struct pkt pkt2give;

int i,j;
char c;

init();
A_init();
B_init();
while (1) {
eventptr = evlist; /* get next event to simulate */
if (eventptr==NULL)
goto terminate;
evlist = evlist->next; /* remove this event from event list */
if (evlist!=NULL)
evlist->prev=NULL;
if (TRACE>=2) {
printf("\nEVENT time: %f,",eventptr->evtime);
printf(" type: %d",eventptr->evtype);
if (eventptr->evtype==0)
printf(", timerinterrupt ");
else if (eventptr->evtype==1)
printf(", fromlayer5 ");
else
printf(", fromlayer3 ");
printf(" entity: %d\n",eventptr->eventity);
}
time = eventptr->evtime; /* update time to next event time */
if (nsim==nsimmax)
break; /* all done with simulation */
if (eventptr->evtype == FROM_LAYER5 ) {
generate_next_arrival(); /* set up future arrival */
/* fill in msg to give with string of same letter */
j = nsim % 26;
for (i=0; i<20; i++)
msg2give.data[i] = 97 + j;
if (TRACE>2) {
printf(" MAINLOOP: data given to student: ");
for (i=0; i<20; i++)
printf("%c", msg2give.data[i]);
printf("\n");
}
nsim++;
if (eventptr->eventity == A)
A_output(msg2give);
else
B_output(msg2give);
}
else if (eventptr->evtype == FROM_LAYER3) {
pkt2give.seqnum = eventptr->pktptr->seqnum;
pkt2give.acknum = eventptr->pktptr->acknum;
pkt2give.checksum = eventptr->pktptr->checksum;
for (i=0; i<20; i++)
pkt2give.payload[i] = eventptr->pktptr->payload[i];
if (eventptr->eventity ==A) /* deliver packet by calling */
A_input(pkt2give); /* appropriate entity */
else
B_input(pkt2give);
free(eventptr->pktptr); /* free the memory for packet */
}
else if (eventptr->evtype == TIMER_INTERRUPT) {
if (eventptr->eventity == A)
A_timerinterrupt();
else
B_timerinterrupt();
}
else {
printf("INTERNAL PANIC: unknown event type \n");
}
free(eventptr);
}

terminate:
printf(" Simulator terminated at time %f\n after sending %d msgs from layer5\n",time,nsim);
}

init() /* initialize the simulator */


{
int i;
float sum, avg;
float jimsrand();

printf("----- Stop and Wait Network Simulator Version 1.1 -------- \n\n");
printf("Enter the number of messages to simulate: ");
scanf("%d",&nsimmax);
printf("Enter packet loss probability [enter 0.0 for no loss]:");
scanf("%f",&lossprob);
printf("Enter packet corruption probability [0.0 for no corruption]:");
scanf("%f",&corruptprob);
printf("Enter average time between messages from sender's layer5 [ > 0.0]:");
scanf("%f",&lambda);
printf("Enter TRACE:");
scanf("%d",&TRACE);

srand(9999); /* init random number generator */


sum = 0.0; /* test random number generator for students */
for (i=0; i<1000; i++)
sum=sum+jimsrand(); /* jimsrand() should be uniform in [0,1] */
avg = sum/1000.0;
if (avg < 0.25 || avg > 0.75) {
printf("It is likely that random number generation on your machine\n" );
printf("is different from what this emulator expects. Please take\n");
printf("a look at the routine jimsrand() in the emulator code. Sorry. \n");
exit(0);
}

ntolayer3 = 0;
nlost = 0;
ncorrupt = 0;

time=0.0; /* initialize time to 0.0 */


generate_next_arrival(); /* initialize event list */
}

/****************************************************************************/
/* jimsrand(): return a float in range [0,1]. The routine below is used to */
/* isolate all random number generation in one location. We assume that the*/
/* system-supplied rand() function return an int in therange [0,mmm] */
/****************************************************************************/
float jimsrand()
{
double mmm = (double) RAND_MAX ;//2147483647; /* largest int - MACHINE
DEPENDENT!!!!!!!! */
float x; /* individual students may need to change mmm */
x = rand()/mmm; /* x should be uniform in [0,1] */
return(x);
}

/********************* EVENT HANDLINE ROUTINES *******/


/* The next set of routines handle the event list */
/*****************************************************/

generate_next_arrival()
{
double x,log(),ceil();
struct event *evptr;
// char *malloc();
float ttime;
int tempint;

if (TRACE>2)
printf(" GENERATE NEXT ARRIVAL: creating new arrival\n");

x = lambda*jimsrand()*2; /* x is uniform on [0,2*lambda] */


/* having mean of lambda */
evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtime = time + x;
evptr->evtype = FROM_LAYER5;
if (BIDIRECTIONAL && (jimsrand()>0.5) )
evptr->eventity = B;
else
evptr->eventity = A;
insertevent(evptr);
}

insertevent(p)
struct event *p;
{
struct event *q,*qold;

if (TRACE>2) {
printf(" INSERTEVENT: time is %lf\n",time);
printf(" INSERTEVENT: future time will be %lf\n",p->evtime);
}
q = evlist; /* q points to header of list in which p struct inserted */
if (q==NULL) { /* list is empty */
evlist=p;
p->next=NULL;
p->prev=NULL;
}
else {
for (qold = q; q !=NULL && p->evtime > q->evtime; q=q->next)
qold=q;
if (q==NULL) { /* end of list */
qold->next = p;
p->prev = qold;
p->next = NULL;
}
else if (q==evlist) { /* front of list */
p->next=evlist;
p->prev=NULL;
p->next->prev=p;
evlist = p;
}
else { /* middle of list */
p->next=q;
p->prev=q->prev;
q->prev->next=p;
q->prev=p;
}
}
}

printevlist()
{
struct event *q;
int i;
printf("--------------\nEvent List Follows:\n");
for(q = evlist; q!=NULL; q=q->next) {
printf("Event time: %f, type: %d entity: %d\n",q->evtime,q->evtype,q->eventity);
}
printf("--------------\n");
}

/* called by students routine to cancel a previously-started timer */


stoptimer(AorB)
int AorB; /* A or B is trying to stop timer */
{
struct event *q,*qold;

if (TRACE>2)
printf(" STOP TIMER: stopping timer at %f\n",time);
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
/* remove this event */
if (q->next==NULL && q->prev==NULL)
evlist=NULL; /* remove first and only event on list */
else if (q->next==NULL) /* end of list - there is one in front */
q->prev->next = NULL;
else if (q==evlist) { /* front of list - there must be event after */
q->next->prev=NULL;
evlist = q->next;
}
else { /* middle of list */
q->next->prev = q->prev;
q->prev->next = q->next;
}
free(q);
return;
}
printf("Warning: unable to cancel your timer. It wasn't running.\n");
}

starttimer(AorB,increment)
int AorB; /* A or B is trying to stop timer */
float increment;
{

struct event *q;


struct event *evptr;
// char *malloc();

if (TRACE>2)
printf(" START TIMER: starting timer at %f\n",time);
/* be nice: check to see if timer is already started, if so, then warn */
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==TIMER_INTERRUPT && q->eventity==AorB) ) {
printf("Warning: attempt to start a timer that is already started\n");
return;
}

/* create future event for when timer goes off */


evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtime = time + increment;
evptr->evtype = TIMER_INTERRUPT;
evptr->eventity = AorB;
insertevent(evptr);
}

/************************** TOLAYER3 ***************/


/* 1A25A48A252A */

tolayer3(AorB,packet)
int AorB; /* A or B is trying to stop timer */
struct pkt packet;
{
struct pkt *mypktptr;
struct event *evptr,*q;
// char *malloc();
float lastime, x, jimsrand();
int i;

ntolayer3++;

/* simulate losses: */
if (jimsrand() < lossprob) {
nlost++;
if (TRACE>0)
printf(" TOLAYER3: packet being lost\n");
return;
}

/* make a copy of the packet student just gave me since he/she may decide */
/* to do something with the packet after we return back to him/her */
mypktptr = (struct pkt *)malloc(sizeof(struct pkt));
mypktptr->seqnum = packet.seqnum;
mypktptr->acknum = packet.acknum;
mypktptr->checksum = packet.checksum;
for (i=0; i<20; i++)
mypktptr->payload[i] = packet.payload[i];
if (TRACE>2) {
printf(" TOLAYER3: seq: %d, ack %d, check: %d ", mypktptr->seqnum,
mypktptr->acknum, mypktptr->checksum);
for (i=0; i<20; i++)
printf("%c",mypktptr->payload[i]);
printf("\n");
}

/* create future event for arrival of packet at the other side */


evptr = (struct event *)malloc(sizeof(struct event));
evptr->evtype = FROM_LAYER3; /* packet will pop out from layer3 */
evptr->eventity = (AorB+1) % 2; /* event occurs at other entity */
evptr->pktptr = mypktptr; /* save ptr to my copy of packet */
/* finally, compute the arrival time of packet at the other end.
medium can not reorder, so make sure packet arrives between 1 and 10
time units after the latest arrival time of packets
currently in the medium on their way to the destination */
lastime = time;
/* for (q=evlist; q!=NULL && q->next!=NULL; q = q->next) */
for (q=evlist; q!=NULL ; q = q->next)
if ( (q->evtype==FROM_LAYER3 && q->eventity==evptr->eventity) )
lastime = q->evtime;
evptr->evtime = lastime + 1 + 9*jimsrand();

/* simulate corruption: */
if (jimsrand() < corruptprob) {
ncorrupt++;
if ( (x = jimsrand()) < .75)
mypktptr->payload[0]='Z'; /* corrupt payload */
else if (x < .875)
mypktptr->seqnum = 999999;
else
mypktptr->acknum = 999999;
if (TRACE>0)
printf(" TOLAYER3: packet being corrupted\n");
}

if (TRACE>2)
printf(" TOLAYER3: scheduling arrival on other side\n");
insertevent(evptr);
}

tolayer5(AorB,datasent)
int AorB;
char datasent[20];
{
int i;
if (TRACE>2) {
printf(" TOLAYER5: data received: ");
for (i=0; i<20; i++)
printf("%c",datasent[i]);
printf("\n");
}

}
Sliding Window

SENDER

#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
int sock,bytes_received,connected,true=1,i=1,s,f=0,sin_size;
char send_data[1024],data[1024],c,fr[30]=" ";
struct sockaddr_in server_addr,client_addr;
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Socket not created");
exit(1);
}
if(setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&true,sizeof(int))==-1)
{
perror("Setsockopt");
exit(1);
}
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(17000);
server_addr.sin_addr.s_addr=INADDR_ANY;
if(bind(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
{
perror("Unable to bind");
exit(1);
}
if(listen(sock,5)==-1)
{
perror("Listen");
exit(1);
}
fflush(stdout);
sin_size=sizeof(struct sockaddr_in);
connected=accept(sock,(struct sockaddr *)&client_addr,&sin_size);
while(strcmp(fr,"exit")!=0)
{
printf("Enter Data Frame %d:(Enter exit for End): ",i);
scanf("%s",fr);
send(connected,fr,strlen(fr),0);
recv(sock,data,1024,0);
if(strlen(data)!=0)
printf("I got an acknowledgement : %s\n",data);
fflush(stdout);
i++;
}
close(sock);
return (0);
}

RECEIVER
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
int main()
{
int sock,bytes_received,i=1;
char receive[30];
struct hostent *host;
struct sockaddr_in server_addr;
host=gethostbyname("127.0.0.1");
if((sock=socket(AF_INET,SOCK_STREAM,0))==-1)
{
perror("Socket not created");
exit(1);
}
printf("Socket created");
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(17000);
server_addr.sin_addr=*((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);
if(connect(sock,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
{
perror("Connect");
exit(1);
}
while(1)
{
bytes_received=recv(sock,receive,20,0);
receive[bytes_received]='\0';
if(strcmp(receive,"exit")==0||strcmp(receive,"exit")==0)
{
close(sock);
break;
}
else
{
if(strlen(receive)<10)
{
printf("\n Frame %d data %s received\n",i,receive);
send(0,receive,strlen(receive),0);
}
else
{
send(0,"negative",10,0);
}
i++;
}
}
close(sock);
return(0);
}

OUTPUT
SENDER
$ cc sender.c
$ ./a.out
Enter Data Frame 1:(Enter exit for End): saveetha
Enter Data Frame 2:(Enter exit for End): mca
Enter Data Frame 3:(Enter exit for End): exit
$

RECEIVER
$ cc receiver.c
$ ./a.out
Socket created
Frame 1 data saveetha received
Frame 2 data mca received
$
Go Back N

#include<stdio.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#define SIZE 4
int main()
{
int sfd,lfd,len,i,j,status;
char str[20],frame[20],temp[20],ack[20];
struct sockaddr_in saddr,caddr;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
perror("Error");
bzero(&saddr,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_addr.s_addr=htonl(INADDR_ANY);
saddr.sin_port=htons(5465);
if(bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr))<0)
perror("Bind Error");
listen(sfd,5);
len=sizeof(&caddr);
lfd=accept(sfd,(struct sockaddr*)&caddr,&len);
printf(" Enter the text : \n");
scanf("%s",str);
i=0;
while(i<strlen(str))
{
memset(frame,0,20);
strncpy(frame,str+i,SIZE);
printf(" Transmitting Frames. ");
len=strlen(frame);
for(j=0;j<len;j++)
{
printf("%d",i+j);
sprintf(temp,"%d",i+j);
strcat(frame,temp);
}
printf("\n");
write(lfd,frame,sizeof(frame));
read(lfd,ack,20);
sscanf(ack,"%d",&status);

if(status==-1)
printf(" Transmission is successful. \n");
else
{
printf(" Received error in %d \n\n",status);
printf("\n\n Retransmitting Frame. ");
for(j=0;;)
{
frame[j]=str[j+status];
printf("%d",j+status);
j++;
if((j+status)%4==0)
break;
}
printf("\n");
frame[j]='\0';
len=strlen(frame);
for(j=0;j<len;j++)
{
sprintf(temp,"%d",j+status);
strcat(frame,temp);
}
write(lfd,frame,sizeof(frame));
}
i+=SIZE;
}
write(lfd,"exit",sizeof("exit"));
printf("Exiting\n");
sleep(2);
close(lfd);
close(sfd);
}
Selective repeat

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
int main()
{
int sfd,lfd,len,choice;
char str[20],str1[20],err[20];
struct sockaddr_in saddr,caddr;
sfd=socket(AF_INET,SOCK_STREAM,0);
if(sfd<0)
perror("FdError");
bzero(&saddr,sizeof(saddr));
saddr.sin_family=AF_INET;
saddr.sin_addr.s_addr=INADDR_ANY;
saddr.sin_port=htons(5465);
connect(sfd,(struct sockaddr*)&saddr,sizeof(saddr));
for(;;)
{
read(sfd,str,20);
if(!strcmp(str,"exit"))
{
printf("Exiting\n");
break;
}
printf("\n\nReceived%s\n\n1.Do u want to report an error(1-Yes 0-No)",str);
scanf("%d",&choice);
if(!choice)
write(sfd,"-1",sizeof("-1"));
else
{
printf("Enter the sequence no of the frame where error has occured\n");
scanf("%s",err);
write(sfd,err,sizeof(err));
read(sfd,str,20);
printf("\n\nReceived the re-transmitted frames%s\n\n",str);
}
OUT PUT :

cc SlideServer.c
./a.out

Enter the text


jerusalem
Transmitting Frames=0123
Transmission is successful
Transmitting Frames=4567
Received error in 5

Retransmitting Frame=678
Transmitting Frames=8
Received error in 2

Retransmitting Frame=34
Exiting

ClientServer.c :

cc ClientServer.c
./a.out

Received=jeru0123

1.Do u want to report an error(1-Yes 0-No)0

Received=sale4567

1.Do u want to report an error(1-Yes 0-No)1


Enter the sequence no of the frame where error has occured
5

Received the re-transmitted frames=ale567

Received=m8

1.Do u want to report an error(1-Yes 0-No)1


Enter the sequence no of the frame where error has occured
2
Received the re-transmitted frames=ru23
Exiting
Bit Stuffing

#include<stdio.h>
#include<string.h>
void main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame length:");
scanf("%d",&n);
printf("Enter input frame (0's & 1's only):");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
i=0; count=1; j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1;a[k]==1 && k<n && count<5;k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After stuffing the frame is:");
for(i=0;i<j;i++)
printf("%d",b[i]);
}

OUTPUT:

Enter frame length: 10

Enter input frame (0’s & 1’s only):


1010111111
After stuffing the frame is:
10101111101
Character Stuffing

#include<stdio.h>
#include<string.h>
main()
{
char a[30], fs[50] = " ", t[3], sd, ed, x[3], s[3], d[3], y[3];
int i, j, p = 0, q = 0;
clrscr();
printf("Enter characters to be stuffed:");
scanf("%s", a);
printf("\nEnter a character that represents starting delimiter:");
scanf(" %c", &sd);
printf("\nEnter a character that represents ending delimiter:");
scanf(" %c", &ed);
x[0] = s[0] = s[1] = sd;
x[1] = s[2] = '\0';
y[0] = d[0] = d[1] = ed;
d[2] = y[1] = '\0';
strcat(fs, x);
for(i = 0; i < strlen(a); i++)
{
t[0] = a[i];
t[1] = '\0';
if(t[0] == sd)
strcat(fs, s);
else if(t[0] == ed)
strcat(fs, d);
else
strcat(fs, t);
}
strcat(fs, y);
printf("\n After stuffing:%s", fs);
getch();
}

Output:-

Enter characters to be stuffed: goodday


Enter a character that represents starting delimiter: d
Enter a character that represents ending delimiter: g
After stuffing: dggooddddayg.
Hamming code

// hammingdetection.c
#include<stdio.h>
void main()
{
int r[7],s[3],index,i,j,sum;
int h[3][7]={{1,0,1,1,1,0,0},{1,1,0,1,0,1,0},{0,1,1,1,0,0,1}};
printf("\n Enter the 7 bit information: \n");
for(i=0;i<7;i++)
scanf("%d",&r[i]);
for(j=0;j<3;j++)
{
sum=0;
for(i=0;i<7;i++)
sum+=h[i][j]*r[i];
sum=sum%2;
s[j]=sum;
}
if(s[0]==0 && s[1]==0 && s[2]==0)
{
printf("\n Error free Implementation.\n");
printf("\n The data bits are\n");
for(i=0;i<4;i++)
printf("%d",r[i]);
exit(0);
}
for(j=0;j<7;j++)
{
if(s[0]==h[0][j] && s[1]==h[1][j] && s[2]==h[2][j])
{
index=j;
break;
}
}
printf("\n The error is in bit no %d\n",index+1);
if(r[index]==0)
r[index]=1;
else
r[index]=0;
printf("\n The correct information is :");
for(i=0;i<7;i++)
printf("%d",r[i]);
printf("\n The data bits are : ");
for(i=0;i<4;i++)
printf("%d",r[i]);
}

Output
A byte of data: 10011010(ip-user)
c programming for follwing steps:
Create the data word, leaving spaces for the parity bits: _ _ 1 _ 0 0 1 _ 1 0 1 0
Calculate the parity for each parity bit (a ? represents the bit position being set):

Position 1 checks bits 1,3,5,7,9,11:


? _ 1 _ 0 0 1 _ 1 0 1 0. Even parity so set position 1 to a 0: 0 _ 1 _ 0 0 1 _ 1 0 1 0
Position 2 checks bits 2,3,6,7,10,11:
0 ? 1 _ 0 0 1 _ 1 0 1 0. Odd parity so set position 2 to a 1: 0 1 1 _ 0 0 1 _ 1 0 1 0
Position 4 checks bits 4,5,6,7,12:
0 1 1 ? 0 0 1 _ 1 0 1 0. Odd parity so set position 4 to a 1: 0 1 1 1 0 0 1 _ 1 0 1 0
Position 8 checks bits 8,9,10,11,12:
0 1 1 1 0 0 1 ? 1 0 1 0. Even parity so set position 8 to a 0: 0 1 1 1 0 0 1 0 1 0 1 0
Code word: 011100101010. (output)
CRC

#include<stdio.h>
#include<string.h>
#define N strlen(g)

char t[28],cs[28],g[]="10001000000100001";
int a,e,c;

void xor(){
for(c = 1;c < N; c++)
cs[c] = (( cs[c] == g[c])?'0':'1');
}

void crc(){
for(e=0;e<N;e++)
cs[e]=t[e];
do{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}

int main()
{
printf("\nEnter data : ");
scanf("%s",t);
printf("\n----------------------------------------");
printf("\nGeneratng polynomial : %s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\n----------------------------------------");
printf("\nModified data is : %s",t);
printf("\n----------------------------------------");
crc();
printf("\nChecksum is : %s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\n----------------------------------------");
printf("\nFinal codeword is : %s",t);
printf("\n----------------------------------------");
printf("\nTest error detection 0(yes) 1(no)? :
");
scanf("%d",&e);
if(e==0)
{
do{
printf("\nEnter the position where error is to be inserted : ");
scanf("%d",&e);
}while(e==0 || e>a+N-
1);
t[e-1]=(t[e-1]=='0')?'1':'0';
printf("\n----------------------------------------");
printf("\nErroneous data : %s\n",t);
}
crc();
for(e=0;(e<N-1) && (cs[e]!='1');e++);
if(e<N-1)
printf("\nError detected\n\n");
Else
printf("\nNo error detected\n\n");
printf("\n----------------------------------------\n");
return 0;
}
OUTPUT:

Enter data : 1101

—————————————-
Generatng polynomial : 10001000000100001
—————————————-
Modified data is : 11010000000000000000
—————————————-
Checksum is : 1101000110101101
—————————————-
Final codeword is : 11011101000110101101
—————————————-
Test error detection 0(yes) 1(no)? : 0

Enter the position where error is to be inserted : 2

—————————————-
Erroneous data : 10011101000110101101

Error detected
Character count

#include <stdio.h>
#include <string.h>

void find_frequency(char [], int []);

int main()
{
char string[100];
int c, count[26] = {0};

printf("Input a string\n");
gets(string);

find_frequency(string, count);

printf("Character Count\n");

for (c = 0 ; c < 26 ; c++)


printf("%c \t %d\n", c + 'a', count[c]);

return 0;
}

void find_frequency(char s[], int count[]) {


int c = 0;

while (s[c] != '\0') {


if (s[c] >= 'a' && s[c] <= 'z' )
count[s[c]-'a']++;
c++;
}
}
Djikstra

#include<stdio.h>
#include<stdlib.h>

int main()
{
int graph[15][15],s[15],pathestimate[15],mark[15];
int num_of_vertices,source,i,j,u,predecessor[15];
int count=0,dest;
int minimum(int a[],int m[],int k);
void printpath(int,int,int[]);
printf(“nenter the number of vertices: “);
scanf(“%d”,&num_of_vertices);
if(num_of_vertices<=0)
{
printf(“n this is meaninglessn”);
exit(1);
}
printf(“n enter the adjacent matrixn”);
for(i=1;i<=num_of_vertices;i++)
{
printf(“nenter the element of row %dn”,i);
for(j=1;j<=num_of_vertices;j++)
{
scanf(“%d”,&graph[i][j]);
}
}
printf(“nenter the source vertex: n”);
scanf(“%d”,&source);
for(j=1;j<=num_of_vertices;j++)
{
mark[j]=0;
pathestimate[j]=999;
predecessor[j]=0;
}

pathestimate=0;

while(count<num_of_vertices){

u=minimum(pathestimate,mark,num_of_vertices);

s[++count]=u;

mark[u]=1;

for(i=1;i<=num_of_vertices;i++)

{
if(graph[u][i]>0)

if(mark[i]!=1)

if(pathestimate[i]>pathestimate[u]+graph[u][i])

pathestimate[i]=pathestimate[u]+graph[u][i];

predecessor[i]=u;

for(i=1;i<=num_of_vertices;i++)

printpath(source,i,predecessor);

if(pathestimate[i]!=999)

printf(“–>(%d)n”,pathestimate[i]);

return 0;

int minimum(int a[],int m[],int k)

int mi=999;
int i,t;

for(i=1;i<=k;i++)

if(m[i]!=1)

if(mi>a[i])

mi=a[i];

t=i;

return t;

void printpath(int x,int i,int p[])

printf(“n”);

if(i==x)

printf(“%d->”,x);

else if(p[i]==0)

printf(“n no path from %d to %d “,x,i);

else
{

printpath(x,p[i],p);

printf(“%d->”,i);

You might also like