2011-11-26 71 views
-1

所以,我試圖玩插座,但我的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); 
+3

嘗試'strcpy(buffer,「GET/\ r \ n \ r \ n」)'開始...... – pilcrow

回答

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