我在Windows上编写了一个C-programm来使用freegeoip来获取我的位置。方面只是说我必须以freegeoip.net/{format}/ {IP_or_hostname}格式发送HTTP GET请求,其中IP_or_hostname是可选的,格式可以是csv,xml或json。所以我做了:
// ....
//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);
我还尝试使用HTTP / 1.1或其他字符串作为消息,例如:
message = "GET /csv HTTP/1.0\r\n\r\n";
但我得到的唯一回应是400 Bad request或403 Forbidden。