我是套接字编程的新手,想编写一个小控制台应用程序来接收网页并将其打印出来。
这是我的代码:
#include <stdio.h>
#include <winsock2.h>
#include <winsock.h>
#include <Ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib" )
#define BUFFERSIZE 5000
int main()
{
WSADATA wsaData;
char buffer[BUFFERSIZE];
char *getMsg = {"GET / HTTP/1.0\nUser-Agent: HTTPTool/1.0\n\n"};
char * url = (char*)malloc(BUFFERSIZE);
int socket_fd = 0;
int receivingContent = 1;
int errorValue;
int numbytes;
struct addrinfo hints;
struct addrinfo *servinfo, *p;
socklen_t addr_size;
if (WSAStartup(MAKEWORD(2,0), &wsaData) != 0)
{
fprintf(stderr, "WSAStartup failed.\n");
exit(1);
}
memset(&hints, 0, sizeof(hints)); // empty struct
hints.ai_family = AF_UNSPEC; // IPv4 or IPv6
hints.ai_socktype = SOCK_STREAM; // using TCP
printf("Give a website like for example: www.google.com \n");
scanf("%s",url);
//Error testing
if ((errorValue = getaddrinfo(url, "80", &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(errorValue));
return 1;
}
// loop through all the results and bind to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((socket_fd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) {
perror("Failed to create socket");
continue;
}
break;
}
//sending the http get message to the server
send(socket_fd, getMsg, strlen(getMsg), 0);
//While the full content isn't downloaded keep receiving
while(receivingContent)
{
numbytes = recv(socket_fd, buffer,BUFFERSIZE , 0);
if(numbytes > 0)
{
buffer[numbytes]='\0';
printf("%s", buffer);
}
else
receivingContent = 0; //stop receiving
}
free(url);
free(getMsg);
freeaddrinfo(servinfo);
closesocket(socket_fd); //close the socket
WSACleanup();
return 0;
}
它编译,然后当我输入例如 www.google.com 时,它崩溃并给我 C 文件。我正在寻找错误,但在我看来我做得对......
有人可以帮我吗?
亲切的问候,
最佳答案
我在你的程序中没有找到connect
。您可能需要在执行 recv
之前执行 connect
。
关于c - 接收网站的简单套接字程序(断言错误),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12761214/