Posted By

tandouri on 11/05/09


Tagged


Versions (?)

Sockets


 / Published in: C
 

  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4.  
  5. void die(char *message);
  6.  
  7. int main(int argc, char *argv[]) {
  8. int sockfd, newSock;
  9. int addrlen;
  10. char buffer[1024];
  11. struct sockaddr_in addr;
  12.  
  13. addr.sin_family = AF_INET;
  14. addr.sin_addr.s_addr = INADDR_ANY;
  15. addr.sin_port = htons(31336);
  16.  
  17. if( (sockfd = socket(AF_INET,SOCK_STREAM,0)) == -1)
  18. die("Couldn't create the socket.");
  19.  
  20. if( ( bind (sockfd, (struct sockaddr *)&addr, sizeof(addr) ) ) == -1 )
  21. die("Binding the socket to the port");
  22.  
  23. if( listen(sockfd,1) == -1)
  24. die("listening for connections");//There's got to be a better way to check for errors -.-
  25.  
  26. addrlen = sizeof(struct sockaddr_in);
  27. newSock = accept(sockfd, (struct sockaddr *)&addr, &addrlen);
  28.  
  29. char *message = "lolsup
  30. ";
  31. send(newSock,message,strlen(message),0);
  32.  
  33. recv(newSock, &buffer, 1024, 0);
  34.  
  35. printf("%s\n", buffer);
  36.  
  37. close(newSock);
  38.  
  39. shutdown(sockfd, 2);
  40. close(sockfd);
  41. }
  42.  
  43. void die(char *message) {
  44. printf("Error: %s\n", message);
  45. exit(0);
  46. }

Report this snippet  

You need to login to post a comment.