Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6.  
  7. #include <netinet/tcp.h>
  8. #include <sys/socket.h>
  9. #include <sys/types.h>
  10. #include <netinet/in.h>
  11. #include <netdb.h>
  12.  
  13. int socket_connect(char *host, in_port_t port){
  14. struct hostent *hp;
  15. struct sockaddr_in addr;
  16. int on = 1, sock;
  17.  
  18. if((hp = gethostbyname(host)) == NULL){
  19. herror("gethostbyname");
  20. exit(1);
  21. }
  22. bcopy(hp->h_addr, &addr.sin_addr, hp->h_length);
  23. addr.sin_port = htons(port);
  24. addr.sin_family = AF_INET;
  25. sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
  26. setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (const char *)&on, sizeof(int));
  27.  
  28. if(sock == -1){
  29. perror("setsockopt");
  30. exit(1);
  31. }
  32.  
  33. if(connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)) == -1){
  34. perror("connect");
  35. exit(1);
  36.  
  37. }
  38. return sock;
  39. }
  40.  
  41. #define BUFFER_SIZE 1024
  42.  
  43. int main(int argc, char *argv[]){
  44. int fd;
  45. char buffer[BUFFER_SIZE];
  46.  
  47. if(argc < 3){
  48. fprintf(stderr, "Usage: %s <hostname> <port>\n", argv[0]);
  49. exit(1);
  50. }
  51.  
  52. fd = socket_connect(argv[1], atoi(argv[2]));
  53. write(fd, "GET /\r\n", strlen("GET /\r\n")); // write(fd, char[]*, len);
  54. bzero(buffer, BUFFER_SIZE);
  55.  
  56. while(read(fd, buffer, BUFFER_SIZE - 1) != 0){
  57. fprintf(stderr, "%s", buffer);
  58. bzero(buffer, BUFFER_SIZE);
  59. }
  60.  
  61. shutdown(fd, SHUT_RDWR);
  62. close(fd);
  63.  
  64. return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement