我是socketprogramming的新手,想要编写一个小的控制台应用程序来接收网页并打印出来。
这是我的代码:
#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.我正在寻找错误但是在我看来我做得对...
有人能帮助我吗?
亲切的问候,
答案 0 :(得分:0)
我的程序中没有找到connect
。在connect
之前,您可能需要recv
。
答案 1 :(得分:0)
感谢Marcus,需要在recv之前进行连接。在我做连接之前,我也发了一个小错误。改变这一切,一切正常!
感谢您的帮助。