Subversion Repositories Kolibri OS

Rev

Rev 8448 | Go to most recent revision | Blame | Last modification | View Log | Download | RSS feed

  1. #include <net/network.h>
  2. #include <conio.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. int main() {
  8.         con_init_console_dll();
  9.     networklib_init();
  10.     con_set_title("http request demo using raw sockets");
  11.  
  12.     char *host = "kolibrios.org";
  13.     int port = 80;
  14.     printf("Connecting to %s on port %d\n", host, port);
  15.  
  16.     struct addrinfo *addr_info;
  17.     char port_str[16]; sprintf(port_str, "%d", port);
  18.     struct addrinfo hints;
  19.     memset(&hints, 0, sizeof(hints));
  20.     hints.ai_family = AF_UNSPEC; // IPv4 or IPv6 doesnt matter
  21.     hints.ai_socktype = SOCK_STREAM; // TCP stream sockets
  22.     if (getaddrinfo(host, port_str, 0, &addr_info) != 0) {
  23.         printf("Host %s not found!\n", host);
  24.         freeaddrinfo(addr_info);
  25.         exit(-1);
  26.     }
  27.     printf("IP address of %s is %s\n", host, inet_ntoa(addr_info->ai_addr->sin_addr));  
  28.     //printf("Host port = %d\n", addr_info->ai_addr->sin_port >> 8);
  29.  
  30.     char request[256];
  31.     sprintf(request, "GET /en/ HTTP/1.1\r\nHost: %s\r\n\r\n", host);
  32.     printf("request = %s\n", request);
  33.  
  34.     int sock = socket(AF_INET4, SOCK_STREAM, IPPROTO_TCP);
  35.  
  36.     puts("Connecting...\n");
  37.     if (connect(sock, addr_info->ai_addr, addr_info->ai_addrlen) != 0) {
  38.         printf("Connection failed, err_code = %d\n", err_code);
  39.         exit(err_code);
  40.     }
  41.     puts("Connected successfully\n");
  42.  
  43.     puts("Sending request...\n");
  44.     if (send(sock, request, strlen(request), MSG_NOFLAG) == -1) {
  45.         printf("Sending failed, err_code = %d\n", err_code);
  46.         exit(err_code);
  47.     }
  48.     puts("Request sended successfully, waiting for response...\n");
  49.  
  50.     char buf[512 + 1];
  51.     if (recv(sock, buf, 512, MSG_NOFLAG) == -1) {
  52.         printf("Receive failed, err_code = %d\n", err_code);
  53.         exit(err_code);
  54.     }
  55.  
  56.     printf("Response = %s\n", buf);
  57.  
  58.     freeaddrinfo(addr_info);
  59.  
  60.     close(sock);
  61.     puts("\n goodbye)\n");
  62.     con_exit(0);
  63.         return 0;
  64. }