Guest User

Untitled

a guest
May 26th, 2018
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <sys/types.h>
  5. #include <sys/socket.h>
  6. #include <arpa/inet.h>
  7.  
  8.  
  9. int main(int argc, char *argv[])
  10. {
  11. if (argc < 2)
  12. {
  13. printf("Usage: %s <port_no>\n", argv[0]);
  14. exit(1);
  15. }
  16.  
  17. int sfd, cfd, port_no;
  18. port_no = strtoul(argv[1], NULL, 10);
  19.  
  20. /*
  21. Create your Socket do error checking
  22. Remember socket returns a socket descriptor
  23. SOCK_STREAM --->TCP
  24. or
  25. SOCK_DGRAM --->UDP
  26. AF_INET ------->protocol/address family
  27.  
  28. */
  29. if ((sfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
  30. {
  31. perror("socket");
  32. exit(2);
  33. }
  34.  
  35. struct sockaddr_in saddr = {0};
  36. saddr.sin_family = AF_INET;
  37. saddr.sin_port = htons(port_no);
  38. saddr.sin_addr.s_addr = INADDR_ANY;// Accept any ip address
  39.  
  40. //1. Bind is used for assigning port
  41. if (bind(sfd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
  42. {
  43. perror("bind");
  44. close(sfd);
  45. exit(3);
  46. }
  47.  
  48. //2. waits for incoming connection
  49. if (listen(sfd, 5) < 0)
  50. {
  51. perror("listen");
  52. close(sfd);
  53. exit(4);
  54. }
  55.  
  56. //3. Accepts the incoming connection
  57.  
  58. struct sockaddr_in caddr = {0};
  59. socklen_t len = sizeof(caddr);
  60. if ((cfd = accept(sfd, (struct sockaddr *)&caddr, &len)) < 0)
  61. {
  62. perror("accept");
  63. exit(5);
  64. }
  65.  
  66. // To make a program like ECHO
  67. char buf[20] = {0};
  68. int ret = 0;
  69. if ((ret = recv(cfd, buf, sizeof(buf), 0)) < 0)
  70. {
  71. perror("recv");
  72. close(cfd);
  73. close(sfd);
  74. exit(6);
  75. }
  76.  
  77. if (send(cfd, buf, ret, 0) < 0)
  78. {
  79. perror("send");
  80. close(cfd);
  81. close(sfd);
  82. exit(7);
  83. }
  84.  
  85. close(cfd);
  86. close(sfd);
  87.  
  88. return 0;
  89. }
Add Comment
Please, Sign In to add comment