我正在尝试编写一个类似于telnet的短程序,作为客户端使用。我从用户那里接收输入,例如:www.google.com 80(端口号)和/index.html。然而,我遇到了一些错误。当我写一些调试信息时,它会显示我有一个坏的文件描述符,并且在文件描述符100上读取失败,消息大小为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);
}
感谢!