我正在尝试编写一个像 telnet 这样的客户端的短程序。
我从用户那里收到这样的输入:www.google.com 80(端口号)和/index.html
但是,我遇到了一些错误。当我写一些调试信息时,它说我有一个错误的文件描述符和文件描述符 100 messagesize = 0 上的读取失败。

struct hostent * pHostInfo;
struct sockaddr_in Address;
long nHostAddress;
char pBuffer[BUFFER_SIZE];
unsigned nReadAmount;
int nHostPort = atoi(port);

vector<char *> headerLines;
char buffer[MAX_MSG_SZ];
char contentType[MAX_MSG_SZ];

int hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

if (hSocket == SOCKET_ERROR)
{
  cout << "\nCould Not Make a Socket!\n" << endl;
  return 1;
}
pHostInfo = gethostbyname(strHostName);
memcpy(&nHostAddress,pHostInfo -> h_addr, pHostInfo -> h_length);

Address.sin_addr.s_addr = nHostAddress;
Address.sin_port=htons(nHostPort);
Address.sin_family = AF_INET;

if (connect(hSocket, (struct sockaddr *)&Address, sizeof(Address)) == SOCKET_ERROR)
{
  cout << "Could not connect to the host!" << endl;
  exit(1);
}
char get[] = "GET ";
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);
strcpy(pBuffer, get);
int len = strlen(pBuffer);
send(hSocket, pBuffer, len, 0);
nReadAmount = recv(hSocket,pBuffer, BUFFER_SIZE, 0);
//Parsing of data here, then close socket
if (close(hSocket) == SOCKET_ERROR)
{
  cout << "Could not close the socket!" << endl;
  exit(1);
}

谢谢!

最佳答案

你的代码中有一个 buffer overrun 。您试图将一堆字符数组一起分配到一个只有 5 个字节长的缓冲区中:

char get[] = "GET ";  // 'get' is 5 bytes long
char http[] = " HTTP/1.0\r\nHost: ";
char end[] = "\r\n\r\n";
strcat(get, URI);  // BOOM!
strcat(get, http);
strcat(get, strHostName);
strcat(get, end);

这可能会覆盖您的局部变量 hSocket ,从而导致“错误的文件描述符错误”。

由于您使用的是 C++(您的代码中有 vector),因此只需使用 std::string 而不是 C 字符数组,这样您就不必担心内存管理。

关于c++ - 为什么我收到错误的文件描述符错误?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7406290/

10-11 22:59
查看更多