使用 HTTP 1.1 很好,但是您的请求是不完整的,因为 HTTP 1.1Host
至少需要标头(以便服务器支持虚拟主机)。
更重要的是,您没有进行任何错误处理。你需要这样做。
您还没有考虑到gethostname()
可以返回多个 IP 地址。您需要访问connect()
每个地址,直到一个成功,或者直到您用完列表。
尝试这个:
char *sendbuf = "GET / HTTP/1.1\r\nHost: www.google.com.tw\r\n\r\n";
//to get the ip from DNS server
pHostEnt = gethostbyname( "www.google.com.tw"); // you should be using getaddrinfo() instead!
if (!pHostEnd)
{
printf("Unable to resolve www.google.com.tw\n");
return; // or whatever...
}
if (pHostEnt->h_addrtype != AF_INET)
{
printf("www.google.com.tw did not resolve to an IPv4 IP address\n");
return; // or whatever...
}
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET)
{
printf("Unable to create socket\n");
return; // or whatever...
}
in_addr **ppaddr = (in_addr**) pHostEnt->h_addr_list;
sockaddr_in serverAddress = {0};
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(SERVER_PORT);
bool connected = false;
int i = 0;
while (ppadd[i] != NULL)
{
// connect to server
serverAddress.sin_addr = *(ppaddr[i]);
printf("Connecting to %s\n", inet_ntoa(serverAddress.sin_addr);
if (connect(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress)) == 0)
{
connected = true;
break;
}
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
fd_set writefds;
FD_ZERO(&writefds);
FD_SET(serverSocket, &writefds);
timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
if (select(0, NULL, &writefds, NULL, &timeout) > 0)
{
connected = true;
break;
}
}
++i;
}
if (!connected)
{
printf("Unable to connect to www.google.com.tw\n");
return; // or whatever...
}
printf("Connected, sending request\n");
//send request
char *ptr = sendbuf;
int len = strlen(sendbuf);
do
{
int bytesSent = send( serverSocket, ptr, len, 0 );
if (bytesSent > 0)
{
ptr += bytesSent;
len -= bytesSent;
continue;
}
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
fd_set writefds;
FD_ZERO(&writefds);
FD_SET(serverSocket, &writefds);
timeval timeout;
timeout.tv_sec = 15;
timeout.tv_usec = 0;
if (select(0, NULL, &writefds, NULL, &timeout) > 0)
continue;
}
printf("Unable to send request\n");
return; // or whatever...
}
while (len > 0);
printf("Reading response\n");
//get response
do
{
int bytesRead = recv(serverSocket, buf, MAX_SIZE, 0);
if (bytesRead > 0)
{
// process buf as needed...
// make sure you are paying attention to the
// Content-Length and Transfer-Encoding headers,
// as they tell you how to read the response.
// Refer to RFC 2616 Section 4.4 for details...
contine;
}
if (bytesRead == 0)
{
printf("Disconnected");
return; // or whatever...
}
if (WSAGetLastError() == WSAEWOULDBLOCK)
{
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(serverSocket, &readfds);
timeval timeout;
timeout.tv_sec = 15;
timeout.tv_usec = 0;
if (select(0, &readfds, NULL, NULL, &timeout) > 0)
continue;
}
printf("Unable to read response\n");
return; // or whatever...
}
while (true);
closesocket(serverSocket);