samedi 29 septembre 2018

C++ http program returns 505 HTTP Version Not Supported error

I'm trying to get public ip address of my sysetm using windows C++ api. But, I got following response:

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

My Code:

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();

Please help me. Thanks in advance.

Note: My request link:

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

Aucun commentaire:

Enregistrer un commentaire