HTTP代理服务器C开发

时间:2012-10-31 16:27:35

标签: c http proxy

我需要构建一个处理GET方法的HTTP代理服务器 我能够建立从客户端(web brownser)到Proxy Server的连接,Proxy正在向服务器发送重新格式化的头并检索响应。 但是代理没有收到整个数据。

我的代码如下:

main(int argc,char **argv)
 {
//Server binds to particular port
//Waiting for connection");
for(;;)
{
     //Connect to client
    handle_connection(connfd,&cli_addr);
    close(connfd);

}
}
void handle_connection(int connfd, struct sockaddr_in *cli_addr)
{
struct sockaddr_in host_addr;
char buffer[BUFFSIZE];
int rfd,n;
char** http_args;
url* requested_url;
struct hostent *hp;

bzero(buffer, BUFFSIZE);

if ((rfd = read(connfd,buffer,BUFFSIZE)) < 0 ) {
    perror("Error reading from socket.");
    return;
}
buffer[rfd]='\0';

split_line( (char*)buffer, (char**)http_args,2);
requested_url = parse_request(http_args[1]);

//Printing
    printf("\nCommand: %s\n", http_args[0]);
    printf("Url: %s\n", http_args[1]);
    printf("proto: %d\n",requested_url->proto);
    printf("port: %d\n",requested_url->port);
    printf("host: %s\n",requested_url->host);
    printf("File: %s\n",requested_url->file);


if((strcmp(http_args[0],"GET"))!=0)
{
printf("here");
http_error_messages(connfd, http_args[0], 501, "Not Implemented","Proxy does not implement this method");
return;
}

//Connection to request made to server on rfd 
sprintf(buffer, "%s %s HTTP/1.%d\r\nHost: %s:80\r\n\r\n"
        , http_args[0], requested_url->file, requested_url->proto, requested_url->host);
printf("In the Server %s",buffer);
//printf("In the Server %s",get_header);
n = write(rfd,buffer,sizeof(buffer));
shutdown(rfd,2);

char buff[MAXLINE];
while((n = read(rfd, buff, MAXLINE)) > 0) {
    write(connfd, buff, MAXLINE);
    printf("%s",buff);
    }
    if(n<0)
    {
    perror("Error in reading");
    }
    shutdown(rfd,1);
    shutdown(connfd,2);

close(rfd); 

 }

1 个答案:

答案 0 :(得分:1)

在TCP套接字上,您需要重复调​​用read(),直到读取预期的终止字符(\n?),或者已读取所需的字节数。

read()可以返回部分数据或不返回数据,具体取决于TCP数据包的分段/缓冲/混乱方式。