Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ****************************************************************
- CRC
- #include <stdio.h>
- #include <string.h>
- int main()
- {
- int i,j,divbit,databit,count=0;
- char data[100], div[30],temp[30],quot[100],rem[30],div1[30];
- printf("Enter the number of bits in the data :");
- scanf("%d",&databit);
- printf("Enter data: ");
- scanf("%s",data);
- printf("Enter the number of bits in the divisor:");
- scanf("%d",&divbit);
- printf("Enter divisor: ");
- scanf("%s",div);
- strcpy(div1,div);
- for(i=0;i<divbit-1;i++)
- {
- data[databit+i]='0';
- }
- for(i=0;i<divbit;i++)
- temp[i]=data[i];
- for(i=0;i<databit;i++)
- {
- quot[i]=temp[0];
- if(quot[i]=='0')
- for(j=0;j<divbit;j++)
- div[j]='0';
- else
- for(j=0;j<divbit;j++)
- div[j]=div1[j];
- for(j=divbit-1;j>0;j--)
- {
- if(temp[j]==div[j])
- rem[j-1]='0';
- else
- rem[j-1]='1';
- }
- rem[divbit-1]=data[i+divbit];
- strcpy(temp,rem);
- }
- strcpy(rem,temp);
- printf("\nRemainder is ");
- for(i=0;i<divbit-1;i++)
- printf("%c",rem[i]);
- printf("\nCRC code is: ");
- for(i=0;i<databit;i++)
- printf("%c",data[i]);
- for(i=0;i<divbit-1;i++)
- printf("%c",rem[i]);
- return 0;
- }
- ************************************************************************************
- CRC (generate and Check)
- #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;
- }
- ****************************************************
- ALT (think better)
- #include<stdio.h>
- #include <string.h>
- int main()
- {
- int i,j,keylen,msglen;
- char data[100], key[30],temp[30],quot[100],rem[30],key1[30];
- printf("Enter Data: ");
- gets(data);
- printf("Enter Key: ");
- gets(key);
- keylen=strlen(key);
- msglen=strlen(data);
- strcpy(key1,key);
- for(i=0;i<keylen-1;i++)
- {
- data[msglen+i]='0';
- }
- for(i=0;i<keylen;i++)
- temp[i]=data[i];
- for(i=0;i<msglen;i++)
- {
- quot[i]=temp[0];
- if(quot[i]=='0')
- for(j=0;j<keylen;j++)
- key[j]='0';
- else
- for(j=0;j<keylen;j++)
- key[j]=key1[j];
- for(j=keylen-1;j>0;j--)
- {
- if(temp[j]==key[j])
- rem[j-1]='0';
- else
- rem[j-1]='1';
- }
- rem[keylen-1]=data[i+keylen];
- strcpy(temp,rem);
- }
- strcpy(rem,temp);
- printf("\nQuotient is ");
- for(i=0;i<msglen;i++)
- printf("%c",quot[i]);
- printf("\nRemainder is ");
- for(i=0;i<keylen-1;i++)
- printf("%c",rem[i]);
- printf("\nFinal data is: ");
- for(i=0;i<msglen;i++)
- printf("%c",data[i]);
- for(i=0;i<keylen-1;i++)
- printf("%c",rem[i]);
- return 0;
- }
- *******************************
- Algorithm --on paper
- 1. Insert the Message to be encoded.
- 2. Zero Padding is done corresponding to the bit length n of CRC.
- 3. Check if the input bit above the leftmost divisor bit is 1 , do
- divisor XOR input .
- 4.Repeat step 3 until divisor traverses the input row ( Left to Right).
- 5. The 'n' non-zero bits on the right-hand end of the row is the value of the CRC function.
- ####################################################################################################
- Checksum
- Algorithm :
- 1. Insert both the hex values.
- 2. Set check=one+two and check=check.
- 3. Calculate and Compare checkresult .
- 4. Check if they are equal , then print value.
- 5. Else print that the generated checksum some is wrong.
- #include<stdio.h>
- #include<stdlib.h>
- #include<fentl.h>
- int main()
- {
- unsigned int one;
- unsigned int two;
- unsigned int check;
- unsigned int checkresult;
- printf("\nEnter the first hex value:");
- scanf("%x",&one);
- printf("\nEnter the second hex value:");
- scanf("%x",&one);
- check=one+two;
- check=check;
- printf("\nThe value of check is:%x",check);
- checkresult=one+two+check;
- printf("\The value of checkresult:%x",checkresult);
- checkresult=checkresult;
- printf("\n The value of answer is :%x",check result);
- else
- printf("\n The check sum of the code generated is not correct");
- }
- ***************************8
- ALT(think better)
- PROGRAM TO CALCULATE CHECKSUM
- #include<stdio.h>
- #include<math.h>
- int sender(int b[10],int k)
- {
- int checksum,sum=0,i;
- printf("\n****SENDER****\n");
- for(i=0;i<k;i++)
- sum+=b[i];
- printf("SUM IS: %d",sum);
- checksum=~sum;
- printf("\nSENDER's CHECKSUM IS:%d",checksum);
- return checksum;
- }
- int receiver(int c[10],int k,int scheck)
- {
- int checksum,sum=0,i;
- printf("\n\n****RECEIVER****\n");
- for(i=0;i<k;i++)
- sum+=c[i];
- printf(" RECEIVER SUM IS:%d",sum);
- sum=sum+scheck;
- checksum=~sum;
- printf("\nRECEIVER's CHECKSUM IS:%d",checksum);
- return checksum;
- }
- main()
- {
- int a[10],i,m,scheck,rcheck;
- printf("\nENTER SIZE OF THE STRING:");//4 4 inputs array in binary
- scanf("%d",&m);
- printf("\nENTER THE ELEMENTS OF THE ARRAY:");
- for(i=0;i<m;i++)
- scanf("%d",&a[i]);
- scheck=sender(a,m);
- rcheck=receiver(a,m,scheck);
- if(rcheck==0)
- printf("\n\nNO ERROR IN TRANSMISSION\n\n");
- else
- printf("\n\nERROR DETECTED");
- return 0;
- }
- ####################################################################################################
- Hamming Code
- #include<stdio.h>
- #include<math.h>
- int main(){
- int n,i,j,k,ip,r,temp,p;
- int data[30],final[30],parity[10];
- printf("\nEnter Number of bits:");
- scanf("%d",&n);
- printf("\nEnter the data to be sent:");
- scanf("%d",&ip);
- for(i=n-1;i>=0;i--)
- {
- data[i]=ip%10;
- ip=ip/10;
- }
- for(r=1;r<n;r++)
- {
- if(n<=pow(2,r)-1-r){
- break;
- }
- }
- for(i=1;i<=n+r;i=i*2)
- {
- final[i]=-1;
- }
- for(i=1,j=0;i<=n+r;i++){
- if(final[i]!=-1){
- final[i]=data[j];
- j+=1;
- }
- }
- for(i=0;i<r;i++){
- p=pow(2,i);
- temp=0;
- for(j=p;j<=n+r;j=j+2*p){
- for(k=0;k<p && j+k<n+r ;k++){
- if(final[j+k]!=-1){
- temp=final[j+k]^temp;
- }
- }
- }
- parity[i]=temp;
- }
- for(i=1,j=0;i<=n+r;i++){
- if(final[i]==-1){
- final[i]=parity[j];
- j+=1;
- }
- }
- printf("Hamming Code=");
- for(i=1;i<=n+r;i++){
- printf("%d",final[i]);
- }
- printf("\n");
- }
- ####################################################################################################
- Sliding Window Protocol(C)
- Server side
- #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);
- }
- Client Side
- #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);
- }
- }
- }
- ####################################################################################################
- OSI LAYER
- #include<stdio.h>
- #include<string.h>
- int main()
- {
- char charstr[40],temp[40];
- int i;
- printf("Enter the input stream\n");
- gets(charstr);
- // Application layer
- printf("\nApplication layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"al");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- // Presentation Layer
- printf("\nPresentation layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"pl");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- //Session Layer
- printf("\nSession layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"sl");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- //Transport Layer
- printf("\nTransport layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"tl");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- //Network Layer
- printf("\nNetwork layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"nl");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- //Data Link layer
- printf("\nData Link layer (sender): ");
- printf("\n\tReceived: %s",charstr);
- strcpy(temp,"dl");
- strcat(temp,charstr);
- strcpy(charstr,temp);
- printf("\n\tForwarded: %s",charstr);
- //Physical layer
- printf("\nPhysical layer(sender) \n\tData sent to the receiver: %s",charstr);
- //Physical layer
- printf("\n\n\nPhysical layer(receiver) \n\tData received: %s",charstr);
- //Data Link layer
- printf("\nData Link layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- //Network layer
- printf("\nNetwork layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- //Transport layer
- printf("\nTransport layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- //Session layer
- printf("\nSession layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- //Presentation layer
- printf("\nPresentation layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- //Application layer
- printf("\nApplication layer (Receiver): ");
- printf("\n\tReceived: %s",charstr);
- for(i=0;i<strlen(charstr);i++)
- {
- charstr[i]=charstr[i+2];
- }
- printf("\n\tForwarded: %s",charstr);
- printf("\n\nOutput presented to user: %s",charstr);
- return 0;
- }
- Algorithm *******************
- 1. Read the input string and address.
- 2. Add application header.
- 3. Print the string.
- 4. Add the presentation layer header.
- 5. Print the string.
- 6. Add the Session layer header.
- 7. Print the string.
- 8. Add the Transport layer header.
- 9. Print the string.
- 10. Add the Network layer header.
- 11. Print the string.
- 12. Add the Datalink layer header.
- 13. Print the string
- 14. Send to the physical layer.
- 15. Print the string
- **********************
- #include<stdio.h>
- #include<conio.h>
- #include<string.h>
- const char * xtract(char []);
- int main()
- {
- char arr[50],ah[]="AH",fin[50],temp[50],ph[]="PH",sh[]="SH",th[]="TH",nh[]="NH",dh[]="DH";
- int addr;
- printf("Transmitter\n\n\n");
- printf("Enter the input string : ");
- gets(arr);
- printf("Enter the address : ");
- scanf("%d",&addr);
- strcpy(fin,ah);
- strcat(fin,arr);
- printf("\n\nApplication layer : ");
- puts(fin);
- printf("\n");
- strcpy(temp,ph);
- strcat(temp,fin);
- strcpy(fin,temp);
- printf("Presentation layer : ");
- puts(fin);
- printf("\n");
- strcpy(temp,sh);
- strcat(temp,fin);
- strcpy(fin,temp);
- printf("Session layer : ");
- puts(fin);
- printf("\n");
- strcpy(temp,th);
- strcat(temp,fin);
- strcpy(fin,temp);
- printf("Transport layer : ");
- puts(fin);
- printf("\n");
- strcpy(temp,nh);
- strcat(temp,fin);
- strcpy(fin,temp);
- printf("Network layer : ");
- puts(fin);
- printf("\n");
- strcpy(temp,dh);
- strcat(temp,fin);
- strcpy(fin,temp);
- printf("Data link layer : ");
- puts(fin);
- printf("\n");
- printf("Message entered into physical layer and transmitted\n\n\nReceiver\n\n\n");
- printf("Datalink layer : ");
- puts(fin);
- printf("\nNetwork layer : ");
- strcpy(temp,xtract(fin));
- printf("\nTransport layer : ");
- strcpy(temp,xtract(temp));
- printf("\nSession layer : ");
- strcpy(temp,xtract(temp));
- printf("\nPresentation layer : ");
- strcpy(temp,xtract(temp));
- printf("\nApplication layer : ");
- strcpy(temp,xtract(temp));
- getch();
- return 0;
- }
- const char * xtract(char arr[])
- {
- char * output = malloc(100);
- int l=strlen(arr);
- int i;
- for(i=0;i<l;i++)
- {
- output[i]=arr[i+2];
- }
- puts(output);
- return (char *)output;
- }
- ####################################################################################################
- BIT STUFFING -DE
- Algorithm :
- 1. a flag “01111110” is embedded at the starting and the ending of the data.
- 2. if data bit is 1 increment count else count is zero.
- 3. If count is five store a zero bit after the five 1 s in the data array.
- 4. Repeat step 3 till the end of data.
- 5. If the data bit is 1 increment count else count is zero.
- 6. If the count is five and the next bit is zero then store the next bit after zero in the data array.
- 7. De stuffed data is transmitted without flags.
- *******************
- Code :
- #include<stdio.h>
- #include<string.h>
- #define DELIM_BIT_PATTERN "01111110"
- #define SNDR_INPUT 0
- #define SNDR_OUTPUT 1
- #define REC_INPUT 2
- #define REC_OUTPUT 3
- char data[4][100];
- int valid_data(void);
- void sender_bit_stuff(void);
- void receiver_process_data(void);
- int main()
- {
- int ans;
- do{
- printf("\nEnter Data from Netwrok Layer in Binary Form:");
- scanf("%s",data[SNDR_INPUT]);
- if(!valid_data())
- continue;
- sender_bit_stuff();
- printf("\nSenders Physical Layer Data:%s\n",data[SNDR_OUTPUT]);
- strcpy(data[REC_INPUT],data[SNDR_OUTPUT]);
- receiver_process_data();
- printf("\nReceiver's Network Layer Data: %s\n",data[REC_OUTPUT]);
- printf("\n\nDo you want to continue?(y: 1/n: 0)");
- scanf("%d",&ans);
- }while(ans!=0);
- }
- int valid_data(){
- char *p=data[SNDR_INPUT];
- if(*p=='\0'){
- printf("\n***Enter Some DAta***\n");
- return 0;
- }
- while(*p!='\0'){
- if(*p!='1' && *p!='0'){
- printf("** this is not binary data. please Enter 0's and 1's\n");
- }
- p++;
- }
- return 1;
- }
- void sender_bit_stuff(void){
- char *src=data[SNDR_INPUT];
- char *dst=data[SNDR_OUTPUT];
- int count=0;
- strcpy(dst,DELIM_BIT_PATTERN);
- dst+=strlen(DELIM_BIT_PATTERN);
- while(*src!='\0')
- {
- if(count==5){
- *dst='0';
- dst+=1;
- count=0;
- }
- if(*src=='1')
- count++;
- else
- count=0;
- *dst++=*src++;
- }
- if(*src=='\0' && count==5){
- *dst='0';
- dst+=1;
- }
- strcpy(dst,DELIM_BIT_PATTERN);
- dst+=strlen(DELIM_BIT_PATTERN);
- *dst='\0';
- }
- void receiver_process_data(void){
- char *src=data[REC_INPUT];
- char *dst=data[REC_OUTPUT];
- char *end;
- int count=0;
- src+=strlen(DELIM_BIT_PATTERN);
- end=data[REC_INPUT]+strlen(data[REC_INPUT])-strlen(DELIM_BIT_PATTERN);
- while(src<=end)
- {
- if(count==5)
- src+=1;
- count=0;
- if(*src=='1')
- count++;
- else
- count=0;
- *dst++=*src++;
- }
- *(dst-1)='\0';
- return;
- }
- ***************************************************
- ALT
- #include<stdio.h>
- #include<conio.h>
- #include<string.h>
- void main()
- {
- int a[20],b[30],i,j,k,count,n;
- printf("enter length of frame-");
- scanf("%d",&n);
- printf("enter frame-");
- 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:");
- printf("01111110");
- for(i=0;i<j;i++)
- printf("%d",b[i]);
- printf("01111110");
- }
- ###################################################################################
- BYTE STUFFING (CHARACTER STUFFF)
- Aim :
- To write a C program to implement the data link layer framing method byte stuffing.
- Algorithm :
- 1. As the DLE characters are non printable characters. The ASCII values of the printable
- characters like *,#,$ are assigned to DLE, STX, ETX.
- 2. If the ASCII value that is assigned to DLE occurs in the data array another DLE character
- is stuffed and stored in the array and transmitted along with starting and ending flags.
- 3. If the ASCII value of DLE occurs in the data array, the next bit is stored in to the array and
- transmitted with out the flags.
- 4. Here whenever the program encounters characters like * the string DLE is added to the original string.
- *************************
- Code :
- #include<stdio.h>
- #include<string.h>
- #define FLAG_BYTE "$"
- #define ESCAPE_BYTE "#"
- void byte_stuff();
- char input_buf[100];
- char output_buf[100];
- main(){
- int ans;
- do{
- input_buf[0]='\0';
- output_buf[0]='\0';
- printf("\nFLAG_BYTE:$,ESC_BYTE=#\n");
- printf("\nEnter th data from Network Layer:");
- scanf("%s",input_buf);
- byte_stuff();
- printf("\nData to the physical Layer:%s",output_buf);
- printf("\nDo you want to continue?(Y: 1/N: 0):");
- scanf("%d",&ans);
- }while(ans!=0);
- return 0;
- }
- void byte_stuff(void){
- int i=0,j=1;
- output_buf[0]='$';
- for(;input_buf[i]!='\0';i++,j++)
- {
- if(input_buf[i]!='$' && input_buf[i]!='#')
- output_buf[j]=input_buf[i];
- else{
- output_buf[j++]='#';
- output_buf[j]=input_buf[i];
- }
- }
- output_buf[j]='$';
- output_buf[j++]='\0';
- }
- ***************************************
- ALT
- #include<stdio.h>
- #include<conio.h>
- void main()
- {
- char frame[100],str[50];
- char flag='z';
- char esc='x';
- int i,j,k=0,n;
- frame[k++]='z';
- printf("Enter String \n");
- gets(str);
- for(j=0;j<strlen(str);j++)
- {
- if(str[j]!=flag&&str[j]!=esc)
- {
- frame[k++]=str[j];
- }
- else{
- frame[k++]='x';
- frame[k++]=str[j];
- }
- }
- frame[k++]='z';
- frame[k++]='\0';
- printf("\nByte stuffing at sender side:\n\n");
- for(i=0;i<k;i++)
- {
- printf("%c",frame[i]);
- }
- printf("\nByte stuffing at receiver side\n\n");
- for(i=0;i<k;i++)
- {
- if(frame[i]=='x'|| frame[i]=='z')
- {
- i++;
- }
- printf("%c",frame[i]);
- }
- }
- **************************************
- ALT 3
- #include<stdio.h>
- #include<string.h>
- void main()
- {
- int j,l,m,c,k;
- char a[50],b[50];
- printf("Enter the string:");
- gets(a);
- strcpy(b,"DLESTX");
- m=strlen(a);
- for(j=0;j<m;)
- {
- if(a[j]=='d')
- {
- if(a[j+1]=='l')
- {
- if(a[j+2]=='e')
- {
- c=j+2;
- for(l=0;l<3;l++)
- {
- for(k=m;k>c;k--)
- {
- a[k]=a[k-1];
- }
- m++;
- a[m]=' ';
- c+=1;
- }
- a[j+3]='d';
- a[j+4]='l';
- a[j+5]='e';
- a[m]=' ';
- j+=5;
- }
- }
- }
- j++;
- }
- strcat(b,a);
- strcat(b,"DLEETX");
- printf("\n%s",b);
- printf("\nReceiver side:");
- m=strlen(a);
- for(j=0;j<m;)
- {
- if(a[j]=='d')
- {
- if(a[j+1]=='l')
- {
- if(a[j+2]=='e')
- {
- c=j;
- for(l=0;l<3;l++)
- {
- for(k=c;k<m;k++)
- a[k]=a[k+1];
- }
- c++;
- }
- j=c;
- }
- }
- j++;
- }
- printf("\n%s\n",a);
- }
- #################################################################################
- CHARACTER COUNT
- Aim :
- To write a C program to implement the data link layer framing method character count.
- Algorithm :
- 1. At the sender side the user is asked to enter the number of frames he want to transmit.
- 2. Depending upon the input, that many number of frames are taken as input from the user
- and stored in a 2 by 2 matrix.
- 3. The length of each frame is calculated and stored in a new array.
- 4.While out putting the frame, the length of each frame is added to the each frame and finally
- all the frames are appended and sent as a single string.
- 5. At the receiver side, the first number is treated as the length of the first frame and the string
- is extracted and displayed.
- 6. The next number is treated as the length of the next frame and so on.
- Code :
- #include<stdio.h>
- #include<string.h>
- char input[10][20];
- int get_input();
- void make_frames(int);
- int count_chars(int s);
- void main()
- {
- int no_of_words=get_input();
- make_frames(no_of_words);
- }
- int get_input()
- {
- int answer;
- int i=0;
- do{
- printf("\nEnter the Word:");
- scanf("%s",input[i]);
- fflush(stdin);
- printf("\nDo you want to continue: (y: 1/n: 0)?:");
- scanf("%d",&answer);
- i++;
- }while(answer!=0);
- return i;
- }
- void make_frames(int num_words){
- int i=0;
- printf("\nThe Transmitted Data is:\n\t");
- for(;i<num_words;i++)
- printf("%d%s",(count_chars(i)+1),input[i]);
- printf("\n\n");
- }
- int count_chars(int index)
- {
- int i=0;
- while(input[index][i]!='\0')
- i++;
- return i;
- }
- #####################################################################################
- GO BACK AND SELECT ARQ
- Code
- #include<stdio.h>
- #include<math.h>
- int main()
- {
- int windowsize,sent=0,acknw,i,m,p;
- printf("Enter no. of bits: ");
- scanf("%d",&m);
- p=pow(2,m);
- printf("The no. of Packets that has transmitted are: %d\n",p);
- windowsize=pow(2,m)-1;
- printf("The Windowsize is: %d\n",windowsize);
- while(1)
- {
- for(i=0;i<windowsize;i++)
- {
- printf("Frame %d has been transmitted \n",sent);
- sent++;
- if(sent==windowsize)
- break;
- }
- printf("\n Please enter the last Acknowledgement received:\n");
- scanf("%d",&acknw);
- if(acknw==windowsize)
- break;
- else
- sent=acknw;
- }
- return 0;
- }
- ############################################################################################
- SELECTIVE REPEAT:
- #include<stdio.h>
- #include<math.h>
- int main()
- {
- int windowsize,sent=0,acknw,i,m,p;
- int n=1;
- printf("Enter no. of bits:");
- scanf("%d",&m);
- p=pow(2,m);
- printf("The no. of Packets has transmitted are: %d\n",p);
- windowsize=pow(2,m-1);
- printf("The Windowsize is: %d\n",windowsize);
- while(1)
- {
- while(n>0)
- {
- for(i=0;i<windowsize;i++)
- {
- printf("Frame %d has been transmitted\n",sent);
- sent++;
- if(sent==windowsize)
- break;
- }
- n=0;
- }
- printf("\n Please enter the Acknowledgement received:\n");
- scanf("%d",&acknw);
- if(acknw>windowsize)
- {
- printf("All previous packetsreceived");
- break;
- }
- else
- {
- sent=acknw;
- printf("Resend the %d packet",sent);
- }
- return 0;
- }
- }
- #############################################################################################
- #############################################################################################
- ############################################################################################
- Write a program to display the name of the computer and its IP address that you are currently
- working on.
- code:
- import java.net.*;
- import java.io.*;
- public class ex2
- {
- public static void main(String args[]) throws Exception
- {
- InetAddress ipadd =InetAddress.getLocalHost();
- System.out.println("Host and Address :"+ipadd);
- System.out.println("Host name :"+ipadd.getHostName());
- String n=ipadd.toString();
- System.out.println("IP address :"+n.substring(n.indexOf("/")+1));
- }
- }
- ##############################################################################################
- To implement echo server and client in java using TCP sockets.
- Code:
- echo client:
- import java.io.*;
- import java.net.*;
- public class ex52
- {
- public static void main(String args[]) throws Exception
- {
- try {
- int Port;
- BufferedReader Buf =new BufferedReader(new InputStreamReader(System.in));
- System.out.print(" Enter the Port Address : " );
- Port=Integer.parseInt(Buf.readLine());
- Socket sok=new Socket("localhost",Port);
- if(sok.isConnected()==true)
- System.out.println(" Server Socket is Connected Succecfully. ");
- InputStream in=sok.getInputStream();
- OutputStream ou=sok.getOutputStream();
- PrintWriter pr=new PrintWriter(ou);
- BufferedReader buf1=new BufferedReader(new InputStreamReader(System.in));
- BufferedReader buf2=new BufferedReader(new InputStreamReader(in));
- String str1,str2;
- System.out.print(" Enter the Message : ");
- str1=buf1.readLine();
- pr.println(str1);
- pr.flush();
- System.out.println(" Message Send Successfully. ");
- str2=buf2.readLine();
- System.out.println(" Message From Server : " + str2);
- }
- catch(Exception e)
- {
- System.out.println(" Error : " + e.getMessage());
- }
- }
- }
- echo server:
- import java.io.*;
- import java.net.*;
- public class ex5
- {
- public static void main(String args[]) throws Exception
- {
- try
- {
- int Port;
- BufferedReader Buf =new BufferedReader(new InputStreamReader(System.in));
- System.out.print(" Enter the Port Address : " );
- Port=Integer.parseInt(Buf.readLine());
- ServerSocket sok =new ServerSocket(Port);
- System.out.println(" Server is Ready To Receive a Message. ");
- System.out.println(" Waiting ..... ");
- Socket so=sok.accept();
- if(so.isConnected()==true)
- System.out.println(" Client Socket is Connected Succecfully. ");
- InputStream in=so.getInputStream();
- OutputStream ou=so.getOutputStream();
- PrintWriter pr=new PrintWriter(ou);
- BufferedReader buf=new BufferedReader(new InputStreamReader(in));
- String str=buf.readLine();
- System.out.println(" Message Received From Client : " + str);
- System.out.println(" This Message is Forwarded To Client. ");
- pr.println(str);
- pr.flush();
- }
- catch(Exception e)
- {
- System.out.println(" Error : " + e.getMessage());
- }
- }
- }
- #################################################################################
- To implement date server and client in java using TCP sockets.
- code:
- server:
- import java.net.*;
- import java.io.*;
- import java.util.*;
- class ex8
- {
- public static void main(String arg[])
- {
- ServerSocket ss = null;
- Socket cs;
- PrintStream ps;
- BufferedReader dis;
- String inet;
- try
- {
- ss = new ServerSocket(4444);
- System.out.println("Press Ctrl+C to quit");
- while(true)
- {
- cs = ss.accept();
- ps = new PrintStream(cs.getOutputStream());
- Date d = new Date();
- ps.println(d);
- dis = new BufferedReader(new
- InputStreamReader(cs.getInputStream()));
- inet = dis.readLine();
- System.out.println("Client System/IP address is :"
- + inet);
- ps.close();
- dis.close();
- }
- }
- catch(IOException e)
- {
- System.out.println("The exception is :" + e);
- }
- }
- }
- client:
- import java.net.*;
- import java.io.*;
- class ex81
- {
- public static void main (String args[])
- {
- Socket soc;
- BufferedReader dis;
- String sdate;
- PrintStream ps;
- try
- {
- InetAddress ia=InetAddress.getLocalHost();
- if(args.length==0)
- soc=new Socket(InetAddress.getLocalHost(),4444);
- else
- soc=new Socket(InetAddress.getByName(args[0]),4444);
- dis=new BufferedReader(new
- InputStreamReader(soc.getInputStream()));
- sdate=dis.readLine();
- System.out.println("The date/time on server is : "+sdate);
- ps=new PrintStream(soc.getOutputStream());
- ps.println(ia);
- ps.close();
- }
- catch(IOException e)
- {
- System.out.println("THE EXCEPTION is :" + e);
- }
- }
- }
- #########################################################################################################
- Write a program to implement a simple message transfer from client to server process using TCP/IP.
- Code:
- SERVER: ss1
- import java.io.*;
- import java.net.*;
- public class ss1
- {
- public static void main(String args[])throws IOException
- {
- ServerSocket s=new ServerSocket(1234);
- Socket s1=s.accept();
- InputStream s1in=s1.getInputStream();
- OutputStream s1out=s1.getOutputStream();
- int n=100;
- BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
- byte b[];
- while (n==100)
- {
- byte b2[]=new byte[20];
- String id=inFromUser.readLine();
- b=id.getBytes();
- s1out.write(b);
- s1in.read(b2);
- String st= new String(b2);
- System.out.println("Client-1 : "+st);
- }
- s1in.close();
- s1out.close();
- s1.close();
- }
- }
- CLIENT: cc1
- import java.io.*;
- import java.net.*;
- public class cc1
- {
- public static void main(String args[])throws IOException
- {
- Socket s1=new Socket("localhost", 1234);
- OutputStream s1out=s1.getOutputStream();
- InputStream s1in=s1.getInputStream();
- int n=100;
- BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
- byte b[];
- while (n==100)
- {
- String id=inFromUser.readLine();
- b=id.getBytes();
- s1out.write(b);
- byte b2[]=new byte[20];
- s1in.read(b2);
- String st=new String(b2);
- System.out.println("Server : " + st);
- }
- s1in.close();
- s1out.close();
- s1.close();
- }
- }
- ##############################################################################################
- Develop a TCP client/server application for transferring a text file from client to server?
- code:
- server:
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.OutputStream;
- import java.net.InetAddress;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class ex10s {
- public static void main(String[] args) throws Exception {
- ServerSocket ssock = new ServerSocket(5000);
- Socket socket = ssock.accept();
- InetAddress IA = InetAddress.getByName("localhost");
- File file = new File("e:\\data1.bin");
- FileInputStream fis = new FileInputStream(file);
- BufferedInputStream bis = new BufferedInputStream(fis);
- OutputStream os = socket.getOutputStream();
- byte[] contents;
- long fileLength = file.length();
- long current = 0;
- long start = System.nanoTime();
- while(current!=fileLength){
- int size = 10000;
- if(fileLength - current >= size)
- current += size;
- else{
- size = (int)(fileLength - current);
- current = fileLength;
- }
- contents = new byte[size];
- bis.read(contents, 0, size);
- os.write(contents);
- System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
- }
- os.flush();
- socket.close();
- ssock.close();
- System.out.println("File sent succesfully!");
- }
- }
- client:
- import java.io.BufferedOutputStream;
- import java.io.FileOutputStream;
- import java.io.InputStream;
- import java.net.InetAddress;
- import java.net.Socket;
- public class ex10c
- {
- public static void main(String[] args) throws Exception{
- Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
- byte[] contents = new byte[10000];
- FileOutputStream fos = new FileOutputStream("e:\\data2.bin");
- BufferedOutputStream bos = new BufferedOutputStream(fos);
- InputStream is = socket.getInputStream();
- int bytesRead = 0;
- while((bytesRead=is.read(contents))!=-1)
- bos.write(contents, 0, bytesRead);
- bos.flush();
- socket.close();
- System.out.println("File saved successfully!");
- }
- }
- #############################################################################
- To implement a chat server and client in java using TCP sockets.
- code:
- server:
- import java.io.*;
- import java.net.*;
- public class ser
- {
- public static void main(String args[])throws IOException
- {
- ServerSocket s=new ServerSocket(1234);
- Socket s1=s.accept();
- InputStream s1in=s1.getInputStream();
- OutputStream s1out=s1.getOutputStream();
- int n=100;
- BufferedReader inUser=new BufferedReader(new InputStreamReader(System.in));
- byte b[];
- while(n==100)
- {
- byte b2[]=new byte[20];
- s1in.read(b2);
- String st=new String(b2);
- System.out.println(st);
- String id=inUser.readLine();
- b=id.getBytes();
- s1out.write(b);
- }
- s1in.close();
- s1out.close();
- s1.close();
- }
- }
- client:
- import java.io.*;
- import java.net.*;
- public class cln
- {
- public static void main(String args[])throws IOException
- {
- Socket s1=new Socket("localhost",1234);
- OutputStream s1out=s1.getOutputStream();
- InputStream s1in=s1.getInputStream();
- int n=100;
- BufferedReader inuser=new BufferedReader(new InputStreamReader(System.in));
- byte b[];
- while(n==100)
- {
- String id=inuser.readLine();
- b=id.getBytes();
- s1out.write(b);
- byte b2[]=new byte[20];
- s1in.read(b2);
- String st=new String(b2);
- System.out.println(st);
- }
- s1in.close();
- s1out.close();
- s1.close();
- }
- }
- ##############################################################################
- USERNAME AND PASSWORD AUTHENTICATE
- Implement a TCP based server program to authenticate the client’s User Name and Password. The validity of the client must be sent as the reply message to the client and display it on the standard output.
- code:
- server:
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class auth
- {
- public static void main(String args[]) throws IOException
- {
- ServerSocket s= new ServerSocket(1234);
- Socket S1=s.accept();
- InputStream S1in=S1.getInputStream();
- OutputStream S1out=S1.getOutputStream();
- byte b1[]=new byte[20];
- byte b[]=new byte[20];
- S1in.read(b);
- String st=new String(b);
- System.out.println(st);
- S1in.read(b1);
- String st1=new String(b1);
- System.out.println(st1);
- if(st.equals(st1))
- {
- String yes="Valid";
- System.out.println("Valid");
- b=yes.getBytes();
- S1out.write(b);
- }
- else
- {
- String yes1="NotValid";
- System.out.println("NotValid");
- b=yes1.getBytes();
- S1out.write(b);
- }
- S1out.close();
- S1in.close();
- S1.close();
- }
- }
- client:
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class client
- {
- public static void main(String args[]) throws IOException
- {
- Socket s1= new Socket("localhost",1234);
- OutputStream s1out=s1.getOutputStream();
- InputStream s1in=s1.getInputStream();
- BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
- byte b1[],b[];
- System.out.println("Enter the Username");
- String id=inFromUser.readLine();
- b=id.getBytes();
- System.out.println("Enter the password");
- String passwrd=inFromUser.readLine();
- b1=passwrd.getBytes();
- s1out.write(b);
- s1out.write(b1);
- byte b2[]=new byte[20];
- s1in.read(b2);
- String st=new String(b2);
- System.out.println(st);
- s1out.close();
- s1.close();
- }
- }
- ########################################################################
- ###########################################################################
- Implement echo server and client in java using UDP sockets.
- Code:
- udps.java
- import java.io.*;
- import java.net.*;
- class udps
- {
- public static int clientport = 8040,serverport = 8050;
- public static void main(String args[]) throws Exception
- {
- DatagramSocket SrvSoc = new DatagramSocket(clientport);
- byte[] SData = new byte[1024];
- BufferedReader br = new BufferedReader(new
- InputStreamReader(System.in));
- System.out.println("Server Ready");
- while (true)
- {
- byte[] RData = new byte[1024];
- DatagramPacket RPack = new DatagramPacket(RData,
- RData.length);
- SrvSoc.receive(RPack);
- String Text = new String(RPack.getData());
- if (Text.trim().length() == 0)
- break;
- System.out.println("\nFrom Client <<< " + Text );
- System.out.print("Msg to Cleint : " );
- String srvmsg = br.readLine();
- InetAddress IPAddr = RPack.getAddress();
- SData = srvmsg.getBytes();
- DatagramPacket SPack = new DatagramPacket(SData,
- SData.length, IPAddr, serverport);
- SrvSoc.send(SPack);
- }
- System.out.println("\nClient Quits\n");
- SrvSoc.close();
- }
- }
- udpc.java
- import java.io.*;
- import java.net.*;
- class udpchatclient
- {
- public static int clientport = 8040,serverport = 8050;
- public static void main(String args[]) throws Exception
- {
- BufferedReader br = new BufferedReader(new
- InputStreamReader (System.in));
- DatagramSocket CliSoc = new DatagramSocket(serverport);
- InetAddress IPAddr;
- String Text;
- if (args.length == 0)
- IPAddr = InetAddress.getLocalHost();
- else
- IPAddr = InetAddress.getByName(args[0]);
- byte[] SData = new byte[1024];
- System.out.println("Press Enter without text to quit");
- while (true)
- {
- System.out.print("\nEnter text for server : ");
- Text = br.readLine();
- SData = Text.getBytes();
- DatagramPacket SPack = new DatagramPacket(SData,
- SData.length, IPAddr, clientport );
- CliSoc.send(SPack);
- if (Text.trim().length() == 0)
- break;
- byte[] RData = new byte[1024];
- DatagramPacket RPack = new DatagramPacket(RData,
- RData.length);
- CliSoc.receive(RPack);
- String Echo = new String(RPack.getData()) ;
- Echo = Echo.trim();
- System.out.println("From Server <<< " + Echo);}
- CliSoc.close();}}
- #################################################################
- Write a program to implement a text based message transfer from client to server process using UDP.
- client
- import java.io.*;
- import java.net.*;
- class udpc
- {
- public static void main(String args[]) throws Exception
- {
- BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
- DatagramSocket clientSocket = new DatagramSocket();
- //Client Socket is created
- InetAddress IPAddress = InetAddress.getByName("localhost");
- //Gets the IP Address
- byte[] sendData = new byte[1024];
- byte[] receiveData = new byte[1024];
- String sentence = inFromUser.readLine();
- sendData = sentence.getBytes();
- //sends data
- DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
- clientSocket.send(sendPacket);
- DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
- clientSocket.receive(receivePacket);
- String modifiedSentence = new String(receivePacket.getData());
- System.out.println("FROM SERVER:" + modifiedSentence);
- clientSocket.close();
- }
- }
- server
- import java.io.*;
- import java.net.*;
- class udps
- {
- public static void main(String args[]) throws Exception
- {
- DatagramSocket serverSocket = new DatagramSocket(9876);
- //Server Socekt Created
- byte[] receiveData = new byte[1024];
- byte[] sendData = new byte[1024];
- while(true)
- {
- DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
- serverSocket.receive(receivePacket);
- String sentence = new String( receivePacket.getData());
- System.out.println("RECEIVED: " + sentence);
- InetAddress IPAddress = receivePacket.getAddress();
- int port = receivePacket.getPort();
- String capitalizedSentence = sentence.toUpperCase();
- //Change sentence to Capital letter
- sendData = capitalizedSentence.getBytes();
- DatagramPacket sendPacket =
- new DatagramPacket(sendData, sendData.length, IPAddress, port);
- serverSocket.send(sendPacket);
- //Send Capitalized data back to client
- }
- }
- }
- ###################################################################################
- . Implement a chat server and client in java using UDP sockets.
- Client:
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class chatclient
- {
- public static void main(String ar[])
- {
- try
- {
- Scanner sc = new Scanner(System.in);
- byte s[] = new byte[1024];
- byte r[] = new byte[1024];
- DatagramSocket ds = new DatagramSocket(4234);
- while(true)
- {
- DatagramPacket drp = new DatagramPacket(r,r.length);
- ds.receive(drp);
- String temp = new String(drp.getData());
- System.out.println(temp);
- int port = drp.getPort();
- InetAddress host = drp.getAddress();
- System.out.println("Enter Message: ");
- String msg = sc.nextLine();
- s = msg.getBytes();
- DatagramPacket dsp = new DatagramPacket(s,s.length,host,port);
- ds.send(dsp);
- }
- }
- catch(Exception e)
- {
- }
- }
- }
- Server:
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class chatserver
- {
- public static void main(String ar[])
- {
- try
- {
- Scanner sc = new Scanner(System.in);
- byte s[] = new byte[1024];
- byte r[] = new byte[1024];
- DatagramSocket ds = new DatagramSocket(6566);
- while(true)
- {
- System.out.println("Enter Message: ");
- String msg = sc.nextLine();
- s = msg.getBytes();
- int port = 4234;
- InetAddress host = InetAddress.getLocalHost();
- DatagramPacket dsp = new DatagramPacket(s,s.length,host,port);
- ds.send(dsp);
- DatagramPacket drp = new DatagramPacket(r,r.length);
- ds.receive(drp);
- String temp = new String(drp.getData());
- System.out.println(temp);
- }
- }
- catch(Exception e)
- {
- }
- }
- }
- ###############################################################################
- &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&THE GREAT C
- C TCP UDP
- To write a socket program to implement a TCP chat application.
- Server Code :
- #include<stdio.h>
- #include<netinet/in.h>
- #include<sys/types.h>
- #include<sys/socket.h>
- #include<netdb.h>
- #include<stdlib.h>
- #include<string.h>
- #define MAX 80
- #define PORT 43454
- #define SA struct sockaddr
- void func(int sockfd)
- {
- char buff[MAX];
- int n;
- for(;;)
- {
- bzero(buff,MAX);
- read(sockfd,buff,sizeof(buff));
- printf("From client: %s\t To client : ",buff);
- bzero(buff,MAX);
- n=0;
- while((buff[n++]=getchar())!='\n');
- write(sockfd,buff,sizeof(buff));
- if(strncmp("exit",buff,4)==0)
- {
- printf("Server Exit...\n");
- break;
- }
- }
- }
- int main()
- {
- int sockfd,connfd,len;
- struct sockaddr_in servaddr,cli;
- sockfd=socket(AF_INET,SOCK_STREAM,0);
- if(sockfd==-1)
- {
- printf("socket creation failed...\n");
- exit(0);
- }
- else
- printf("Socket successfully created..\n");
- bzero(&servaddr,sizeof(servaddr));
- servaddr.sin_family=AF_INET;
- servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
- servaddr.sin_port=htons(PORT);
- if((bind(sockfd,(SA*)&servaddr, sizeof(servaddr)))!=0)
- {
- printf("socket bind failed...\n");
- exit(0);
- }
- else
- printf("Socket successfully binded..\n");
- if((listen(sockfd,5))!=0)
- {
- printf("Listen failed...\n");
- exit(0);
- }
- else
- printf("Server listening..\n");
- len=sizeof(cli);
- connfd=accept(sockfd,(SA *)&cli,&len);
- if(connfd<0)
- {
- printf("server acccept failed...\n");
- exit(0);
- }
- else
- printf("server acccept the client...\n");
- func(connfd);
- close(sockfd);
- }
- Client Code:
- #include<stdio.h>
- #include<netinet/in.h>
- #include<sys/types.h>
- #include<sys/socket.h>
- #include<netdb.h>
- #include<string.h>
- #include<stdlib.h>
- #define MAX 80
- #define PORT 43454
- #define SA struct sockaddr
- void func(int sockfd)
- {
- char buff[MAX];
- int n;
- for(;;)
- {
- bzero(buff,sizeof(buff));
- printf("Enter the string : ");
- n=0;
- while((buff[n++]=getchar())!='\n');
- write(sockfd,buff,sizeof(buff));
- bzero(buff,sizeof(buff));
- read(sockfd,buff,sizeof(buff));
- printf("From Server : %s",buff);
- if((strncmp(buff,"exit",4))==0)
- {
- printf("Client Exit...\n");
- break;
- }
- }
- }
- int main()
- {
- int sockfd,connfd;
- struct sockaddr_in servaddr,cli;
- sockfd=socket(AF_INET,SOCK_STREAM,0);
- if(sockfd==-1)
- {
- printf("socket creation failed...\n");
- exit(0);
- }
- else
- printf("Socket successfully created..\n");
- bzero(&servaddr,sizeof(servaddr));
- servaddr.sin_family=AF_INET;
- servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
- servaddr.sin_port=htons(PORT);
- if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
- {
- printf("connection with the server failed...\n");
- exit(0);
- }
- else
- printf("connected to the server..\n");
- func(sockfd);
- close(sockfd);
- }
- ##################################################################
- To write a socket program to implement file transfer protocol.
- Server Code :
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <errno.h>
- #include <string.h>
- #include <sys/types.h>
- int main(void)
- {
- int listenfd = 0;
- int connfd = 0;
- struct sockaddr_in serv_addr;
- char sendBuff[1025];
- int numrv;
- listenfd = socket(AF_INET, SOCK_STREAM, 0);
- printf("Socket retrieve success\n");
- memset(&serv_addr, '0', sizeof(serv_addr));
- memset(sendBuff, '0', sizeof(sendBuff));
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
- serv_addr.sin_port = htons(5000);
- bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
- if(listen(listenfd, 10) == -1)
- {
- printf("Failed to listen\n");
- return -1;
- }
- while(1)
- {
- connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);
- FILE *fp = fopen("sample_file.txt","rb");
- if(fp==NULL)
- {
- printf("File opern error");
- return 1;
- }
- while(1)
- {
- unsigned char buff[256]={0};
- int nread = fread(buff,1,256,fp);
- printf("Bytes read %d \n", nread);
- if(nread > 0)
- {
- printf("Sending \n");
- write(connfd, buff, nread);
- }
- if (nread < 256)
- {
- if (feof(fp))
- printf("End of file\n");
- if (ferror(fp))
- printf("Error reading\n");
- break;
- }
- }
- close(connfd);
- sleep(1);
- }
- }
- Client Code:
- #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>
- #include <arpa/inet.h>
- int main(void)
- {
- int sockfd = 0;
- int bytesReceived = 0;
- char recvBuff[256];
- memset(recvBuff, '0', sizeof(recvBuff));
- struct sockaddr_in serv_addr;
- if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
- {
- printf("\n Error : Could not create socket \n");
- return 1;
- }
- serv_addr.sin_family = AF_INET;
- serv_addr.sin_port = htons(5000); // port
- serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
- if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
- {
- printf("\n Error : Connect Failed \n");
- return 1;
- }
- FILE *fp;
- fp = fopen("sample_file.txt", "ab");
- if(NULL == fp)
- {
- printf("Error opening file");
- return 1;
- }
- while((bytesReceived = read(sockfd, recvBuff, 256)) > 0)
- {
- printf("Bytes received %d\n",bytesReceived);
- recvBuff[bytesReceived] = 0;
- fwrite(recvBuff, 1,bytesReceived,fp);
- printf("%s \n", recvBuff); }
- if(bytesReceived < 0)
- {
- printf("\n Read Error \n");
- }
- return 0;
- }
- #######################################################################################
- To write a program to implement UDP protocol by means of a message transfer.
- Code :
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <stdio.h>
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #define BUFLEN 512
- #define NPACK 10
- #define PORT 9930
- void diep(char *s)
- {
- perror(s);
- exit(1);
- }
- int main(void)
- {
- struct sockaddr_in si_me, si_other;
- int s, i, slen=sizeof(si_other);
- char buf[BUFLEN];
- if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
- diep("socket");
- memset((char *) &si_me, 0, sizeof(si_me));
- si_me.sin_family = AF_INET;
- si_me.sin_port = htons(PORT);
- si_me.sin_addr.s_addr = htonl(INADDR_ANY);
- if (bind(s, &si_me, sizeof(si_me))==-1)
- diep("bind");
- for (i=0; i<NPACK; i++) {
- if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
- diep("recvfrom()");
- printf("Received packet from %s:%d\nData: %s\n\n",
- inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
- }
- close(s);
- return 0;
- }
- Client :
- #define SRV_IP "999.999.999.999"
- int main(void)
- {
- struct sockaddr_in si_other;
- int s, i, slen=sizeof(si_other);
- char buf[BUFLEN];
- if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
- diep("socket");
- memset((char *) &si_other, 0, sizeof(si_other));
- si_other.sin_family = AF_INET;
- si_other.sin_port = htons(PORT);
- if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
- fprintf(stderr, "inet_aton() failed\n");
- exit(1);
- }
- for (i=0; i<NPACK; i++) {
- printf("Sending packet %d\n", i);
- sprintf(buf, "This is packet %d\n", i);
- if (sendto(s, buf, BUFLEN, 0, &si_other, slen)==1)
- diep("sendto()");
- }
- close(s);
- return 0;
- }
- ########################################################################################
- To write a program to implement client authentication of username and password
- Code :
- Server :
- //authentication server - socket, memset, sockaddr_in in ip7, bind, listen, accept, write, read
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #define ANSI_COLOR_GREEN "\x1b[32m"
- #define ANSI_COLOR_RESET "\x1b[0m"
- struct user {
- char *username;
- char *password;
- };
- int main() {
- /*login details*/
- struct user singleUser;
- singleUser.username = "omijn";
- singleUser.password = "qwerty";
- /*messages*/
- char * userOK_enterPass = "Please enter your password : ";
- char * userNotFound = "This username does not exist.";
- char * userAuthenticated = "User authenticated!";
- char * invalidPassword = "Invalid password.";
- /*errors*/
- int bindError = 0;
- int serverSocketFD = 0, clientFD = 0, n = 0, auth = 0;
- char receiveBuffer[1024] = "", sendBuffer[1024] = "";
- struct sockaddr_in serverAddress;
- system("clear");
- //create socket
- if((serverSocketFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- printf("> Socket creation failed.\n");
- else
- printf("> Socket created.\n");
- //clear memory
- memset(receiveBuffer, '0', sizeof(receiveBuffer));
- memset(sendBuffer, '0', sizeof(sendBuffer));
- memset(&serverAddress, '0', sizeof(serverAddress));
- //server address
- serverAddress.sin_family = AF_INET;
- serverAddress.sin_port = htons(2884);
- serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
- printf("> Address created.\n");
- //assign name to server
- if((bind(serverSocketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) == -1) {
- printf("> Bind error.\n");
- bindError = errno;
- printf("%s\n", strerror(bindError));
- return -1;
- }
- else
- printf("> Binding successful.\n");
- //listen
- if((listen(serverSocketFD, 5)) == -1)
- printf("> Listen error.\n");
- else
- printf("> Server listening.\n");
- //accept connection
- if((clientFD = accept(serverSocketFD, (struct sockaddr *)NULL, NULL)) != 0)
- printf(ANSI_COLOR_GREEN "> Client connected!\n" ANSI_COLOR_RESET);
- else
- printf("> Client connect error.\n");
- while(!auth) {
- /* receive ------------------------------------------------------------------- */
- while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
- if(n == -1)
- printf("> Read error.\n");
- receiveBuffer[n] = 0;
- break;
- }
- if(strcmp(receiveBuffer, singleUser.username) == 0) {
- write(clientFD, userOK_enterPass, strlen(userOK_enterPass));
- auth = 0;
- while(!auth) {
- while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
- if(n == -1)
- printf("> Read error.\n");
- receiveBuffer[n] = 0;
- break;
- }
- if(strcmp(receiveBuffer, singleUser.password) == 0) {
- /*user authenticated*/
- auth = 1;
- printf("\n%s", userAuthenticated);
- write(clientFD, userAuthenticated, strlen(userAuthenticated));
- }
- else {
- auth = 0;
- printf("\n%s", invalidPassword);
- write(clientFD, invalidPassword, strlen(invalidPassword));
- }
- }
- }
- else {
- printf("\n%s", userNotFound);
- write(clientFD, userNotFound, strlen(userNotFound));
- }
- printf(ANSI_COLOR_GREEN "\n%s" ANSI_COLOR_RESET, receiveBuffer);
- //clear receive buffer for next use
- strcpy(receiveBuffer, "");
- //clear send buffer for next use
- strcpy(sendBuffer, "");
- }
- printf("\n");
- return 0;
- }
- Client :
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <string.h>
- #include <netinet/in.h>
- #include <arpa/inet.h>
- #include <errno.h>
- #define ANSI_COLOR_GREEN "\x1b[32m"
- #define ANSI_COLOR_RESET "\x1b[0m"
- struct user {
- char *username;
- char *password;
- };
- int main() {
- /*login details*/
- struct user singleUser;
- singleUser.username = "omijn";
- singleUser.password = "qwerty";
- /*messages*/
- char * userOK_enterPass = "Please enter your password : ";
- char * userNotFound = "This username does not exist.";
- char * userAuthenticated = "User authenticated!";
- char * invalidPassword = "Invalid password.";
- /*errors*/
- int bindError = 0;
- int serverSocketFD = 0, clientFD = 0, n = 0, auth = 0;
- char receiveBuffer[1024] = "", sendBuffer[1024] = "";
- struct sockaddr_in serverAddress;
- system("clear");
- //create socket
- if((serverSocketFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
- printf("> Socket creation failed.\n");
- else
- printf("> Socket created.\n");
- //clear memory
- memset(receiveBuffer, '0', sizeof(receiveBuffer));
- memset(sendBuffer, '0', sizeof(sendBuffer));
- memset(&serverAddress, '0', sizeof(serverAddress));
- //server address
- serverAddress.sin_family = AF_INET;
- serverAddress.sin_port = htons(2884);
- serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
- printf("> Address created.\n");
- //assign name to server
- if((bind(serverSocketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) == -1) {
- printf("> Bind error.\n");
- bindError = errno;
- printf("%s\n", strerror(bindError));
- return -1;
- }
- else
- printf("> Binding successful.\n");
- //listen
- if((listen(serverSocketFD, 5)) == -1)
- printf("> Listen error.\n");
- else
- printf("> Server listening.\n");
- //accept connection
- if((clientFD = accept(serverSocketFD, (struct sockaddr *)NULL, NULL)) != 0)
- printf(ANSI_COLOR_GREEN "> Client connected!\n" ANSI_COLOR_RESET);
- else
- printf("> Client connect error.\n");
- while(!auth) {
- /* receive ------------------------------------------------------------------- */
- while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
- if(n == -1)
- printf("> Read error.\n");
- receiveBuffer[n] = 0;
- break;
- }
- if(strcmp(receiveBuffer, singleUser.username) == 0) {
- write(clientFD, userOK_enterPass, strlen(userOK_enterPass));
- auth = 0;
- while(!auth) {
- while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
- if(n == -1)
- printf("> Read error.\n");
- receiveBuffer[n] = 0;
- break;
- }
- if(strcmp(receiveBuffer, singleUser.password) == 0) {
- /*user authenticated*/
- auth = 1;
- printf("\n%s", userAuthenticated);
- write(clientFD, userAuthenticated, strlen(userAuthenticated));
- }
- else {
- auth = 0;
- printf("\n%s", invalidPassword);
- write(clientFD, invalidPassword, strlen(invalidPassword));
- }
- }
- }
- else {
- printf("\n%s", userNotFound);
- write(clientFD, userNotFound, strlen(userNotFound));
- }
- printf(ANSI_COLOR_GREEN "\n%s" ANSI_COLOR_RESET, receiveBuffer);
- //clear receive buffer for next use
- strcpy(receiveBuffer, "");
- //clear send buffer for next use
- strcpy(sendBuffer, "");
- }
- printf("\n");
- return 0;}
- ##########################################################################################
- To write a program to implement the Echo UDP Server
- Code :
- Server
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <string.h>
- #include <stdlib.h>
- int main(){
- int udpSocket, nBytes;
- char buffer[1024];
- struct sockaddr_in serverAddr, clientAddr;
- struct sockaddr_storage serverStorage;
- socklen_t addr_size, client_addr_size;
- int i;
- /*Create UDP socket*/
- udpSocket = socket(PF_INET, SOCK_DGRAM, 0);
- /*Configure settings in address struct*/
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_port = htons(7891);
- serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
- memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
- /*Bind socket with address struct*/
- bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
- /*Initialize size variable to be used later on*/
- addr_size = sizeof serverStorage;
- while(1){
- nBytes = recvfrom(udpSocket,buffer,1024,0,(struct sockaddr *)&serverStorage, &addr_size);
- /*Convert message received to uppercase*/
- for(i=0;i<nBytes-1;i++)
- buffer[i] = toupper(buffer[i]);
- /*Send uppercase message back to client, using serverStorage as the address*/
- sendto(udpSocket,buffer,nBytes,0,(struct sockaddr *)&serverStorage,addr_size);
- }
- return 0;
- }
- Client:
- #include <stdio.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <string.h>
- int main(){
- int clientSocket, portNum, nBytes;
- char buffer[1024];
- struct sockaddr_in serverAddr;
- socklen_t addr_size;
- /*Create UDP socket*/
- clientSocket = socket(PF_INET, SOCK_DGRAM, 0);
- /*Configure settings in address struct*/
- serverAddr.sin_family = AF_INET;
- serverAddr.sin_port = htons(7891);
- serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
- memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
- /*Initialize size variable to be used later on*/
- addr_size = sizeof serverAddr;
- while(1){
- printf("Type a sentence to send to server:\n");
- fgets(buffer,1024,stdin);
- printf("You typed: %s",buffer);
- nBytes = strlen(buffer) + 1;
- /*Send message to server*/
- sendto(clientSocket,buffer,nBytes,0,(struct sockaddr *)&serverAddr,addr_size);
- /*Receive message from server*/
- nBytes = recvfrom(clientSocket,buffer,1024,0,NULL, NULL);
- printf("Received from server: %s\n",buffer);
- }
- return 0;
- }
- --------------------------------------------------------------------------------------------------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment