0

I have written a C-programm on Windows to get my location using freegeoip. The side just says that I must send a HTTP GET request in format freegeoip.net/{format}/{IP_or_hostname} where IP_or_hostname is optional and format can be csv, xml or json. So I did:

// ....

//Create a socket
if((s = socket(AF_INET , SOCK_STREAM , 0 )) == INVALID_SOCKET){
    printf("Could not create socket : %d" , WSAGetLastError());
}

printf("Socket created.\n");
server.sin_addr.s_addr = inet_addr("104.31.11.172"); //Actual address of url
server.sin_family = AF_INET;
server.sin_port = htons( 80 ); //Http port

//Connect to remote server
if (connect(s , (struct sockaddr *)&server , sizeof(server)) < 0){
    puts("connect error");
    return 1;
}
puts("Connected");

//Send some data
//I think this might be the error:
message = "GET freegeoip.net/csv HTTP/1.0\r\n\r\n"; 

if( send(s , message , strlen(message) , 0) < 0){
    puts("Send failed");
    return 1;
}
puts("Data Send\n");

//Receive a reply from the server
if((recv_size = recv(s , server_reply , 2000 , 0)) == SOCKET_ERROR){
    puts("recv failed");
}

puts("Reply received\n");

//Add a NULL terminating character to make it a proper string before printing
server_reply[recv_size] = '\0';
puts(server_reply);

I also tryed HTTP/1.1 or other strings for message, like:

message = "GET /csv HTTP/1.0\r\n\r\n"; 

But the only response I get is 400 Bad request or 403 Forbidden.

Alex S.
  • 31
  • 1
  • 6
  • Try to add a `/` after csv. And you might add a `host:` line – Gerhardh Apr 05 '17 at 08:31
  • HTTP response code 400 may be caused by header `HOST` absent. 403 may be caused by other header absent, as instance, `User-Agent`, or url path, or HTTP method. recommend read [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol). – neuo Apr 12 '17 at 06:57

0 Answers0