将字符串转换为const char然后构造hostent的问题

时间:2015-10-09 16:48:45

标签: c++ winsock

我有这个代码可以创建一个http-webrequest,但我不知道如何向主机const添加一个url,因为每次我用代码执行此操作时都会显示此错误:

  

附加信息:对象引用未设置为的实例   对象

以下是代码:

// originally posted to http://i.stack.imgur.com/hH1BG.png

#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
void connect(string url)
{
  //Adding for the host
  const char *curl = url.c_str();
  WSADATA wsaData;
  //original code
  if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
    cout << "WSAStartup failed.\n";
    system("pause");

  }
  SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  struct hostent *host;
  host = gethostbyname(curl);
  SOCKADDR_IN SockAddr;
  SockAddr.sin_port = htons(80);
  SockAddr.sin_family = AF_INET;
  SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
  cout << "Connecting...\n";
  if (connect(Socket, (SOCKADDR*)(&SockAddr), sizeof(SockAddr)) != 0){
    cout << "Could not connect";
    system("pause");

  }
  cout << "Connected.\n";
  send(Socket, "GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.google.com\r\nConnection close\r\n\r\n"), 0);
  char buffer[10000];
  int nDataLength;
  while ((nDataLength = recv(Socket, buffer, 10000, 0)) > 0){
    int i = 0;
    while (buffer[i] > 32 || buffer[i] == '\n' || buffer[i] == '\r') {
      cout << buffer[i];
      i += 1;
    }
  }
  closesocket(Socket);
  WSACleanup();
  system("pause");

}

1 个答案:

答案 0 :(得分:1)

问题是您盲目地假设gethostbyname的返回值不是NULL,在尝试使用{{1}之前,您应该检查主机名查找是否成功}。

  

如果没有错误发生,gethostbyname会将指针返回到上述的hostent结构。否则,它返回空指针,并且可以通过调用host->h_addr来检索特定的错误号。

     

SRC; msdn.microsoft.com - gethostbyname function (windows)

建议修复

WSAGetLastError