So, I’m trying to play around with sockets, but my read() call keeps hanging. I’m connecting to a random web page (e.g. yahoo.com) on port 80. My output is showing that I’m writing 5 bytes, but I’m not getting anything in return. Can anyone point out what I’m doing wrong?
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);
Your HTTP protocol is not complete enough. Use this…
You must specify the “GET” and filename, the HTTP version, the Hostname, and two new lines to indicate the header is done. The server expects you to complete the header before it starts sending anything. This is why your call to read() is stalling. Take a look at the Client Request example on the HTTP article on Wikipedia.