使用Winsock获取随机/奇怪的数据

Getting random/weird data using Winsock

本文关键字:数据 Winsock 获取 随机 使用      更新时间:2023-10-16

我刚开始使用Winsock,为了看看它能做什么,我做了一个快速的HTTP客户端(不是真的),它只是请求一个网站的索引页。但是,当尝试读取从服务器接收到的数据时,它不是我所期望的。下面是一些输出示例:

ÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌÌ̤÷

这发生在连接到我尝试的任何网站时,我从试图输出recvbuf的内容中得到这个,在那里收到的数据应该被存储。这是如何数据通常从winsock返回?而且,我不认为这是我的代码,因为我没有得到任何错误。我很确定这是正常的,我只是错过了一个步骤,但搜索没有出现任何东西,所以我在这里问。

编辑:对不起,不敢相信我忘记了我的代码:

#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include "stdafx.h"
#include <winsock2.h>
#include <windows.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <iostream>
#pragma comment(lib, "Ws2_32.lib")
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
    addrinfo *result, *ptr, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
iResult = getaddrinfo("google.com", "80", &hints, &result);
if (iResult != 0) {
    cout << "Error in getaddrinfo()!n";
    cin.get();
    return 1;
} else {
    cout << "Success!n";
}
SOCKET ConnectSocket = INVALID_SOCKET;
ptr = result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
iResult = connect(ConnectSocket, ptr->ai_addr, int(ptr->ai_addrlen));
freeaddrinfo(result);
int recvbuflen = 512;
char *sendbuf = "GET / http/1.1";
char recvbuf[512];
send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
shutdown(ConnectSocket, SD_SEND);
do {
    iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
    cout << recvbuf << endl;
} while (iResult > 0);
cin.get();
return 0;
}

您的HTTP请求错误。阅读RFC 2616。试试这个:

char *sendbuf = "GET / HTTP/1.1rnHost: google.comrnrn";

这是HTTP 1.1请求所需的最小值

由于您正在关闭套接字的发送部分,您还应该包括Connection: close标头,因为您将不会在后续请求中重用套接字:

char *sendbuf = "GET / HTTP/1.1rnHost: google.comrnConnection: closernrn";

如果你发送一个HTTP 1.0请求,你可以省略HostConnection头(Host在1.0中不使用,close是1.0的默认行为):

char *sendbuf = "GET / HTTP/1.0rnrn";

也就是说,你的读取循环太简单了,这不是HTTP响应应该被读取的方式。你需要逐行读取HTTP报头,直到你遇到一个空行,然后解析报头并读取HTTP正文的其余部分,如果有的话,基于报头告诉你如何读取(详见RFC 2616 Section 4.4)。

我对GET/http/1.1知之甚少,但谷歌使用HTTPS。

我将"google.com"替换为"web.mit.edu",然后刷新"http://web.mit.edu/"。

它确实有效