【问题标题】:C++ http program returns 505 HTTP Version Not Supported errorC++ http 程序返回 505 HTTP Version Not Supported 错误
【发布时间】:2018-09-29 08:49:26
【问题描述】:

我正在尝试使用 Windows C++ api 获取我的系统的公共 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

【问题讨论】:

  • 很可能与您的问题无关,但不要忘记 HTTP 中的行尾是 "\r\n" 组合,不能保证 std::endl 会添加它。显式添加换行符序列,并跳过 std::endl 的使用(这里也不需要这样做)。
  • @Someprogrammerdude 我试过但现在返回 0。
  • 您是否尝试过读取 send() 函数的返回值?它可以小于你要发送的字节数,也可以等于 SOCKET_ERROR:link
  • 正如@Someprogrammerdude 所建议的,将所有std::endl 替换为"\r\n"。我试过了,它奏效了。

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


【解决方案1】:

你说

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

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

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

(注意http,没有S,而不是https。)

...应该工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多