-1

I wrote a basic C program that establishes a connection with the IP address of google.com and then starts receiving data from client.

But firstly, during compilation the following warning is generated:

test.c:12:25: warning: implicit declaration
      of function 'inet_addr' is invalid in
      C99 [-Wimplicit-function-declaration]
address.sin_addr.s_addr=inet_addr("2...
                        ^
1 warning generated.

Secondly, on running the program, the following output is generated:

HTTP/1.0 400 Bad Request
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
ContGET/HTTP/1.1

What changes can I make in my code to successfully receive data from an HTTP server ?

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>

int main()
{
    int mySocket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in address;
    address.sin_port = htons(80);
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = inet_addr("216.58.200.196");
    connect(mySocket, (struct sockaddr *)&address, sizeof(address));
    char msg[21] = "GET/HTTP/1.1\r\n\r\n";
    send(mySocket, msg, 21, 0);
    char msgRecv[100];
    recv(mySocket, msgRecv, 100, 0);
    printf("%s", msgRecv);
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    This HTTP request is wrong in multiple ways (at least missing spaces, no host header). Please study the standard if you really want to implement HTTP yourself, that what standards are for. – Steffen Ullrich Sep 18 '20 at 15:43
  • About the implicit declaration warning - you are missing the right `#include`, see https://linux.die.net/man/3/inet_addr –  Sep 18 '20 at 16:07
  • Could you elaborate on what the appropriate http request would be in this case ? I'm a beginner in socket programming – Debal Ghosh Sep 18 '20 at 16:35
  • @DebalGhosh like Steffen told you, you need to read the HTTP 1.1 standard spec, it outlines everything you need to know. Start with [RFC 2616](https://tools.ietf.org/html/rfc2616), and its successors RFCs 7230-7235. – Remy Lebeau Sep 19 '20 at 05:33

1 Answers1

1

Your code has many faults (lack of error handling, misusing send(), recv() and printf(), etc), but the main cause of the HTTP failure is because your HTTP request is malformed.

If you read the HTTP 1.1 protocol specification, RFC 2616 and its successors RFCs 7230-7235, you will see that you are missing required space characters between GET and /, and between / and HTTP, and that you are also missing a required Host header.

At a bare minimum, your HTTP request needs to look like this instead:

char msg[] = "GET / HTTP/1.1\r\nHost: google.com\r\n\r\n";

Once you have that working, look at this answer for the kind of logic you will need to implement afterwards to receive the server's response properly (a single call to recv() won't cut it, not even close).

Community
  • 1
  • 1
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770