C ++ http程序返回505 HTTP版本不支持错误

时间:2018-09-29 08:49:26

标签: c++ http c++11 visual-c++ https

我正在尝试使用Windows C ++ API获取我的sysetm的公共IP地址。但是,我得到了以下回应:

HTTP/1.1 505 HTTP Version Not Supported
Connection: close
Server: Cowboy
Date: Sat, 29 Sep 2018 08:46:51 GMT
Content-Length: 0

我的代码:

std::stringstream request2;
std::string hostName = "api.ipify.org";
std::string path = "/?format=text";

request2 << "GET " << path <<" HTTP/1.1" << std::endl;
request2 << "Host: " << hostName << std::endl;

request2 << std::endl;
std::string request1 = request2.str();

//init winsock
if (WSAStartup(MAKEWORD(2, 0), &wsaData) != 0)
{
    exit(1);
}

//open socket
if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
    exit(1);
}

struct hostent  *he;
memset(&serveraddr, 0, sizeof(serveraddr));

const char *hostname = hostName.c_str();
if ((he = gethostbyname(hostname)) == NULL)
{
    WriteLogFile("Host not found");
    exit(1);
}

/* copy the network address to sockaddr_in structure */
memcpy(&serveraddr.sin_addr, he->h_addr_list[0], he->h_length);
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(PORT);

if ((connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr))) < 0)
{
    exit(1);
}

//send request
if (send(sock, request1.c_str(), request1.length(), 0) != request1.length())
{
    exit(1);
}

//get response
response = "";
resLen = BUFFERSIZE;
while (resLen == BUFFERSIZE)
{
    resLen = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
    if (resLen>0) {
        response += std::string(buffer).substr(0, resLen);
    }
}

IpAddress = response;

//disconnect
closesocket(sock);

//cleanup
WSACleanup();

请帮助我。预先感谢。

注意:我的请求链接:

https://api.ipify.org/?format=text

1 个答案:

答案 0 :(得分:0)

您说

  

注意:我的请求链接:   https://api.ipify.org/?format=text

但是无法使用这样的普通套接字连接到 https 服务器。您需要像OpenSSL这样的东西。但是,如果将链接更改为

http://api.ipify.org/?format=text

(请注意, http ,不带 S ,而不是 https 。)

... 应该有效。