Subversion Repositories Kolibri OS

Rev

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

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