所以,我正在尝试使用套接字,但我的read()
调用一直挂着。我正在连接到端口80上的随机网页(例如yahoo.com)。我的输出显示我正在写5个字节,但我没有得到任何回报。谁能指出我做错了什么?
portno = 80;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {printf("could not open socket\n");}
server = gethostbyname("yahoo.com");
if (server == NULL)
{
printf("could not get hostbyname\n");
exit(0);
}
printf("Server name:%s\n",server->h_name);
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
printf("connect error\n");
}
char buffer[1000];
strcpy(buffer,"GET \\");
printf("bytes in command:%d\n",sizeof(buffer));
n = write(sockfd,buffer,strlen(buffer));
if(n <= 0){printf("could not get page:\n");}
printf("Bytes that where writen:%d\n", n);
printf("reading from socket\n");
n = read(sockfd,buffer,sizeof(buffer));
printf("bytes that where read:%d",n);
答案 0 :(得分:4)
您的HTTP协议不够完整。使用这个......
strcpy(buffer,"GET / HTTP/1.1\r\nHostname:www.yahoo.com\r\n\r\n");
您必须指定“GET”和文件名,HTTP版本,主机名和两个新行以指示标头已完成。服务器希望您在开始发送任何内容之前完成标头。这就是你对read()的调用停滞的原因。请查看Wikipedia上HTTP文章中的Client Request example。