Guest User

Untitled

a guest
Nov 5th, 2017
25
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 62.42 KB | None | 0 0
  1. ****************************************************************
  2. CRC
  3.  
  4. #include <stdio.h>
  5. #include <string.h>
  6. int main()
  7. {
  8. int i,j,divbit,databit,count=0;
  9. char data[100], div[30],temp[30],quot[100],rem[30],div1[30];
  10. printf("Enter the number of bits in the data :");
  11. scanf("%d",&databit);
  12. printf("Enter data: ");
  13. scanf("%s",data);
  14. printf("Enter the number of bits in the divisor:");
  15. scanf("%d",&divbit);
  16. printf("Enter divisor: ");
  17. scanf("%s",div);
  18. strcpy(div1,div);
  19. for(i=0;i<divbit-1;i++)
  20. {
  21. data[databit+i]='0';
  22. }
  23. for(i=0;i<divbit;i++)
  24. temp[i]=data[i];
  25. for(i=0;i<databit;i++)
  26. {
  27. quot[i]=temp[0];
  28. if(quot[i]=='0')
  29. for(j=0;j<divbit;j++)
  30. div[j]='0';
  31. else
  32. for(j=0;j<divbit;j++)
  33. div[j]=div1[j];
  34. for(j=divbit-1;j>0;j--)
  35. {
  36. if(temp[j]==div[j])
  37. rem[j-1]='0';
  38. else
  39. rem[j-1]='1';
  40. }
  41. rem[divbit-1]=data[i+divbit];
  42. strcpy(temp,rem);
  43. }
  44. strcpy(rem,temp);
  45. printf("\nRemainder is ");
  46. for(i=0;i<divbit-1;i++)
  47. printf("%c",rem[i]);
  48. printf("\nCRC code is: ");
  49. for(i=0;i<databit;i++)
  50. printf("%c",data[i]);
  51. for(i=0;i<divbit-1;i++)
  52. printf("%c",rem[i]);
  53.  
  54. return 0;
  55. }
  56. ************************************************************************************
  57.  
  58. CRC (generate and Check)
  59.  
  60. #include<stdio.h>
  61. #include<string.h>
  62. #define N strlen(g)
  63. char t[28],cs[28],g[]="10001000000100001";
  64. int a,e,c;
  65. void xor(){
  66. for(c = 1;c < N; c++)
  67. cs[c] = (( cs[c] == g[c])?'0':'1');
  68. }
  69. void crc(){
  70. for(e=0;e<N;e++)
  71. cs[e]=t[e];
  72. do{
  73. if(cs[0]=='1')
  74. xor();
  75. for(c=0;c<N-1;c++)
  76. cs[c]=cs[c+1];
  77. cs[c]=t[e++];
  78. }while(e<=a+N-1);
  79. }
  80. int main()
  81. {
  82. printf("\nEnter data : ");
  83. scanf("%s",t);
  84. printf("\n----------------------------------------");
  85. printf("\nGeneratng polynomial : %s",g);
  86. a=strlen(t);
  87. for(e=a;e<a+N-1;e++)
  88. t[e]='0';
  89. printf("\n----------------------------------------");
  90. printf("\nModified data is : %s",t);
  91. printf("\n----------------------------------------");
  92. crc();
  93. printf("\nChecksum is : %s",cs);
  94. for(e=a;e<a+N-1;e++)
  95. t[e]=cs[e-a];
  96. printf("\n----------------------------------------");
  97. printf("\nFinal codeword is : %s",t);
  98. printf("\n----------------------------------------");
  99. printf("\nTest error detection 0(yes) 1(no)? : ");
  100. scanf("%d",&e);
  101. if(e==0)
  102. {
  103. do{
  104. printf("\nEnter the position where error is to be inserted : ");
  105. scanf("%d",&e);
  106. }while(e==0 || e>a+N-1);
  107. t[e-1]=(t[e-1]=='0')?'1':'0';
  108. printf("\n----------------------------------------");
  109. printf("\nErroneous data : %s\n",t);
  110. }
  111. crc();
  112. for(e=0;(e<N-1) && (cs[e]!='1');e++);
  113. if(e<N-1)
  114. printf("\nError detected\n\n");
  115. else
  116. printf("\nNo error detected\n\n");
  117. printf("\n----------------------------------------\n");
  118. return 0;
  119. }
  120.  
  121. ****************************************************
  122. ALT (think better)
  123.  
  124.  
  125. #include<stdio.h>
  126. #include <string.h>
  127. int main()
  128. {
  129. int i,j,keylen,msglen;
  130. char data[100], key[30],temp[30],quot[100],rem[30],key1[30];
  131. printf("Enter Data: ");
  132. gets(data);
  133. printf("Enter Key: ");
  134. gets(key);
  135. keylen=strlen(key);
  136. msglen=strlen(data);
  137. strcpy(key1,key);
  138. for(i=0;i<keylen-1;i++)
  139. {
  140. data[msglen+i]='0';
  141. }
  142. for(i=0;i<keylen;i++)
  143. temp[i]=data[i];
  144. for(i=0;i<msglen;i++)
  145. {
  146. quot[i]=temp[0];
  147. if(quot[i]=='0')
  148. for(j=0;j<keylen;j++)
  149. key[j]='0';
  150. else
  151. for(j=0;j<keylen;j++)
  152. key[j]=key1[j];
  153. for(j=keylen-1;j>0;j--)
  154. {
  155. if(temp[j]==key[j])
  156. rem[j-1]='0';
  157. else
  158. rem[j-1]='1';
  159. }
  160. rem[keylen-1]=data[i+keylen];
  161. strcpy(temp,rem);
  162. }
  163. strcpy(rem,temp);
  164. printf("\nQuotient is ");
  165. for(i=0;i<msglen;i++)
  166. printf("%c",quot[i]);
  167. printf("\nRemainder is ");
  168. for(i=0;i<keylen-1;i++)
  169. printf("%c",rem[i]);
  170. printf("\nFinal data is: ");
  171. for(i=0;i<msglen;i++)
  172. printf("%c",data[i]);
  173. for(i=0;i<keylen-1;i++)
  174. printf("%c",rem[i]);
  175. return 0;
  176. }
  177.  
  178.  
  179.  
  180. *******************************
  181. Algorithm --on paper
  182.  
  183. 1. Insert the Message to be encoded.
  184. 2. Zero Padding is done corresponding to the bit length n of CRC.
  185. 3. Check if the input bit above the leftmost divisor bit is 1 , do
  186. divisor XOR input .
  187. 4.Repeat step 3 until divisor traverses the input row ( Left to Right).
  188. 5. The 'n' non-zero bits on the right-hand end of the row is the value of the CRC function.
  189.  
  190.  
  191.  
  192.  
  193. ####################################################################################################
  194. Checksum
  195.  
  196. Algorithm :
  197. 1. Insert both the hex values.
  198. 2. Set check=one+two and check=check.
  199. 3. Calculate and Compare checkresult .
  200. 4. Check if they are equal , then print value.
  201. 5. Else print that the generated checksum some is wrong.
  202.  
  203.  
  204.  
  205. #include<stdio.h>
  206. #include<stdlib.h>
  207. #include<fentl.h>
  208. int main()
  209. {
  210. unsigned int one;
  211. unsigned int two;
  212. unsigned int check;
  213. unsigned int checkresult;
  214. printf("\nEnter the first hex value:");
  215. scanf("%x",&one);
  216. printf("\nEnter the second hex value:");
  217. scanf("%x",&one);
  218. check=one+two;
  219. check=check;
  220. printf("\nThe value of check is:%x",check);
  221. checkresult=one+two+check;
  222. printf("\The value of checkresult:%x",checkresult);
  223. checkresult=checkresult;
  224. printf("\n The value of answer is :%x",check result);
  225. else
  226. printf("\n The check sum of the code generated is not correct");
  227. }
  228.  
  229. ***************************8
  230. ALT(think better)
  231.  
  232. PROGRAM TO CALCULATE CHECKSUM
  233. #include<stdio.h>
  234.  
  235. #include<math.h>
  236. int sender(int b[10],int k)
  237. {
  238.  
  239.  
  240.  
  241.  
  242.  
  243. int checksum,sum=0,i;
  244. printf("\n****SENDER****\n");
  245. for(i=0;i<k;i++)
  246. sum+=b[i];
  247. printf("SUM IS: %d",sum);
  248. checksum=~sum;
  249. printf("\nSENDER's CHECKSUM IS:%d",checksum);
  250. return checksum;
  251. }
  252. int receiver(int c[10],int k,int scheck)
  253. {
  254. int checksum,sum=0,i;
  255. printf("\n\n****RECEIVER****\n");
  256. for(i=0;i<k;i++)
  257. sum+=c[i];
  258. printf(" RECEIVER SUM IS:%d",sum);
  259. sum=sum+scheck;
  260. checksum=~sum;
  261. printf("\nRECEIVER's CHECKSUM IS:%d",checksum);
  262. return checksum;
  263. }
  264. main()
  265. {
  266. int a[10],i,m,scheck,rcheck;
  267.  
  268. printf("\nENTER SIZE OF THE STRING:");//4 4 inputs array in binary
  269. scanf("%d",&m);
  270. printf("\nENTER THE ELEMENTS OF THE ARRAY:");
  271. for(i=0;i<m;i++)
  272. scanf("%d",&a[i]);
  273. scheck=sender(a,m);
  274. rcheck=receiver(a,m,scheck);
  275. if(rcheck==0)
  276. printf("\n\nNO ERROR IN TRANSMISSION\n\n");
  277. else
  278. printf("\n\nERROR DETECTED");
  279. return 0;
  280. }
  281.  
  282.  
  283.  
  284.  
  285.  
  286. ####################################################################################################
  287. Hamming Code
  288.  
  289. #include<stdio.h>
  290. #include<math.h>
  291. int main(){
  292. int n,i,j,k,ip,r,temp,p;
  293. int data[30],final[30],parity[10];
  294. printf("\nEnter Number of bits:");
  295. scanf("%d",&n);
  296. printf("\nEnter the data to be sent:");
  297. scanf("%d",&ip);
  298. for(i=n-1;i>=0;i--)
  299. {
  300. data[i]=ip%10;
  301. ip=ip/10;
  302. }
  303. for(r=1;r<n;r++)
  304. {
  305. if(n<=pow(2,r)-1-r){
  306. break;
  307. }
  308. }
  309. for(i=1;i<=n+r;i=i*2)
  310. {
  311. final[i]=-1;
  312. }
  313. for(i=1,j=0;i<=n+r;i++){
  314. if(final[i]!=-1){
  315. final[i]=data[j];
  316. j+=1;
  317. }
  318. }
  319. for(i=0;i<r;i++){
  320. p=pow(2,i);
  321. temp=0;
  322. for(j=p;j<=n+r;j=j+2*p){
  323. for(k=0;k<p && j+k<n+r ;k++){
  324. if(final[j+k]!=-1){
  325. temp=final[j+k]^temp;
  326. }
  327. }
  328. }
  329. parity[i]=temp;
  330. }
  331. for(i=1,j=0;i<=n+r;i++){
  332. if(final[i]==-1){
  333. final[i]=parity[j];
  334. j+=1;
  335. }
  336. }
  337. printf("Hamming Code=");
  338. for(i=1;i<=n+r;i++){
  339. printf("%d",final[i]);
  340. }
  341. printf("\n");
  342. }
  343.  
  344.  
  345.  
  346. ####################################################################################################
  347. Sliding Window Protocol(C)
  348.  
  349. Server side
  350. #include<stdio.h>
  351. #include<sys/socket.h>
  352. #include<sys/types.h>
  353. #include<netinet/in.h>
  354. #include<string.h>
  355. #include<stdlib.h>
  356. #include<arpa/inet.h>
  357. #define SIZE 4
  358. int main()
  359. {
  360. int sfd,lfd,len,i,j,status;
  361. char str[20],frame[20],temp[20],ack[20];
  362. struct sockaddr_in saddr,caddr;
  363. sfd=socket(AF_INET,SOCK_STREAM,0);
  364. if(sfd<0)
  365. perror("Error");
  366. bzero(&saddr,sizeof(saddr));
  367. saddr.sin_family=AF_INET;
  368. saddr.sin_addr.s_addr=htonl(INADDR_ANY);
  369. saddr.sin_port=htons(5465);
  370. if(bind(sfd,(struct sockaddr*)&saddr,sizeof(saddr))<0)
  371. perror("Bind Error");
  372. listen(sfd,5);
  373. len=sizeof(&caddr);
  374. lfd=accept(sfd,(struct sockaddr*)&caddr,&len);
  375. printf(" Enter the text : \n");
  376. scanf("%s",str);
  377. i=0;
  378. while(i<strlen(str))
  379. {
  380. memset(frame,0,20);
  381. strncpy(frame,str+i,SIZE);
  382. printf(" Transmitting Frames. ");
  383. len=strlen(frame);
  384. for(j=0;j<len;j++)
  385. {
  386. printf("%d",i+j);
  387. sprintf(temp,"%d",i+j);
  388. strcat(frame,temp);
  389. }
  390. printf("\n");
  391. write(lfd,frame,sizeof(frame));
  392. read(lfd,ack,20);
  393. sscanf(ack,"%d",&status);
  394. if(status==-1)
  395. printf(" Transmission is successful. \n");
  396. else
  397. {
  398. printf(" Received error in %d \n\n",status);
  399. printf("\n\n Retransmitting Frame. ");
  400. for(j=0;;)
  401. {
  402. frame[j]=str[j+status];
  403. printf("%d",j+status);
  404. j++;
  405. if((j+status)%4==0)
  406. break;
  407. }
  408. printf("\n");
  409. frame[j]='\0';
  410. len=strlen(frame);
  411. for(j=0;j<len;j++)
  412. {
  413. sprintf(temp,"%d",j+status);
  414. strcat(frame,temp);
  415. }
  416. write(lfd,frame,sizeof(frame));
  417. }
  418. i+=SIZE;
  419. }
  420. write(lfd,"exit",sizeof("exit"));
  421. printf("Exiting\n");
  422. sleep(2);
  423. close(lfd);
  424. close(sfd);
  425. }
  426.  
  427. Client Side
  428. #include<stdio.h>
  429. #include<string.h>
  430. #include<stdlib.h>
  431. #include<sys/socket.h>
  432. #include<sys/types.h>
  433. #include<netinet/in.h>
  434. int main()
  435. {
  436. int sfd,lfd,len,choice;
  437. char str[20],str1[20],err[20];
  438. struct sockaddr_in saddr,caddr;
  439. sfd=socket(AF_INET,SOCK_STREAM,0);
  440. if(sfd<0)
  441. perror("FdError");
  442. bzero(&saddr,sizeof(saddr));
  443. saddr.sin_family=AF_INET;
  444. saddr.sin_addr.s_addr=INADDR_ANY;
  445. saddr.sin_port=htons(5465);
  446. connect(sfd,(struct sockaddr*)&saddr,sizeof(saddr));
  447. for(;;)
  448. {
  449. read(sfd,str,20);
  450. if(!strcmp(str,"exit"))
  451. {
  452. printf("Exiting\n");
  453. break;
  454. }
  455. printf("\n\nReceived%s\n\n1.Do u want to report an error(1-Yes 0-No)",str);
  456. scanf("%d",&choice);
  457. if(!choice)
  458. write(sfd,"-1",sizeof("-1"));
  459. else
  460. {
  461. printf("Enter the sequence no of the frame where error has occured\n");
  462. scanf("%s",err);
  463. write(sfd,err,sizeof(err));
  464. read(sfd,str,20);
  465. printf("\n\nReceived the re-transmitted frames%s\n\n",str);
  466. }
  467. }
  468. }
  469.  
  470.  
  471.  
  472. ####################################################################################################
  473. OSI LAYER
  474.  
  475. #include<stdio.h>
  476. #include<string.h>
  477. int main()
  478. {
  479. char charstr[40],temp[40];
  480. int i;
  481. printf("Enter the input stream\n");
  482. gets(charstr);
  483. // Application layer
  484. printf("\nApplication layer (sender): ");
  485. printf("\n\tReceived: %s",charstr);
  486. strcpy(temp,"al");
  487. strcat(temp,charstr);
  488. strcpy(charstr,temp);
  489. printf("\n\tForwarded: %s",charstr);
  490. // Presentation Layer
  491. printf("\nPresentation layer (sender): ");
  492. printf("\n\tReceived: %s",charstr);
  493. strcpy(temp,"pl");
  494. strcat(temp,charstr);
  495. strcpy(charstr,temp);
  496. printf("\n\tForwarded: %s",charstr);
  497. //Session Layer
  498. printf("\nSession layer (sender): ");
  499. printf("\n\tReceived: %s",charstr);
  500. strcpy(temp,"sl");
  501. strcat(temp,charstr);
  502. strcpy(charstr,temp);
  503. printf("\n\tForwarded: %s",charstr);
  504. //Transport Layer
  505. printf("\nTransport layer (sender): ");
  506. printf("\n\tReceived: %s",charstr);
  507. strcpy(temp,"tl");
  508. strcat(temp,charstr);
  509. strcpy(charstr,temp);
  510. printf("\n\tForwarded: %s",charstr);
  511. //Network Layer
  512. printf("\nNetwork layer (sender): ");
  513. printf("\n\tReceived: %s",charstr);
  514. strcpy(temp,"nl");
  515. strcat(temp,charstr);
  516. strcpy(charstr,temp);
  517. printf("\n\tForwarded: %s",charstr);
  518. //Data Link layer
  519. printf("\nData Link layer (sender): ");
  520. printf("\n\tReceived: %s",charstr);
  521. strcpy(temp,"dl");
  522. strcat(temp,charstr);
  523. strcpy(charstr,temp);
  524. printf("\n\tForwarded: %s",charstr);
  525. //Physical layer
  526. printf("\nPhysical layer(sender) \n\tData sent to the receiver: %s",charstr);
  527.  
  528. //Physical layer
  529. printf("\n\n\nPhysical layer(receiver) \n\tData received: %s",charstr);
  530. //Data Link layer
  531. printf("\nData Link layer (Receiver): ");
  532. printf("\n\tReceived: %s",charstr);
  533. for(i=0;i<strlen(charstr);i++)
  534. {
  535. charstr[i]=charstr[i+2];
  536. }
  537. printf("\n\tForwarded: %s",charstr);
  538. //Network layer
  539. printf("\nNetwork layer (Receiver): ");
  540. printf("\n\tReceived: %s",charstr);
  541. for(i=0;i<strlen(charstr);i++)
  542. {
  543. charstr[i]=charstr[i+2];
  544. }
  545. printf("\n\tForwarded: %s",charstr);
  546. //Transport layer
  547. printf("\nTransport layer (Receiver): ");
  548. printf("\n\tReceived: %s",charstr);
  549. for(i=0;i<strlen(charstr);i++)
  550. {
  551. charstr[i]=charstr[i+2];
  552. }
  553. printf("\n\tForwarded: %s",charstr);
  554. //Session layer
  555. printf("\nSession layer (Receiver): ");
  556. printf("\n\tReceived: %s",charstr);
  557. for(i=0;i<strlen(charstr);i++)
  558. {
  559. charstr[i]=charstr[i+2];
  560. }
  561. printf("\n\tForwarded: %s",charstr);
  562. //Presentation layer
  563. printf("\nPresentation layer (Receiver): ");
  564. printf("\n\tReceived: %s",charstr);
  565. for(i=0;i<strlen(charstr);i++)
  566. {
  567. charstr[i]=charstr[i+2];
  568. }
  569. printf("\n\tForwarded: %s",charstr);
  570. //Application layer
  571. printf("\nApplication layer (Receiver): ");
  572. printf("\n\tReceived: %s",charstr);
  573. for(i=0;i<strlen(charstr);i++)
  574. {
  575. charstr[i]=charstr[i+2];
  576. }
  577. printf("\n\tForwarded: %s",charstr);
  578. printf("\n\nOutput presented to user: %s",charstr);
  579.  
  580. return 0;
  581. }
  582.  
  583. Algorithm *******************
  584. 1. Read the input string and address.
  585. 2. Add application header.
  586. 3. Print the string.
  587. 4. Add the presentation layer header.
  588. 5. Print the string.
  589. 6. Add the Session layer header.
  590. 7. Print the string.
  591. 8. Add the Transport layer header.
  592. 9. Print the string.
  593. 10. Add the Network layer header.
  594. 11. Print the string.
  595. 12. Add the Datalink layer header.
  596. 13. Print the string
  597. 14. Send to the physical layer.
  598. 15. Print the string
  599.  
  600. **********************
  601. #include<stdio.h>
  602. #include<conio.h>
  603. #include<string.h>
  604. const char * xtract(char []);
  605. int main()
  606. {
  607. char arr[50],ah[]="AH",fin[50],temp[50],ph[]="PH",sh[]="SH",th[]="TH",nh[]="NH",dh[]="DH";
  608. int addr;
  609. printf("Transmitter\n\n\n");
  610. printf("Enter the input string : ");
  611. gets(arr);
  612. printf("Enter the address : ");
  613. scanf("%d",&addr);
  614.  
  615. strcpy(fin,ah);
  616. strcat(fin,arr);
  617. printf("\n\nApplication layer : ");
  618. puts(fin);
  619. printf("\n");
  620.  
  621. strcpy(temp,ph);
  622. strcat(temp,fin);
  623. strcpy(fin,temp);
  624. printf("Presentation layer : ");
  625. puts(fin);
  626. printf("\n");
  627.  
  628. strcpy(temp,sh);
  629. strcat(temp,fin);
  630. strcpy(fin,temp);
  631. printf("Session layer : ");
  632. puts(fin);
  633. printf("\n");
  634.  
  635. strcpy(temp,th);
  636. strcat(temp,fin);
  637. strcpy(fin,temp);
  638. printf("Transport layer : ");
  639. puts(fin);
  640. printf("\n");
  641.  
  642. strcpy(temp,nh);
  643. strcat(temp,fin);
  644. strcpy(fin,temp);
  645. printf("Network layer : ");
  646. puts(fin);
  647. printf("\n");
  648.  
  649. strcpy(temp,dh);
  650. strcat(temp,fin);
  651. strcpy(fin,temp);
  652. printf("Data link layer : ");
  653. puts(fin);
  654. printf("\n");
  655. printf("Message entered into physical layer and transmitted\n\n\nReceiver\n\n\n");
  656.  
  657. printf("Datalink layer : ");
  658. puts(fin);
  659.  
  660. printf("\nNetwork layer : ");
  661. strcpy(temp,xtract(fin));
  662.  
  663. printf("\nTransport layer : ");
  664. strcpy(temp,xtract(temp));
  665.  
  666. printf("\nSession layer : ");
  667. strcpy(temp,xtract(temp));
  668.  
  669. printf("\nPresentation layer : ");
  670. strcpy(temp,xtract(temp));
  671.  
  672. printf("\nApplication layer : ");
  673. strcpy(temp,xtract(temp));
  674.  
  675. getch();
  676. return 0;
  677. }
  678. const char * xtract(char arr[])
  679. {
  680. char * output = malloc(100);
  681. int l=strlen(arr);
  682. int i;
  683. for(i=0;i<l;i++)
  684. {
  685. output[i]=arr[i+2];
  686. }
  687. puts(output);
  688. return (char *)output;
  689. }
  690.  
  691.  
  692.  
  693.  
  694. ####################################################################################################
  695. BIT STUFFING -DE
  696.  
  697. Algorithm :
  698. 1. a flag “01111110” is embedded at the starting and the ending of the data.
  699. 2. if data bit is 1 increment count else count is zero.
  700. 3. If count is five store a zero bit after the five 1􀀀 s in the data array.
  701. 4. Repeat step 3 till the end of data.
  702. 5. If the data bit is 1 increment count else count is zero.
  703. 6. If the count is five and the next bit is zero then store the next bit after zero in the data array.
  704. 7. De stuffed data is transmitted without flags.
  705.  
  706. *******************
  707. Code :
  708. #include<stdio.h>
  709. #include<string.h>
  710. #define DELIM_BIT_PATTERN "01111110"
  711. #define SNDR_INPUT 0
  712. #define SNDR_OUTPUT 1
  713. #define REC_INPUT 2
  714. #define REC_OUTPUT 3
  715.  
  716. char data[4][100];
  717.  
  718. int valid_data(void);
  719. void sender_bit_stuff(void);
  720. void receiver_process_data(void);
  721.  
  722. int main()
  723. {
  724. int ans;
  725. do{
  726. printf("\nEnter Data from Netwrok Layer in Binary Form:");
  727. scanf("%s",data[SNDR_INPUT]);
  728. if(!valid_data())
  729. continue;
  730. sender_bit_stuff();
  731. printf("\nSenders Physical Layer Data:%s\n",data[SNDR_OUTPUT]);
  732. strcpy(data[REC_INPUT],data[SNDR_OUTPUT]);
  733. receiver_process_data();
  734. printf("\nReceiver's Network Layer Data: %s\n",data[REC_OUTPUT]);
  735. printf("\n\nDo you want to continue?(y: 1/n: 0)");
  736. scanf("%d",&ans);
  737. }while(ans!=0);
  738. }
  739.  
  740.  
  741. int valid_data(){
  742. char *p=data[SNDR_INPUT];
  743. if(*p=='\0'){
  744. printf("\n***Enter Some DAta***\n");
  745. return 0;
  746. }
  747. while(*p!='\0'){
  748. if(*p!='1' && *p!='0'){
  749. printf("** this is not binary data. please Enter 0's and 1's\n");
  750. }
  751. p++;
  752. }
  753. return 1;
  754. }
  755. void sender_bit_stuff(void){
  756. char *src=data[SNDR_INPUT];
  757. char *dst=data[SNDR_OUTPUT];
  758. int count=0;
  759. strcpy(dst,DELIM_BIT_PATTERN);
  760. dst+=strlen(DELIM_BIT_PATTERN);
  761. while(*src!='\0')
  762. {
  763. if(count==5){
  764. *dst='0';
  765. dst+=1;
  766. count=0;
  767. }
  768. if(*src=='1')
  769. count++;
  770. else
  771. count=0;
  772. *dst++=*src++;
  773. }
  774. if(*src=='\0' && count==5){
  775. *dst='0';
  776. dst+=1;
  777. }
  778. strcpy(dst,DELIM_BIT_PATTERN);
  779. dst+=strlen(DELIM_BIT_PATTERN);
  780. *dst='\0';
  781. }
  782. void receiver_process_data(void){
  783. char *src=data[REC_INPUT];
  784. char *dst=data[REC_OUTPUT];
  785. char *end;
  786. int count=0;
  787. src+=strlen(DELIM_BIT_PATTERN);
  788. end=data[REC_INPUT]+strlen(data[REC_INPUT])-strlen(DELIM_BIT_PATTERN);
  789. while(src<=end)
  790. {
  791. if(count==5)
  792. src+=1;
  793. count=0;
  794. if(*src=='1')
  795. count++;
  796. else
  797. count=0;
  798. *dst++=*src++;
  799. }
  800. *(dst-1)='\0';
  801. return;
  802. }
  803.  
  804. ***************************************************
  805. ALT
  806.  
  807. #include<stdio.h>
  808. #include<conio.h>
  809. #include<string.h>
  810. void main()
  811. {
  812. int a[20],b[30],i,j,k,count,n;
  813. printf("enter length of frame-");
  814. scanf("%d",&n);
  815. printf("enter frame-");
  816. for(i=0;i<n;i++)
  817. scanf("%d",&a[i]);
  818. i=0;
  819. count=1;
  820. j=0;
  821. while(i<n)
  822. {
  823. if(a[i]==1)
  824. {
  825. b[j]=a[i];
  826. for(k=i+1;a[k]==1 && k<n && count<5;k++)
  827. {
  828. j++;
  829. b[j]=a[k];
  830. count++;
  831. if(count==5)
  832. {
  833. j++;
  834. b[j]=0;
  835. }
  836. i=k;
  837. }
  838. }
  839. else
  840. {
  841. b[j]=a[i];
  842. }
  843. i++;
  844. j++;
  845. }
  846.  
  847. printf("After stuffing the frame is:");
  848. printf("01111110");
  849. for(i=0;i<j;i++)
  850. printf("%d",b[i]);
  851. printf("01111110");
  852.  
  853. }
  854.  
  855. ###################################################################################
  856. BYTE STUFFING (CHARACTER STUFFF)
  857.  
  858. Aim :
  859.  
  860. To write a C program to implement the data link layer framing method byte stuffing.
  861.  
  862. Algorithm :
  863. 1. As the DLE characters are non printable characters. The ASCII values of the printable
  864. characters like *,#,$ are assigned to DLE, STX, ETX.
  865. 2. If the ASCII value that is assigned to DLE occurs in the data array another DLE character
  866. is stuffed and stored in the array and transmitted along with starting and ending flags.
  867. 3. If the ASCII value of DLE occurs in the data array, the next bit is stored in to the array and
  868. transmitted with out the flags.
  869. 4. Here whenever the program encounters characters like * the string DLE is added to the original string.
  870.  
  871. *************************
  872.  
  873. Code :
  874. #include<stdio.h>
  875. #include<string.h>
  876.  
  877. #define FLAG_BYTE "$"
  878. #define ESCAPE_BYTE "#"
  879.  
  880. void byte_stuff();
  881. char input_buf[100];
  882. char output_buf[100];
  883.  
  884. main(){
  885. int ans;
  886. do{
  887. input_buf[0]='\0';
  888. output_buf[0]='\0';
  889. printf("\nFLAG_BYTE:$,ESC_BYTE=#\n");
  890. printf("\nEnter th data from Network Layer:");
  891. scanf("%s",input_buf);
  892. byte_stuff();
  893. printf("\nData to the physical Layer:%s",output_buf);
  894. printf("\nDo you want to continue?(Y: 1/N: 0):");
  895. scanf("%d",&ans);
  896. }while(ans!=0);
  897. return 0;
  898. }
  899. void byte_stuff(void){
  900. int i=0,j=1;
  901. output_buf[0]='$';
  902. for(;input_buf[i]!='\0';i++,j++)
  903. {
  904. if(input_buf[i]!='$' && input_buf[i]!='#')
  905. output_buf[j]=input_buf[i];
  906. else{
  907. output_buf[j++]='#';
  908. output_buf[j]=input_buf[i];
  909. }
  910. }
  911. output_buf[j]='$';
  912. output_buf[j++]='\0';
  913. }
  914.  
  915. ***************************************
  916. ALT
  917.  
  918. #include<stdio.h>
  919. #include<conio.h>
  920. void main()
  921. {
  922. char frame[100],str[50];
  923. char flag='z';
  924. char esc='x';
  925. int i,j,k=0,n;
  926. frame[k++]='z';
  927.  
  928. printf("Enter String \n");
  929.  
  930. gets(str);
  931.  
  932. for(j=0;j<strlen(str);j++)
  933. {
  934. if(str[j]!=flag&&str[j]!=esc)
  935. {
  936. frame[k++]=str[j];
  937. }
  938. else{
  939. frame[k++]='x';
  940. frame[k++]=str[j];
  941. }
  942. }
  943.  
  944.  
  945. frame[k++]='z';
  946. frame[k++]='\0';
  947.  
  948. printf("\nByte stuffing at sender side:\n\n");
  949.  
  950. for(i=0;i<k;i++)
  951. {
  952. printf("%c",frame[i]);
  953. }
  954.  
  955. printf("\nByte stuffing at receiver side\n\n");
  956.  
  957. for(i=0;i<k;i++)
  958. {
  959. if(frame[i]=='x'|| frame[i]=='z')
  960. {
  961. i++;
  962. }
  963. printf("%c",frame[i]);
  964. }
  965.  
  966. }
  967. **************************************
  968. ALT 3
  969.  
  970. #include<stdio.h>
  971. #include<string.h>
  972.  
  973. void main()
  974. {
  975. int j,l,m,c,k;
  976. char a[50],b[50];
  977.  
  978. printf("Enter the string:");
  979. gets(a);
  980.  
  981. strcpy(b,"DLESTX");
  982. m=strlen(a);
  983.  
  984. for(j=0;j<m;)
  985. {
  986. if(a[j]=='d')
  987. {
  988. if(a[j+1]=='l')
  989. {
  990. if(a[j+2]=='e')
  991. {
  992. c=j+2;
  993. for(l=0;l<3;l++)
  994. {
  995. for(k=m;k>c;k--)
  996. {
  997. a[k]=a[k-1];
  998. }
  999. m++;
  1000. a[m]=' ';
  1001. c+=1;
  1002. }
  1003.  
  1004. a[j+3]='d';
  1005. a[j+4]='l';
  1006. a[j+5]='e';
  1007. a[m]=' ';
  1008. j+=5;
  1009. }
  1010. }
  1011. }
  1012. j++;
  1013. }
  1014.  
  1015. strcat(b,a);
  1016. strcat(b,"DLEETX");
  1017. printf("\n%s",b);
  1018. printf("\nReceiver side:");
  1019.  
  1020. m=strlen(a);
  1021. for(j=0;j<m;)
  1022. {
  1023. if(a[j]=='d')
  1024. {
  1025. if(a[j+1]=='l')
  1026. {
  1027. if(a[j+2]=='e')
  1028. {
  1029. c=j;
  1030. for(l=0;l<3;l++)
  1031. {
  1032. for(k=c;k<m;k++)
  1033. a[k]=a[k+1];
  1034. }
  1035. c++;
  1036. }
  1037. j=c;
  1038. }
  1039. }
  1040. j++;
  1041. }
  1042. printf("\n%s\n",a);
  1043. }
  1044.  
  1045.  
  1046. #################################################################################
  1047.  
  1048. CHARACTER COUNT
  1049.  
  1050.  
  1051. Aim :
  1052. To write a C program to implement the data link layer framing method character count.
  1053.  
  1054. Algorithm :
  1055.  
  1056. 1. At the sender side the user is asked to enter the number of frames he want to transmit.
  1057. 2. Depending upon the input, that many number of frames are taken as input from the user
  1058. and stored in a 2 by 2 matrix.
  1059. 3. The length of each frame is calculated and stored in a new array.
  1060. 4.While out putting the frame, the length of each frame is added to the each frame and finally
  1061. all the frames are appended and sent as a single string.
  1062. 5. At the receiver side, the first number is treated as the length of the first frame and the string
  1063. is extracted and displayed.
  1064. 6. The next number is treated as the length of the next frame and so on.
  1065.  
  1066. Code :
  1067. #include<stdio.h>
  1068. #include<string.h>
  1069. char input[10][20];
  1070. int get_input();
  1071. void make_frames(int);
  1072. int count_chars(int s);
  1073. void main()
  1074. {
  1075. int no_of_words=get_input();
  1076. make_frames(no_of_words);
  1077. }
  1078. int get_input()
  1079. {
  1080. int answer;
  1081. int i=0;
  1082. do{
  1083. printf("\nEnter the Word:");
  1084. scanf("%s",input[i]);
  1085. fflush(stdin);
  1086. printf("\nDo you want to continue: (y: 1/n: 0)?:");
  1087. scanf("%d",&answer);
  1088. i++;
  1089. }while(answer!=0);
  1090. return i;
  1091. }
  1092. void make_frames(int num_words){
  1093. int i=0;
  1094. printf("\nThe Transmitted Data is:\n\t");
  1095.  
  1096. for(;i<num_words;i++)
  1097. printf("%d%s",(count_chars(i)+1),input[i]);
  1098.  
  1099. printf("\n\n");
  1100. }
  1101. int count_chars(int index)
  1102. {
  1103. int i=0;
  1104. while(input[index][i]!='\0')
  1105. i++;
  1106. return i;
  1107. }
  1108.  
  1109. #####################################################################################
  1110.  
  1111. GO BACK AND SELECT ARQ
  1112.  
  1113. Code
  1114. #include<stdio.h>
  1115. #include<math.h>
  1116. int main()
  1117. {
  1118. int windowsize,sent=0,acknw,i,m,p;
  1119. printf("Enter no. of bits: ");
  1120. scanf("%d",&m);
  1121. p=pow(2,m);
  1122. printf("The no. of Packets that has transmitted are: %d\n",p);
  1123. windowsize=pow(2,m)-1;
  1124. printf("The Windowsize is: %d\n",windowsize);
  1125. while(1)
  1126. {
  1127. for(i=0;i<windowsize;i++)
  1128. {
  1129. printf("Frame %d has been transmitted \n",sent);
  1130. sent++;
  1131. if(sent==windowsize)
  1132. break;
  1133. }
  1134. printf("\n Please enter the last Acknowledgement received:\n");
  1135. scanf("%d",&acknw);
  1136. if(acknw==windowsize)
  1137. break;
  1138. else
  1139. sent=acknw;
  1140. }
  1141. return 0;
  1142. }
  1143.  
  1144.  
  1145. ############################################################################################
  1146.  
  1147. SELECTIVE REPEAT:
  1148.  
  1149.  
  1150. #include<stdio.h>
  1151. #include<math.h>
  1152. int main()
  1153. {
  1154. int windowsize,sent=0,acknw,i,m,p;
  1155. int n=1;
  1156. printf("Enter no. of bits:");
  1157. scanf("%d",&m);
  1158. p=pow(2,m);
  1159. printf("The no. of Packets has transmitted are: %d\n",p);
  1160. windowsize=pow(2,m-1);
  1161. printf("The Windowsize is: %d\n",windowsize);
  1162. while(1)
  1163. {
  1164. while(n>0)
  1165. {
  1166. for(i=0;i<windowsize;i++)
  1167. {
  1168. printf("Frame %d has been transmitted\n",sent);
  1169. sent++;
  1170. if(sent==windowsize)
  1171. break;
  1172. }
  1173. n=0;
  1174. }
  1175. printf("\n Please enter the Acknowledgement received:\n");
  1176. scanf("%d",&acknw);
  1177. if(acknw>windowsize)
  1178. {
  1179. printf("All previous packetsreceived");
  1180. break;
  1181. }
  1182. else
  1183. {
  1184. sent=acknw;
  1185. printf("Resend the %d packet",sent);
  1186. }
  1187. return 0;
  1188. }
  1189. }
  1190.  
  1191. #############################################################################################
  1192.  
  1193. #############################################################################################
  1194.  
  1195. ############################################################################################
  1196.  
  1197.  
  1198. Write a program to display the name of the computer and its IP address that you are currently
  1199. working on.
  1200.  
  1201. code:
  1202.  
  1203. import java.net.*;
  1204. import java.io.*;
  1205. public class ex2
  1206. {
  1207. public static void main(String args[]) throws Exception
  1208. {
  1209. InetAddress ipadd =InetAddress.getLocalHost();
  1210. System.out.println("Host and Address :"+ipadd);
  1211. System.out.println("Host name :"+ipadd.getHostName());
  1212. String n=ipadd.toString();
  1213. System.out.println("IP address :"+n.substring(n.indexOf("/")+1));
  1214. }
  1215. }
  1216.  
  1217. ##############################################################################################
  1218.  
  1219. To implement echo server and client in java using TCP sockets.
  1220.  
  1221. Code:
  1222.  
  1223. echo client:
  1224.  
  1225. import java.io.*;
  1226. import java.net.*;
  1227. public class ex52
  1228. {
  1229. public static void main(String args[]) throws Exception
  1230. {
  1231. try {
  1232. int Port;
  1233. BufferedReader Buf =new BufferedReader(new InputStreamReader(System.in));
  1234. System.out.print(" Enter the Port Address : " );
  1235. Port=Integer.parseInt(Buf.readLine());
  1236. Socket sok=new Socket("localhost",Port);
  1237. if(sok.isConnected()==true)
  1238. System.out.println(" Server Socket is Connected Succecfully. ");
  1239. InputStream in=sok.getInputStream();
  1240. OutputStream ou=sok.getOutputStream();
  1241. PrintWriter pr=new PrintWriter(ou);
  1242. BufferedReader buf1=new BufferedReader(new InputStreamReader(System.in));
  1243. BufferedReader buf2=new BufferedReader(new InputStreamReader(in));
  1244. String str1,str2;
  1245. System.out.print(" Enter the Message : ");
  1246. str1=buf1.readLine();
  1247. pr.println(str1);
  1248. pr.flush();
  1249. System.out.println(" Message Send Successfully. ");
  1250. str2=buf2.readLine();
  1251. System.out.println(" Message From Server : " + str2);
  1252. }
  1253. catch(Exception e)
  1254. {
  1255. System.out.println(" Error : " + e.getMessage());
  1256. }
  1257. }
  1258. }
  1259.  
  1260. echo server:
  1261.  
  1262. import java.io.*;
  1263. import java.net.*;
  1264. public class ex5
  1265. {
  1266. public static void main(String args[]) throws Exception
  1267. {
  1268. try
  1269. {
  1270. int Port;
  1271. BufferedReader Buf =new BufferedReader(new InputStreamReader(System.in));
  1272. System.out.print(" Enter the Port Address : " );
  1273. Port=Integer.parseInt(Buf.readLine());
  1274. ServerSocket sok =new ServerSocket(Port);
  1275. System.out.println(" Server is Ready To Receive a Message. ");
  1276. System.out.println(" Waiting ..... ");
  1277. Socket so=sok.accept();
  1278. if(so.isConnected()==true)
  1279. System.out.println(" Client Socket is Connected Succecfully. ");
  1280. InputStream in=so.getInputStream();
  1281. OutputStream ou=so.getOutputStream();
  1282. PrintWriter pr=new PrintWriter(ou);
  1283. BufferedReader buf=new BufferedReader(new InputStreamReader(in));
  1284. String str=buf.readLine();
  1285. System.out.println(" Message Received From Client : " + str);
  1286. System.out.println(" This Message is Forwarded To Client. ");
  1287. pr.println(str);
  1288. pr.flush();
  1289. }
  1290. catch(Exception e)
  1291. {
  1292. System.out.println(" Error : " + e.getMessage());
  1293. }
  1294. }
  1295. }
  1296.  
  1297.  
  1298. #################################################################################
  1299. To implement date server and client in java using TCP sockets.
  1300.  
  1301. code:
  1302.  
  1303. server:
  1304.  
  1305. import java.net.*;
  1306. import java.io.*;
  1307. import java.util.*;
  1308. class ex8
  1309. {
  1310. public static void main(String arg[])
  1311. {
  1312. ServerSocket ss = null;
  1313. Socket cs;
  1314. PrintStream ps;
  1315. BufferedReader dis;
  1316. String inet;
  1317. try
  1318. {
  1319. ss = new ServerSocket(4444);
  1320. System.out.println("Press Ctrl+C to quit");
  1321. while(true)
  1322. {
  1323. cs = ss.accept();
  1324. ps = new PrintStream(cs.getOutputStream());
  1325. Date d = new Date();
  1326. ps.println(d);
  1327. dis = new BufferedReader(new
  1328. InputStreamReader(cs.getInputStream()));
  1329. inet = dis.readLine();
  1330. System.out.println("Client System/IP address is :"
  1331. + inet);
  1332. ps.close();
  1333. dis.close();
  1334. }
  1335. }
  1336. catch(IOException e)
  1337. {
  1338. System.out.println("The exception is :" + e);
  1339. }
  1340. }
  1341. }
  1342.  
  1343.  
  1344. client:
  1345.  
  1346. import java.net.*;
  1347. import java.io.*;
  1348. class ex81
  1349. {
  1350. public static void main (String args[])
  1351. {
  1352. Socket soc;
  1353. BufferedReader dis;
  1354. String sdate;
  1355. PrintStream ps;
  1356. try
  1357. {
  1358. InetAddress ia=InetAddress.getLocalHost();
  1359. if(args.length==0)
  1360. soc=new Socket(InetAddress.getLocalHost(),4444);
  1361. else
  1362. soc=new Socket(InetAddress.getByName(args[0]),4444);
  1363. dis=new BufferedReader(new
  1364. InputStreamReader(soc.getInputStream()));
  1365. sdate=dis.readLine();
  1366. System.out.println("The date/time on server is : "+sdate);
  1367. ps=new PrintStream(soc.getOutputStream());
  1368. ps.println(ia);
  1369. ps.close();
  1370. }
  1371. catch(IOException e)
  1372. {
  1373. System.out.println("THE EXCEPTION is :" + e);
  1374. }
  1375. }
  1376. }
  1377.  
  1378.  
  1379. #########################################################################################################
  1380.  
  1381. Write a program to implement a simple message transfer from client to server process using TCP/IP.
  1382.  
  1383. Code:
  1384. SERVER: ss1
  1385.  
  1386. import java.io.*;
  1387. import java.net.*;
  1388. public class ss1
  1389. {
  1390. public static void main(String args[])throws IOException
  1391. {
  1392. ServerSocket s=new ServerSocket(1234);
  1393. Socket s1=s.accept();
  1394. InputStream s1in=s1.getInputStream();
  1395. OutputStream s1out=s1.getOutputStream();
  1396. int n=100;
  1397. BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
  1398. byte b[];
  1399. while (n==100)
  1400. {
  1401. byte b2[]=new byte[20];
  1402. String id=inFromUser.readLine();
  1403. b=id.getBytes();
  1404. s1out.write(b);
  1405. s1in.read(b2);
  1406. String st= new String(b2);
  1407. System.out.println("Client-1 : "+st);
  1408.  
  1409. }
  1410. s1in.close();
  1411. s1out.close();
  1412. s1.close();
  1413. }
  1414. }
  1415.  
  1416.  
  1417. CLIENT: cc1
  1418.  
  1419. import java.io.*;
  1420. import java.net.*;
  1421. public class cc1
  1422. {
  1423. public static void main(String args[])throws IOException
  1424. {
  1425. Socket s1=new Socket("localhost", 1234);
  1426. OutputStream s1out=s1.getOutputStream();
  1427. InputStream s1in=s1.getInputStream();
  1428. int n=100;
  1429. BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
  1430. byte b[];
  1431. while (n==100)
  1432. {
  1433. String id=inFromUser.readLine();
  1434. b=id.getBytes();
  1435. s1out.write(b);
  1436. byte b2[]=new byte[20];
  1437. s1in.read(b2);
  1438. String st=new String(b2);
  1439. System.out.println("Server : " + st);
  1440. }
  1441. s1in.close();
  1442. s1out.close();
  1443. s1.close();
  1444. }
  1445. }
  1446.  
  1447.  
  1448. ##############################################################################################
  1449.  
  1450. Develop a TCP client/server application for transferring a text file from client to server?
  1451.  
  1452. code:
  1453.  
  1454. server:
  1455.  
  1456. import java.io.BufferedInputStream;
  1457. import java.io.File;
  1458. import java.io.FileInputStream;
  1459. import java.io.OutputStream;
  1460. import java.net.InetAddress;
  1461. import java.net.ServerSocket;
  1462. import java.net.Socket;
  1463. public class ex10s {
  1464. public static void main(String[] args) throws Exception {
  1465. ServerSocket ssock = new ServerSocket(5000);
  1466. Socket socket = ssock.accept();
  1467. InetAddress IA = InetAddress.getByName("localhost");
  1468. File file = new File("e:\\data1.bin");
  1469. FileInputStream fis = new FileInputStream(file);
  1470. BufferedInputStream bis = new BufferedInputStream(fis);
  1471. OutputStream os = socket.getOutputStream();
  1472. byte[] contents;
  1473. long fileLength = file.length();
  1474. long current = 0;
  1475. long start = System.nanoTime();
  1476. while(current!=fileLength){
  1477. int size = 10000;
  1478. if(fileLength - current >= size)
  1479. current += size;
  1480. else{
  1481. size = (int)(fileLength - current);
  1482. current = fileLength;
  1483. }
  1484. contents = new byte[size];
  1485. bis.read(contents, 0, size);
  1486. os.write(contents);
  1487. System.out.print("Sending file ... "+(current*100)/fileLength+"% complete!");
  1488. }
  1489. os.flush();
  1490. socket.close();
  1491. ssock.close();
  1492. System.out.println("File sent succesfully!");
  1493. }
  1494. }
  1495.  
  1496. client:
  1497.  
  1498. import java.io.BufferedOutputStream;
  1499. import java.io.FileOutputStream;
  1500. import java.io.InputStream;
  1501. import java.net.InetAddress;
  1502. import java.net.Socket;
  1503. public class ex10c
  1504. {
  1505. public static void main(String[] args) throws Exception{
  1506. Socket socket = new Socket(InetAddress.getByName("localhost"), 5000);
  1507. byte[] contents = new byte[10000];
  1508. FileOutputStream fos = new FileOutputStream("e:\\data2.bin");
  1509. BufferedOutputStream bos = new BufferedOutputStream(fos);
  1510. InputStream is = socket.getInputStream();
  1511. int bytesRead = 0;
  1512. while((bytesRead=is.read(contents))!=-1)
  1513. bos.write(contents, 0, bytesRead);
  1514. bos.flush();
  1515. socket.close();
  1516. System.out.println("File saved successfully!");
  1517. }
  1518. }
  1519.  
  1520.  
  1521. #############################################################################
  1522.  
  1523. To implement a chat server and client in java using TCP sockets.
  1524.  
  1525. code:
  1526.  
  1527. server:
  1528.  
  1529. import java.io.*;
  1530. import java.net.*;
  1531. public class ser
  1532. {
  1533. public static void main(String args[])throws IOException
  1534. {
  1535. ServerSocket s=new ServerSocket(1234);
  1536. Socket s1=s.accept();
  1537. InputStream s1in=s1.getInputStream();
  1538. OutputStream s1out=s1.getOutputStream();
  1539. int n=100;
  1540. BufferedReader inUser=new BufferedReader(new InputStreamReader(System.in));
  1541. byte b[];
  1542. while(n==100)
  1543. {
  1544. byte b2[]=new byte[20];
  1545. s1in.read(b2);
  1546. String st=new String(b2);
  1547. System.out.println(st);
  1548. String id=inUser.readLine();
  1549. b=id.getBytes();
  1550. s1out.write(b);
  1551. }
  1552. s1in.close();
  1553. s1out.close();
  1554. s1.close();
  1555. }
  1556. }
  1557.  
  1558. client:
  1559.  
  1560. import java.io.*;
  1561. import java.net.*;
  1562. public class cln
  1563. {
  1564. public static void main(String args[])throws IOException
  1565. {
  1566. Socket s1=new Socket("localhost",1234);
  1567. OutputStream s1out=s1.getOutputStream();
  1568. InputStream s1in=s1.getInputStream();
  1569. int n=100;
  1570. BufferedReader inuser=new BufferedReader(new InputStreamReader(System.in));
  1571. byte b[];
  1572. while(n==100)
  1573. {
  1574. String id=inuser.readLine();
  1575. b=id.getBytes();
  1576. s1out.write(b);
  1577. byte b2[]=new byte[20];
  1578. s1in.read(b2);
  1579. String st=new String(b2);
  1580. System.out.println(st);
  1581. }
  1582. s1in.close();
  1583. s1out.close();
  1584. s1.close();
  1585. }
  1586. }
  1587.  
  1588. ##############################################################################
  1589.  
  1590. USERNAME AND PASSWORD AUTHENTICATE
  1591.  
  1592. 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.
  1593.  
  1594.  
  1595. code:
  1596.  
  1597. server:
  1598.  
  1599. import java.io.*;
  1600. import java.net.*;
  1601. import java.util.*;
  1602. public class auth
  1603. {
  1604. public static void main(String args[]) throws IOException
  1605. {
  1606. ServerSocket s= new ServerSocket(1234);
  1607. Socket S1=s.accept();
  1608. InputStream S1in=S1.getInputStream();
  1609. OutputStream S1out=S1.getOutputStream();
  1610. byte b1[]=new byte[20];
  1611. byte b[]=new byte[20];
  1612. S1in.read(b);
  1613. String st=new String(b);
  1614. System.out.println(st);
  1615. S1in.read(b1);
  1616. String st1=new String(b1);
  1617. System.out.println(st1);
  1618. if(st.equals(st1))
  1619. {
  1620. String yes="Valid";
  1621. System.out.println("Valid");
  1622. b=yes.getBytes();
  1623. S1out.write(b);
  1624. }
  1625. else
  1626. {
  1627. String yes1="NotValid";
  1628. System.out.println("NotValid");
  1629. b=yes1.getBytes();
  1630. S1out.write(b);
  1631. }
  1632. S1out.close();
  1633. S1in.close();
  1634. S1.close();
  1635. }
  1636. }
  1637.  
  1638.  
  1639. client:
  1640.  
  1641. import java.io.*;
  1642. import java.net.*;
  1643. import java.util.*;
  1644. public class client
  1645. {
  1646. public static void main(String args[]) throws IOException
  1647. {
  1648. Socket s1= new Socket("localhost",1234);
  1649. OutputStream s1out=s1.getOutputStream();
  1650. InputStream s1in=s1.getInputStream();
  1651. BufferedReader inFromUser=new BufferedReader(new InputStreamReader(System.in));
  1652. byte b1[],b[];
  1653. System.out.println("Enter the Username");
  1654. String id=inFromUser.readLine();
  1655. b=id.getBytes();
  1656. System.out.println("Enter the password");
  1657. String passwrd=inFromUser.readLine();
  1658. b1=passwrd.getBytes();
  1659. s1out.write(b);
  1660. s1out.write(b1);
  1661. byte b2[]=new byte[20];
  1662. s1in.read(b2);
  1663. String st=new String(b2);
  1664. System.out.println(st);
  1665. s1out.close();
  1666. s1.close();
  1667. }
  1668. }
  1669.  
  1670. ########################################################################
  1671.  
  1672. ###########################################################################
  1673.  
  1674.  
  1675. Implement echo server and client in java using UDP sockets.
  1676. Code:
  1677. udps.java
  1678. import java.io.*;
  1679. import java.net.*;
  1680. class udps
  1681. {
  1682. public static int clientport = 8040,serverport = 8050;
  1683. public static void main(String args[]) throws Exception
  1684. {
  1685. DatagramSocket SrvSoc = new DatagramSocket(clientport);
  1686. byte[] SData = new byte[1024];
  1687. BufferedReader br = new BufferedReader(new
  1688. InputStreamReader(System.in));
  1689. System.out.println("Server Ready");
  1690. while (true)
  1691. {
  1692. byte[] RData = new byte[1024];
  1693. DatagramPacket RPack = new DatagramPacket(RData,
  1694. RData.length);
  1695. SrvSoc.receive(RPack);
  1696. String Text = new String(RPack.getData());
  1697. if (Text.trim().length() == 0)
  1698. break;
  1699. System.out.println("\nFrom Client <<< " + Text );
  1700. System.out.print("Msg to Cleint : " );
  1701. String srvmsg = br.readLine();
  1702. InetAddress IPAddr = RPack.getAddress();
  1703. SData = srvmsg.getBytes();
  1704. DatagramPacket SPack = new DatagramPacket(SData,
  1705. SData.length, IPAddr, serverport);
  1706. SrvSoc.send(SPack);
  1707. }
  1708. System.out.println("\nClient Quits\n");
  1709. SrvSoc.close();
  1710. }
  1711. }
  1712.  
  1713. udpc.java
  1714.  
  1715. import java.io.*;
  1716. import java.net.*;
  1717. class udpchatclient
  1718. {
  1719. public static int clientport = 8040,serverport = 8050;
  1720. public static void main(String args[]) throws Exception
  1721. {
  1722. BufferedReader br = new BufferedReader(new
  1723. InputStreamReader (System.in));
  1724. DatagramSocket CliSoc = new DatagramSocket(serverport);
  1725. InetAddress IPAddr;
  1726. String Text;
  1727. if (args.length == 0)
  1728. IPAddr = InetAddress.getLocalHost();
  1729. else
  1730. IPAddr = InetAddress.getByName(args[0]);
  1731. byte[] SData = new byte[1024];
  1732. System.out.println("Press Enter without text to quit");
  1733. while (true)
  1734. {
  1735. System.out.print("\nEnter text for server : ");
  1736. Text = br.readLine();
  1737. SData = Text.getBytes();
  1738. DatagramPacket SPack = new DatagramPacket(SData,
  1739. SData.length, IPAddr, clientport );
  1740. CliSoc.send(SPack);
  1741. if (Text.trim().length() == 0)
  1742. break;
  1743. byte[] RData = new byte[1024];
  1744. DatagramPacket RPack = new DatagramPacket(RData,
  1745. RData.length);
  1746. CliSoc.receive(RPack);
  1747. String Echo = new String(RPack.getData()) ;
  1748. Echo = Echo.trim();
  1749. System.out.println("From Server <<< " + Echo);}
  1750. CliSoc.close();}}
  1751.  
  1752.  
  1753. #################################################################
  1754.  
  1755.  
  1756. Write a program to implement a text based message transfer from client to server process using UDP.
  1757.  
  1758.  
  1759. client
  1760.  
  1761. import java.io.*;
  1762. import java.net.*;
  1763. class udpc
  1764. {
  1765. public static void main(String args[]) throws Exception
  1766. {
  1767. BufferedReader inFromUser =new BufferedReader(new InputStreamReader(System.in));
  1768. DatagramSocket clientSocket = new DatagramSocket();
  1769. //Client Socket is created
  1770. InetAddress IPAddress = InetAddress.getByName("localhost");
  1771. //Gets the IP Address
  1772. byte[] sendData = new byte[1024];
  1773. byte[] receiveData = new byte[1024];
  1774. String sentence = inFromUser.readLine();
  1775. sendData = sentence.getBytes();
  1776. //sends data
  1777. DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
  1778. clientSocket.send(sendPacket);
  1779. DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
  1780. clientSocket.receive(receivePacket);
  1781. String modifiedSentence = new String(receivePacket.getData());
  1782. System.out.println("FROM SERVER:" + modifiedSentence);
  1783. clientSocket.close();
  1784. }
  1785. }
  1786.  
  1787.  
  1788.  
  1789. server
  1790.  
  1791. import java.io.*;
  1792. import java.net.*;
  1793. class udps
  1794. {
  1795. public static void main(String args[]) throws Exception
  1796. {
  1797. DatagramSocket serverSocket = new DatagramSocket(9876);
  1798. //Server Socekt Created
  1799. byte[] receiveData = new byte[1024];
  1800. byte[] sendData = new byte[1024];
  1801. while(true)
  1802. {
  1803. DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
  1804. serverSocket.receive(receivePacket);
  1805. String sentence = new String( receivePacket.getData());
  1806. System.out.println("RECEIVED: " + sentence);
  1807. InetAddress IPAddress = receivePacket.getAddress();
  1808. int port = receivePacket.getPort();
  1809. String capitalizedSentence = sentence.toUpperCase();
  1810. //Change sentence to Capital letter
  1811. sendData = capitalizedSentence.getBytes();
  1812. DatagramPacket sendPacket =
  1813. new DatagramPacket(sendData, sendData.length, IPAddress, port);
  1814. serverSocket.send(sendPacket);
  1815. //Send Capitalized data back to client
  1816. }
  1817. }
  1818. }
  1819.  
  1820.  
  1821. ###################################################################################
  1822.  
  1823. . Implement a chat server and client in java using UDP sockets.
  1824.  
  1825.  
  1826. Client:
  1827.  
  1828. import java.io.*;
  1829. import java.net.*;
  1830. import java.util.*;
  1831. public class chatclient
  1832. {
  1833. public static void main(String ar[])
  1834. {
  1835. try
  1836. {
  1837. Scanner sc = new Scanner(System.in);
  1838. byte s[] = new byte[1024];
  1839. byte r[] = new byte[1024];
  1840. DatagramSocket ds = new DatagramSocket(4234);
  1841. while(true)
  1842. {
  1843. DatagramPacket drp = new DatagramPacket(r,r.length);
  1844. ds.receive(drp);
  1845. String temp = new String(drp.getData());
  1846. System.out.println(temp);
  1847. int port = drp.getPort();
  1848. InetAddress host = drp.getAddress();
  1849. System.out.println("Enter Message: ");
  1850. String msg = sc.nextLine();
  1851. s = msg.getBytes();
  1852. DatagramPacket dsp = new DatagramPacket(s,s.length,host,port);
  1853. ds.send(dsp);
  1854. }
  1855. }
  1856. catch(Exception e)
  1857. {
  1858. }
  1859. }
  1860. }
  1861.  
  1862. Server:
  1863.  
  1864. import java.io.*;
  1865. import java.net.*;
  1866. import java.util.*;
  1867. public class chatserver
  1868. {
  1869. public static void main(String ar[])
  1870. {
  1871. try
  1872. {
  1873. Scanner sc = new Scanner(System.in);
  1874. byte s[] = new byte[1024];
  1875. byte r[] = new byte[1024];
  1876. DatagramSocket ds = new DatagramSocket(6566);
  1877. while(true)
  1878. {
  1879. System.out.println("Enter Message: ");
  1880. String msg = sc.nextLine();
  1881. s = msg.getBytes();
  1882. int port = 4234;
  1883. InetAddress host = InetAddress.getLocalHost();
  1884. DatagramPacket dsp = new DatagramPacket(s,s.length,host,port);
  1885. ds.send(dsp);
  1886. DatagramPacket drp = new DatagramPacket(r,r.length);
  1887. ds.receive(drp);
  1888. String temp = new String(drp.getData());
  1889. System.out.println(temp);
  1890. }
  1891. }
  1892. catch(Exception e)
  1893. {
  1894. }
  1895. }
  1896. }
  1897.  
  1898. ###############################################################################
  1899.  
  1900.  
  1901. &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&THE GREAT C
  1902.  
  1903. C TCP UDP
  1904.  
  1905.  
  1906.  
  1907. To write a socket program to implement a TCP chat application.
  1908.  
  1909.  
  1910. Server Code :
  1911.  
  1912. #include<stdio.h>
  1913. #include<netinet/in.h>
  1914. #include<sys/types.h>
  1915. #include<sys/socket.h>
  1916. #include<netdb.h>
  1917. #include<stdlib.h>
  1918. #include<string.h>
  1919. #define MAX 80
  1920. #define PORT 43454
  1921. #define SA struct sockaddr
  1922. void func(int sockfd)
  1923. {
  1924. char buff[MAX];
  1925. int n;
  1926. for(;;)
  1927. {
  1928. bzero(buff,MAX);
  1929. read(sockfd,buff,sizeof(buff));
  1930. printf("From client: %s\t To client : ",buff);
  1931. bzero(buff,MAX);
  1932. n=0;
  1933. while((buff[n++]=getchar())!='\n');
  1934. write(sockfd,buff,sizeof(buff));
  1935. if(strncmp("exit",buff,4)==0)
  1936. {
  1937. printf("Server Exit...\n");
  1938. break;
  1939. }
  1940. }
  1941. }
  1942. int main()
  1943. {
  1944. int sockfd,connfd,len;
  1945. struct sockaddr_in servaddr,cli;
  1946. sockfd=socket(AF_INET,SOCK_STREAM,0);
  1947. if(sockfd==-1)
  1948. {
  1949. printf("socket creation failed...\n");
  1950. exit(0);
  1951. }
  1952. else
  1953. printf("Socket successfully created..\n");
  1954. bzero(&servaddr,sizeof(servaddr));
  1955. servaddr.sin_family=AF_INET;
  1956. servaddr.sin_addr.s_addr=htonl(INADDR_ANY);
  1957. servaddr.sin_port=htons(PORT);
  1958. if((bind(sockfd,(SA*)&servaddr, sizeof(servaddr)))!=0)
  1959. {
  1960. printf("socket bind failed...\n");
  1961. exit(0);
  1962. }
  1963. else
  1964. printf("Socket successfully binded..\n");
  1965. if((listen(sockfd,5))!=0)
  1966. {
  1967. printf("Listen failed...\n");
  1968. exit(0);
  1969. }
  1970. else
  1971. printf("Server listening..\n");
  1972. len=sizeof(cli);
  1973. connfd=accept(sockfd,(SA *)&cli,&len);
  1974. if(connfd<0)
  1975. {
  1976. printf("server acccept failed...\n");
  1977. exit(0);
  1978. }
  1979. else
  1980. printf("server acccept the client...\n");
  1981. func(connfd);
  1982. close(sockfd);
  1983. }
  1984.  
  1985.  
  1986.  
  1987. Client Code:
  1988.  
  1989. #include<stdio.h>
  1990. #include<netinet/in.h>
  1991. #include<sys/types.h>
  1992. #include<sys/socket.h>
  1993. #include<netdb.h>
  1994. #include<string.h>
  1995. #include<stdlib.h>
  1996. #define MAX 80
  1997. #define PORT 43454
  1998. #define SA struct sockaddr
  1999. void func(int sockfd)
  2000. {
  2001. char buff[MAX];
  2002. int n;
  2003. for(;;)
  2004. {
  2005. bzero(buff,sizeof(buff));
  2006. printf("Enter the string : ");
  2007. n=0;
  2008. while((buff[n++]=getchar())!='\n');
  2009. write(sockfd,buff,sizeof(buff));
  2010. bzero(buff,sizeof(buff));
  2011. read(sockfd,buff,sizeof(buff));
  2012. printf("From Server : %s",buff);
  2013. if((strncmp(buff,"exit",4))==0)
  2014. {
  2015. printf("Client Exit...\n");
  2016. break;
  2017. }
  2018. }
  2019. }
  2020.  
  2021. int main()
  2022. {
  2023. int sockfd,connfd;
  2024. struct sockaddr_in servaddr,cli;
  2025. sockfd=socket(AF_INET,SOCK_STREAM,0);
  2026. if(sockfd==-1)
  2027. {
  2028. printf("socket creation failed...\n");
  2029. exit(0);
  2030. }
  2031. else
  2032. printf("Socket successfully created..\n");
  2033. bzero(&servaddr,sizeof(servaddr));
  2034. servaddr.sin_family=AF_INET;
  2035. servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
  2036. servaddr.sin_port=htons(PORT);
  2037. if(connect(sockfd,(SA *)&servaddr,sizeof(servaddr))!=0)
  2038. {
  2039. printf("connection with the server failed...\n");
  2040. exit(0);
  2041. }
  2042. else
  2043. printf("connected to the server..\n");
  2044. func(sockfd);
  2045. close(sockfd);
  2046. }
  2047.  
  2048.  
  2049.  
  2050. ##################################################################
  2051.  
  2052. To write a socket program to implement file transfer protocol.
  2053.  
  2054. Server Code :
  2055.  
  2056. #include <sys/socket.h>
  2057. #include <netinet/in.h>
  2058. #include <arpa/inet.h>
  2059. #include <stdio.h>
  2060. #include <stdlib.h>
  2061. #include <unistd.h>
  2062. #include <errno.h>
  2063. #include <string.h>
  2064. #include <sys/types.h>
  2065.  
  2066. int main(void)
  2067. {
  2068. int listenfd = 0;
  2069. int connfd = 0;
  2070. struct sockaddr_in serv_addr;
  2071. char sendBuff[1025];
  2072. int numrv;
  2073.  
  2074. listenfd = socket(AF_INET, SOCK_STREAM, 0);
  2075.  
  2076. printf("Socket retrieve success\n");
  2077.  
  2078. memset(&serv_addr, '0', sizeof(serv_addr));
  2079. memset(sendBuff, '0', sizeof(sendBuff));
  2080.  
  2081. serv_addr.sin_family = AF_INET;
  2082. serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  2083. serv_addr.sin_port = htons(5000);
  2084.  
  2085. bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr));
  2086.  
  2087. if(listen(listenfd, 10) == -1)
  2088. {
  2089. printf("Failed to listen\n");
  2090. return -1;
  2091. }
  2092.  
  2093.  
  2094. while(1)
  2095. {
  2096. connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL);
  2097.  
  2098. FILE *fp = fopen("sample_file.txt","rb");
  2099. if(fp==NULL)
  2100. {
  2101. printf("File opern error");
  2102. return 1;
  2103. }
  2104.  
  2105. while(1)
  2106. {
  2107. unsigned char buff[256]={0};
  2108. int nread = fread(buff,1,256,fp);
  2109. printf("Bytes read %d \n", nread);
  2110.  
  2111. if(nread > 0)
  2112. {
  2113. printf("Sending \n");
  2114. write(connfd, buff, nread);
  2115. }
  2116. if (nread < 256)
  2117. {
  2118. if (feof(fp))
  2119. printf("End of file\n");
  2120. if (ferror(fp))
  2121. printf("Error reading\n");
  2122. break;
  2123. }
  2124.  
  2125.  
  2126. }
  2127.  
  2128. close(connfd);
  2129. sleep(1);
  2130. }
  2131. }
  2132.  
  2133.  
  2134. Client Code:
  2135.  
  2136. #include <sys/socket.h>
  2137. #include <sys/types.h>
  2138. #include <netinet/in.h>
  2139. #include <netdb.h>
  2140. #include <stdio.h>
  2141. #include <string.h>
  2142. #include <stdlib.h>
  2143. #include <unistd.h>
  2144. #include <errno.h>
  2145. #include <arpa/inet.h>
  2146. int main(void)
  2147. {
  2148. int sockfd = 0;
  2149. int bytesReceived = 0;
  2150. char recvBuff[256];
  2151. memset(recvBuff, '0', sizeof(recvBuff));
  2152. struct sockaddr_in serv_addr;
  2153.  
  2154. if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0)
  2155. {
  2156. printf("\n Error : Could not create socket \n");
  2157. return 1;
  2158. }
  2159.  
  2160. serv_addr.sin_family = AF_INET;
  2161. serv_addr.sin_port = htons(5000); // port
  2162. serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
  2163.  
  2164. if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr))<0)
  2165. {
  2166. printf("\n Error : Connect Failed \n");
  2167. return 1;
  2168. }
  2169.  
  2170.  
  2171. FILE *fp;
  2172. fp = fopen("sample_file.txt", "ab");
  2173. if(NULL == fp)
  2174. {
  2175. printf("Error opening file");
  2176. return 1;
  2177. }
  2178. while((bytesReceived = read(sockfd, recvBuff, 256)) > 0)
  2179. {
  2180. printf("Bytes received %d\n",bytesReceived);
  2181. recvBuff[bytesReceived] = 0;
  2182. fwrite(recvBuff, 1,bytesReceived,fp);
  2183. printf("%s \n", recvBuff); }
  2184. if(bytesReceived < 0)
  2185. {
  2186. printf("\n Read Error \n");
  2187. }
  2188. return 0;
  2189. }
  2190.  
  2191.  
  2192. #######################################################################################
  2193.  
  2194. To write a program to implement UDP protocol by means of a message transfer.
  2195. Code :
  2196. #include <arpa/inet.h>
  2197. #include <netinet/in.h>
  2198. #include <stdio.h>
  2199. #include <sys/types.h>
  2200. #include <sys/socket.h>
  2201. #include <unistd.h>
  2202.  
  2203. #define BUFLEN 512
  2204. #define NPACK 10
  2205. #define PORT 9930
  2206.  
  2207. void diep(char *s)
  2208. {
  2209. perror(s);
  2210. exit(1);
  2211. }
  2212.  
  2213. int main(void)
  2214. {
  2215. struct sockaddr_in si_me, si_other;
  2216. int s, i, slen=sizeof(si_other);
  2217. char buf[BUFLEN];
  2218.  
  2219. if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
  2220. diep("socket");
  2221.  
  2222. memset((char *) &si_me, 0, sizeof(si_me));
  2223. si_me.sin_family = AF_INET;
  2224. si_me.sin_port = htons(PORT);
  2225. si_me.sin_addr.s_addr = htonl(INADDR_ANY);
  2226. if (bind(s, &si_me, sizeof(si_me))==-1)
  2227. diep("bind");
  2228.  
  2229. for (i=0; i<NPACK; i++) {
  2230. if (recvfrom(s, buf, BUFLEN, 0, &si_other, &slen)==-1)
  2231. diep("recvfrom()");
  2232. printf("Received packet from %s:%d\nData: %s\n\n",
  2233. inet_ntoa(si_other.sin_addr), ntohs(si_other.sin_port), buf);
  2234. }
  2235.  
  2236. close(s);
  2237. return 0;
  2238. }
  2239.  
  2240.  
  2241. Client :
  2242. #define SRV_IP "999.999.999.999"
  2243. int main(void)
  2244. {
  2245. struct sockaddr_in si_other;
  2246. int s, i, slen=sizeof(si_other);
  2247. char buf[BUFLEN];
  2248.  
  2249. if ((s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1)
  2250. diep("socket");
  2251.  
  2252. memset((char *) &si_other, 0, sizeof(si_other));
  2253. si_other.sin_family = AF_INET;
  2254. si_other.sin_port = htons(PORT);
  2255. if (inet_aton(SRV_IP, &si_other.sin_addr)==0) {
  2256. fprintf(stderr, "inet_aton() failed\n");
  2257. exit(1);
  2258. }
  2259.  
  2260. for (i=0; i<NPACK; i++) {
  2261. printf("Sending packet %d\n", i);
  2262. sprintf(buf, "This is packet %d\n", i);
  2263. if (sendto(s, buf, BUFLEN, 0, &si_other, slen)==1)
  2264. diep("sendto()");
  2265. }
  2266.  
  2267. close(s);
  2268. return 0;
  2269. }
  2270.  
  2271. ########################################################################################
  2272.  
  2273.  
  2274. To write a program to implement client authentication of username and password
  2275.  
  2276. Code :
  2277. Server :
  2278. //authentication server - socket, memset, sockaddr_in in ip7, bind, listen, accept, write, read
  2279. #include <sys/types.h>
  2280. #include <sys/socket.h>
  2281. #include <unistd.h>
  2282. #include <stdio.h>
  2283. #include <string.h>
  2284. #include <netinet/in.h>
  2285. #include <arpa/inet.h>
  2286. #include <errno.h>
  2287. #define ANSI_COLOR_GREEN "\x1b[32m"
  2288. #define ANSI_COLOR_RESET "\x1b[0m"
  2289.  
  2290. struct user {
  2291. char *username;
  2292. char *password;
  2293. };
  2294. int main() {
  2295.  
  2296. /*login details*/
  2297. struct user singleUser;
  2298. singleUser.username = "omijn";
  2299. singleUser.password = "qwerty";
  2300.  
  2301. /*messages*/
  2302. char * userOK_enterPass = "Please enter your password : ";
  2303. char * userNotFound = "This username does not exist.";
  2304. char * userAuthenticated = "User authenticated!";
  2305. char * invalidPassword = "Invalid password.";
  2306.  
  2307. /*errors*/
  2308. int bindError = 0;
  2309.  
  2310. int serverSocketFD = 0, clientFD = 0, n = 0, auth = 0;
  2311. char receiveBuffer[1024] = "", sendBuffer[1024] = "";
  2312. struct sockaddr_in serverAddress;
  2313.  
  2314. system("clear");
  2315.  
  2316. //create socket
  2317. if((serverSocketFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  2318. printf("> Socket creation failed.\n");
  2319. else
  2320. printf("> Socket created.\n");
  2321.  
  2322. //clear memory
  2323. memset(receiveBuffer, '0', sizeof(receiveBuffer));
  2324. memset(sendBuffer, '0', sizeof(sendBuffer));
  2325. memset(&serverAddress, '0', sizeof(serverAddress));
  2326.  
  2327. //server address
  2328. serverAddress.sin_family = AF_INET;
  2329. serverAddress.sin_port = htons(2884);
  2330. serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
  2331. printf("> Address created.\n");
  2332.  
  2333. //assign name to server
  2334. if((bind(serverSocketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) == -1) {
  2335. printf("> Bind error.\n");
  2336. bindError = errno;
  2337. printf("%s\n", strerror(bindError));
  2338. return -1;
  2339. }
  2340. else
  2341. printf("> Binding successful.\n");
  2342.  
  2343. //listen
  2344. if((listen(serverSocketFD, 5)) == -1)
  2345. printf("> Listen error.\n");
  2346. else
  2347. printf("> Server listening.\n");
  2348.  
  2349. //accept connection
  2350. if((clientFD = accept(serverSocketFD, (struct sockaddr *)NULL, NULL)) != 0)
  2351. printf(ANSI_COLOR_GREEN "> Client connected!\n" ANSI_COLOR_RESET);
  2352. else
  2353. printf("> Client connect error.\n");
  2354.  
  2355. while(!auth) {
  2356.  
  2357. /* receive ------------------------------------------------------------------- */
  2358. while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
  2359. if(n == -1)
  2360. printf("> Read error.\n");
  2361. receiveBuffer[n] = 0;
  2362. break;
  2363. }
  2364.  
  2365.  
  2366. if(strcmp(receiveBuffer, singleUser.username) == 0) {
  2367. write(clientFD, userOK_enterPass, strlen(userOK_enterPass));
  2368.  
  2369. auth = 0;
  2370.  
  2371. while(!auth) {
  2372.  
  2373. while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
  2374. if(n == -1)
  2375. printf("> Read error.\n");
  2376. receiveBuffer[n] = 0;
  2377. break;
  2378. }
  2379.  
  2380.  
  2381. if(strcmp(receiveBuffer, singleUser.password) == 0) {
  2382. /*user authenticated*/
  2383. auth = 1;
  2384.  
  2385. printf("\n%s", userAuthenticated);
  2386.  
  2387. write(clientFD, userAuthenticated, strlen(userAuthenticated));
  2388.  
  2389. }
  2390.  
  2391. else {
  2392. auth = 0;
  2393.  
  2394. printf("\n%s", invalidPassword);
  2395.  
  2396. write(clientFD, invalidPassword, strlen(invalidPassword));
  2397.  
  2398. }
  2399.  
  2400. }
  2401.  
  2402. }
  2403.  
  2404. else {
  2405. printf("\n%s", userNotFound);
  2406. write(clientFD, userNotFound, strlen(userNotFound));
  2407. }
  2408.  
  2409.  
  2410. printf(ANSI_COLOR_GREEN "\n%s" ANSI_COLOR_RESET, receiveBuffer);
  2411.  
  2412. //clear receive buffer for next use
  2413. strcpy(receiveBuffer, "");
  2414.  
  2415. //clear send buffer for next use
  2416. strcpy(sendBuffer, "");
  2417.  
  2418. }
  2419.  
  2420. printf("\n");
  2421.  
  2422. return 0;
  2423. }
  2424.  
  2425. Client :
  2426.  
  2427. #include <sys/types.h>
  2428. #include <sys/socket.h>
  2429. #include <unistd.h>
  2430. #include <stdio.h>
  2431. #include <string.h>
  2432. #include <netinet/in.h>
  2433. #include <arpa/inet.h>
  2434. #include <errno.h>
  2435. #define ANSI_COLOR_GREEN "\x1b[32m"
  2436. #define ANSI_COLOR_RESET "\x1b[0m"
  2437.  
  2438. struct user {
  2439. char *username;
  2440. char *password;
  2441. };
  2442.  
  2443. int main() {
  2444.  
  2445. /*login details*/
  2446. struct user singleUser;
  2447. singleUser.username = "omijn";
  2448. singleUser.password = "qwerty";
  2449.  
  2450.  
  2451. /*messages*/
  2452. char * userOK_enterPass = "Please enter your password : ";
  2453. char * userNotFound = "This username does not exist.";
  2454. char * userAuthenticated = "User authenticated!";
  2455. char * invalidPassword = "Invalid password.";
  2456.  
  2457.  
  2458. /*errors*/
  2459. int bindError = 0;
  2460.  
  2461. int serverSocketFD = 0, clientFD = 0, n = 0, auth = 0;
  2462. char receiveBuffer[1024] = "", sendBuffer[1024] = "";
  2463. struct sockaddr_in serverAddress;
  2464.  
  2465. system("clear");
  2466.  
  2467. //create socket
  2468. if((serverSocketFD = socket(AF_INET, SOCK_STREAM, 0)) == -1)
  2469. printf("> Socket creation failed.\n");
  2470. else
  2471. printf("> Socket created.\n");
  2472.  
  2473. //clear memory
  2474. memset(receiveBuffer, '0', sizeof(receiveBuffer));
  2475. memset(sendBuffer, '0', sizeof(sendBuffer));
  2476. memset(&serverAddress, '0', sizeof(serverAddress));
  2477.  
  2478. //server address
  2479. serverAddress.sin_family = AF_INET;
  2480. serverAddress.sin_port = htons(2884);
  2481. serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
  2482. printf("> Address created.\n");
  2483.  
  2484. //assign name to server
  2485. if((bind(serverSocketFD, (struct sockaddr*)&serverAddress, sizeof(serverAddress))) == -1) {
  2486. printf("> Bind error.\n");
  2487. bindError = errno;
  2488. printf("%s\n", strerror(bindError));
  2489. return -1;
  2490. }
  2491. else
  2492. printf("> Binding successful.\n");
  2493.  
  2494. //listen
  2495. if((listen(serverSocketFD, 5)) == -1)
  2496. printf("> Listen error.\n");
  2497. else
  2498. printf("> Server listening.\n");
  2499.  
  2500. //accept connection
  2501. if((clientFD = accept(serverSocketFD, (struct sockaddr *)NULL, NULL)) != 0)
  2502. printf(ANSI_COLOR_GREEN "> Client connected!\n" ANSI_COLOR_RESET);
  2503. else
  2504. printf("> Client connect error.\n");
  2505.  
  2506. while(!auth) {
  2507.  
  2508. /* receive ------------------------------------------------------------------- */
  2509. while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
  2510. if(n == -1)
  2511. printf("> Read error.\n");
  2512. receiveBuffer[n] = 0;
  2513. break;
  2514. }
  2515.  
  2516.  
  2517. if(strcmp(receiveBuffer, singleUser.username) == 0) {
  2518. write(clientFD, userOK_enterPass, strlen(userOK_enterPass));
  2519.  
  2520. auth = 0;
  2521.  
  2522. while(!auth) {
  2523.  
  2524. while((n = read(clientFD, receiveBuffer, sizeof(receiveBuffer) - 1)) > 0) {
  2525. if(n == -1)
  2526. printf("> Read error.\n");
  2527. receiveBuffer[n] = 0;
  2528. break;
  2529. }
  2530.  
  2531.  
  2532. if(strcmp(receiveBuffer, singleUser.password) == 0) {
  2533. /*user authenticated*/
  2534. auth = 1;
  2535.  
  2536. printf("\n%s", userAuthenticated);
  2537.  
  2538. write(clientFD, userAuthenticated, strlen(userAuthenticated));
  2539.  
  2540. }
  2541.  
  2542. else {
  2543. auth = 0;
  2544.  
  2545. printf("\n%s", invalidPassword);
  2546.  
  2547. write(clientFD, invalidPassword, strlen(invalidPassword));
  2548.  
  2549. }
  2550.  
  2551. }
  2552.  
  2553. }
  2554.  
  2555. else {
  2556. printf("\n%s", userNotFound);
  2557. write(clientFD, userNotFound, strlen(userNotFound));
  2558. }
  2559.  
  2560.  
  2561. printf(ANSI_COLOR_GREEN "\n%s" ANSI_COLOR_RESET, receiveBuffer);
  2562.  
  2563. //clear receive buffer for next use
  2564. strcpy(receiveBuffer, "");
  2565.  
  2566. //clear send buffer for next use
  2567. strcpy(sendBuffer, "");
  2568.  
  2569. }
  2570.  
  2571. printf("\n");
  2572.  
  2573. return 0;}
  2574.  
  2575.  
  2576. ##########################################################################################
  2577.  
  2578. To write a program to implement the Echo UDP Server
  2579.  
  2580. Code :
  2581. Server
  2582. #include <stdio.h>
  2583. #include <sys/socket.h>
  2584. #include <netinet/in.h>
  2585. #include <string.h>
  2586. #include <stdlib.h>
  2587.  
  2588. int main(){
  2589. int udpSocket, nBytes;
  2590. char buffer[1024];
  2591. struct sockaddr_in serverAddr, clientAddr;
  2592. struct sockaddr_storage serverStorage;
  2593. socklen_t addr_size, client_addr_size;
  2594. int i;
  2595.  
  2596. /*Create UDP socket*/
  2597. udpSocket = socket(PF_INET, SOCK_DGRAM, 0);
  2598.  
  2599. /*Configure settings in address struct*/
  2600. serverAddr.sin_family = AF_INET;
  2601. serverAddr.sin_port = htons(7891);
  2602. serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  2603. memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
  2604.  
  2605. /*Bind socket with address struct*/
  2606. bind(udpSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
  2607.  
  2608. /*Initialize size variable to be used later on*/
  2609. addr_size = sizeof serverStorage;
  2610.  
  2611. while(1){
  2612.  
  2613. nBytes = recvfrom(udpSocket,buffer,1024,0,(struct sockaddr *)&serverStorage, &addr_size);
  2614.  
  2615. /*Convert message received to uppercase*/
  2616. for(i=0;i<nBytes-1;i++)
  2617. buffer[i] = toupper(buffer[i]);
  2618.  
  2619. /*Send uppercase message back to client, using serverStorage as the address*/
  2620. sendto(udpSocket,buffer,nBytes,0,(struct sockaddr *)&serverStorage,addr_size);
  2621. }
  2622.  
  2623. return 0;
  2624. }
  2625.  
  2626. Client:
  2627. #include <stdio.h>
  2628. #include <sys/socket.h>
  2629. #include <netinet/in.h>
  2630. #include <string.h>
  2631.  
  2632. int main(){
  2633. int clientSocket, portNum, nBytes;
  2634. char buffer[1024];
  2635. struct sockaddr_in serverAddr;
  2636. socklen_t addr_size;
  2637.  
  2638. /*Create UDP socket*/
  2639. clientSocket = socket(PF_INET, SOCK_DGRAM, 0);
  2640.  
  2641. /*Configure settings in address struct*/
  2642. serverAddr.sin_family = AF_INET;
  2643. serverAddr.sin_port = htons(7891);
  2644. serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
  2645. memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);
  2646.  
  2647. /*Initialize size variable to be used later on*/
  2648. addr_size = sizeof serverAddr;
  2649.  
  2650. while(1){
  2651. printf("Type a sentence to send to server:\n");
  2652. fgets(buffer,1024,stdin);
  2653. printf("You typed: %s",buffer);
  2654.  
  2655. nBytes = strlen(buffer) + 1;
  2656.  
  2657. /*Send message to server*/
  2658. sendto(clientSocket,buffer,nBytes,0,(struct sockaddr *)&serverAddr,addr_size);
  2659.  
  2660. /*Receive message from server*/
  2661. nBytes = recvfrom(clientSocket,buffer,1024,0,NULL, NULL);
  2662.  
  2663. printf("Received from server: %s\n",buffer);
  2664.  
  2665. }
  2666.  
  2667. return 0;
  2668. }
  2669.  
  2670.  
  2671.  
  2672. --------------------------------------------------------------------------------------------------------------------------------------------------------------------
Add Comment
Please, Sign In to add comment