Advertisement
Guest User

tmp

a guest
Nov 25th, 2015
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. /*
  2. ** server.c -- a stream socket server demo
  3. */
  4.  
  5. #include <stdio.h>
  6. #include <stdlib.h>
  7. #include <unistd.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <sys/types.h>
  11. #include <sys/socket.h>
  12. #include <netinet/in.h>
  13. #include <arpa/inet.h>
  14.  
  15. #define MYPORT 3499 // the port users will be connecting to
  16. #define BACKLOG 10 // how many pending connections queue will hold
  17.  
  18. int main(void)
  19. {
  20. int sockfd, new_fd; // listen on sock_fd, new connection on new_fd
  21. struct sockaddr_in my_addr; // my address information
  22. struct sockaddr_in their_addr; // connector's address information
  23. int sin_size;
  24. int yes=1;
  25.  
  26. if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  27. perror("socket");
  28. exit(1);
  29. }
  30.  
  31. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
  32. perror("setsockopt");
  33. exit(1);
  34. }
  35.  
  36. my_addr.sin_family = AF_INET; // host byte order
  37. my_addr.sin_port = htons(MYPORT); // short, network byte order
  38. my_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP
  39. memset(&(my_addr.sin_zero), '\0', 8); // zero the rest of the struct
  40.  
  41. if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
  42. perror("bind");
  43. exit(1);
  44. }
  45.  
  46. if (listen(sockfd, BACKLOG) == -1) {
  47. perror("listen");
  48. exit(1);
  49. }
  50.  
  51. while(1) { // main accept() loop
  52. sin_size = sizeof(struct sockaddr_in);
  53. if ((new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size)) == -1) {
  54. perror("accept");
  55. continue;
  56. }
  57. printf("server: got connection from %s\n",inet_ntoa(their_addr.sin_addr));
  58. if (send(new_fd, "Hello, world!\n", 14, 0) == -1)
  59. perror("send");
  60.  
  61. close(new_fd);
  62. }
  63.  
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement