C语言通过socket接受一个网页的子页信息啊????求大佬

#include
#include
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSADATA data;
//winsock版本2.2
int err = WSAStartup(MAKEWORD(2, 2), &data);
if (err)
return;

//用域名获取对方主机名
char host[] = "www.dianping.com";
struct hostent* h = gethostbyname(host);
if (h == NULL)
    return;

////IPV4
//if (h->h_addrtype != AF_INET)
//  return;
struct in_addr ina;
//解析IP
memmove(&ina, h->h_addr, 4);
LPSTR ipstr = inet_ntoa(ina);
//Socket封装
struct sockaddr_in si;
si.sin_family = AF_INET;
si.sin_port = htons(80);
//ipstr = (LPSTR)"120.78.150.62:80/wuqi/index.html";
si.sin_addr.S_un.S_addr = inet_addr(ipstr);
int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
connect(sock, (SOCKADDR*)& si, sizeof(si));
if (sock == -1 || sock == -2)
    return;

//发送请求
//char host[] = "120.78.150.62:80/wuqi/index.html";
char request[1024] = "GET /?st=1 HTTP/1.1\r\nHost:";
strcat_s(request, host);
strcat_s(request, "\r\nConnection:Close\r\n\r\n");
int ret = send(sock, request, strlen(request), 0);
//printf("%s\n",request);
//获取网页内容
FILE * f = fopen("recieved.txt","w");

int isstart = 0;
while (ret > 0)
{
    const int bufsize = 1024;
    char* buf = (char*)calloc(bufsize, 1);
    ret = recv(sock, buf, bufsize - 1, 0);
    fprintf(f, "%s", buf);
    free(buf);
}
fclose(f);
closesocket(sock);
WSACleanup();
printf("读取网页内容成功,已保存在recieved.txt中");
printf("3秒后自动关闭");
Sleep(3000);
return;

}
就输入子页的域名地址就不知道为什么访问不了了!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

c++

1个回答

C语言如果在windows上,读取网页不需要那么复杂,直接用URLDownloadToFile 这个api函数就可以了
https://baike.baidu.com/item/URLDownloadToFile

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问