我正在尝试向网站的根文档发送HEAD请求。这是我的代码:
main(int argc, char *argv[])
{
int csd;
struct sockaddr_in server;
struct hostent *server_host;
int server_len;
int string_size;
short server_port;
char req_buffer[BUF_LEN];
char temp_buffer[BUF_LEN];
char receiveBuffer[BUF_LEN];
char resource_buffer[BUF_LEN];
int t;
if(argc!=2)
{
fprintf(stderr,"Usage: %s website \n",argv[0]);
exit(EXIT_FAILURE);
}
server_host=gethostbyname(argv[1]); //resolve hostname
if (server_host == NULL)
{
herror("While calling gethostbyname()");
exit(EXIT_FAILURE);
}
csd=socket(PF_INET, SOCK_STREAM, 0); //create socket
if(csd<0)
{
perror("While calling socket()");
exit(EXIT_FAILURE);
}
server.sin_family=AF_INET;
memcpy(&server.sin_addr, server_host->h_addr_list[0], server_host->h_length);
server.sin_port = htons(80);
server_len=sizeof(server);
t = connect(csd, (struct sockaddr *) &server, server_len);
if (t<0)
{
perror("while connecting()");
exit(EXIT_FAILURE);
}
else
{
printf("connected to server\n\n");
}
printf("input resource, with format'/(resource name)'\n"); //request for resource (for example /index.html)
scanf("%s", temp_buffer);
printf("retreiving HEAD...\n\n");
sprintf(temp_buffer, "HEAD %s HTTP/1.0\r\n", resource_buffer);
strcpy(req_buffer, temp_buffer);
sprintf(temp_buffer, "HOST: %s\r\n", server_host);
strcat(req_buffer, temp_buffer);
sprintf(temp_buffer, "\r\n");
strcat(req_buffer, temp_buffer);
write(csd, req_buffer, strlen(req_buffer));
read(csd, receiveBuffer, BUF_LEN);
printf(receiveBuffer);
}
到目前为止,我还没有成功,我只是得到了不好的要求。我使用网站测试:man7.org/linux/man-pages/index.html和man7.org/mtk/index.html
答案 0 :(得分:1)
首先,您使用的是HTTP 1.0上不存在的host
标头,您需要使用1.1。还要添加connection: close
以确保不使用keepalive。
主要问题很可能是您在主机标头中使用server_host
。它不是字符串,它是一个结构体,因此它会将垃圾输出到您的请求中。
简单的调试会话或只输出您发出的请求会显示此错误。