1

我正在编写一个简单的 HTTP 客户端程序,它应该可以工作,但是当我发送 GET 消息时,服务器没有响应,过了一会儿我得到 504 网关超时,因此建立了连接。这是代码:

int main(int argc, char *argv[]){

int sockfd = 0, n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr; 
struct sockaddr_in my_addr;  
struct hostent *host;
char *msg=malloc(1024*sizeof(char));
socklen_t addrsize = sizeof(struct sockaddr_in );

memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
    printf("\n Error : Could not create socket \n");
    return 1;
} 


memset(&serv_addr, '0', sizeof(serv_addr)); 
serv_addr.sin_family = AF_INET;
if(argc==4)serv_addr.sin_port = htons(atoi(argv[3])); 
else serv_addr.sin_port = htons(80); 
host=gethostbyname(argv[1]);
bcopy(host->h_addr,&(serv_addr.sin_addr.s_addr),host->h_length);


if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
   printf("\n Error : Connect Failed. %s \n", strerror(errno));
   return 1;
} 

sprintf(msg,"GET %s HTTP/1.0\r\nHost: %s\r\nConnection: close\r\n\r\n",argv[2],argv[1]);
printf("Sending:\n%s",msg);
write(sockfd,msg,sizeof(msg));
printf("Recieved:\n");
while ( (n = read(sockfd, recvBuff, sizeof(recvBuff)-1)) > 0)
{
    recvBuff[n] = 0;
    if(fputs(recvBuff, stdout) == EOF)
    {
        printf("\n Error : Fputs error\n");
    }
} 

if(n < 0)
{
    perror("\n Read error \n");
} 

close(sockfd);

}
4

0 回答 0