代理服务器程序中的分段错误

时间:2015-10-09 14:11:34

标签: c sockets

我正在尝试在c中创建一个简单的代理服务器。我已使用此url parser来解析来自客户端的http请求。它返回一个指向此结构的指针:

struct parsed_url {
    char *scheme;               /* mandatory */
    char *host;                 /* mandatory */
    char *port;                 /* optional */
    char *path;                 /* optional */
    char *query;                /* optional */
    char *fragment;             /* optional */
    char *username;             /* optional */
    char *password;             /* optional */
};

在解析来自客户端的http请求后打印主机名时,它会显示正确的结果,例如" www.google.com"。但是当我将此主机名传递给gethostbyname()时,它会给我分段错误。我不明白为什么会发生这种情况。 这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include "url_parser.h"
int main(int argc,char *argv[])
{
    struct sockaddr_in server,client;
    struct hostent *host;
    int s1,s2,s3,len;
    int port;
    char ip[100];
    char path[100];
    int p;
    struct parsed_url *url = NULL;
    int n;
    char buffer[500];
    char site[500];
    port = atoi(argv[1]);

    bzero((char *)&server,sizeof(server));
    server.sin_port = htons(port);
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_family = AF_INET;
    s1 = socket(AF_INET,SOCK_STREAM,0);

    if(bind(s1,(struct sockaddr *)&server,sizeof(server)) == -1) {
        perror("can't bind");
        exit(1);
    }

    if(listen(s1,10) == -1) {
        perror("coudnt't listen");
        exit(1);
    }
    len = sizeof(client);
    s2 = accept(s1,(struct sockaddr *)&client,&len);
    if(s2 == -1) {
        perror("coudnt aceept");
        exit(1);
    }
    memset(buffer,0,sizeof(buffer));
    n = recv(s2,buffer,500,0);
    if(n < 0) {
        perror("not recieved");
        exit(1);
    }
    buffer[n] = '\0';

    url = parse_url(buffer);
    bzero((char *)&client,sizeof(client));
    client.sin_port = htons(80);
    printf("%s %d",url->host,strlen(url->host));
    host = gethostbyname((char *)url->host);
    if(!host) {
        herror("host error");
    }
    bcopy((char *)host->h_addr,(char *)&client.sin_addr.s_addr,host->h_length);
    client.sin_family = AF_INET;
    s3 = socket(AF_INET,SOCK_STREAM,0);


    if(connect(s3,(struct sockaddr *)&client,sizeof(client)) == -1) {
        perror("can't connect\n");
        exit(1);
    }
    sprintf(site,"GET http://%s/ HTTP/1.0\n\n",url->host);
    n = send(s3,site,strlen(site),0);
    if(n < 0) {
        perror("message not sent");
        exit(1);
    }
    while(1) {
        memset(site,0,sizeof(site));
        n = recv(s3,site,500,0);
        if(n < 0) {
            perror("coudnot read");
            exit(1);
        }
        //site[n] = '\0';
        send(s2,site,strlen(site),0);
    }
    close(s1);
    close(s2);
    return 0;
}

url_parser使用this进行解析。

0 个答案:

没有答案