-2

我正在使用套接字编程和 C 编写一个简单的代理。

我在从网络服务器获取 HTTP 响应时遇到问题。当我运行此代码并尝试访问 cisco.com 网站时,我的程序给了我一个分段错误错误。

#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
int main()
{
    int serverSocket;
    char ip[INET_ADDRSTRLEN];
    int i;
    int j;
    serverSocket = socket(AF_INET, SOCK_STREAM, 0);
    struct sockaddr_in serverAddress ;
    char pageFilter[] = "HTTP/1.1 302 Found\n\n<html><head><title>this web page is filter !..!</title></head><body><h1>This page in filter</h1><p><h3>Please Leave This site and get out of here!</h3></p></body></html>";
    serverAddress.sin_family = AF_INET;
    serverAddress.sin_port = htons(9090);
    bind(serverSocket, (struct sockaddr *)&serverAddress, sizeof(serverAddress));
    listen(serverSocket, 20);
    while (1)
    {
        int clientSocket ;
        int size;
        struct sockaddr_in clientAddress;
        char * pch;
        char * site;
        char buffer[9000];
        size = sizeof(clientAddress);
        clientSocket = accept(serverSocket, (struct sockaddr *)&clientAddress, &size);
        recv(clientSocket, buffer, sizeof(buffer), 0);
        site = strstr(buffer, "yahoo.com");
        if(site != NULL)
        {
            send(clientSocket, pageFilter, sizeof(pageFilter) ,0);
            close(clientSocket);
        }
        else
        {
            int middleSocket;
            char buf[128];
            char response[10000];
            struct sockaddr_in  middleAddress;
            struct hostent *he;
                    struct in_addr **addr_list;
            char site[] = "cisco.com";
            middleSocket = socket(AF_INET, SOCK_STREAM, 0);
            middleAddress.sin_family = AF_INET;
            middleAddress.sin_port = htons(80);
            he =  gethostbyname(site);
                    addr_list = (struct in_addr **)he -> h_addr_list;
                    middleAddress.sin_addr.s_addr = inet_addr(inet_ntoa(*addr_list[0]));
            connect(middleSocket, (struct sockaddr *)&middleAddress, sizeof(middleAddress));
            send(middleSocket, buffer, sizeof(buffer),0);
            while((unsigned)strlen(buf) != 0)
            {
                recv(middleSocket, buf, sizeof(buf), 0);
                strcat(response,buf);
            }
            send(clientSocket, response, strlen(response),0);
            close(clientSocket);    
        }
    }
    return 0;
}
4

2 回答 2

0

首先,捕获 的返回值recv,它要么表示错误,要么表示接收到的字节数。

ssize_t n;

n = recv(middleSocket, buf, sizeof(buf) - 1);

请注意,您不应该通过sizeof(buf),因为您需要空间来保证buf.

检查错误。

if (n == -1) { /* handle error */ }
else if (n == 0) { /* handle empty response */ }

和零终止buf

buf[n] = '\0';

您的分段错误可能是因为您调用strstr了无界字符串。

于 2013-10-18T17:37:06.173 回答
0

分段错误是由无效的内存访问引起的。阅读更多:http ://en.wikipedia.org/wiki/Segmentation_fault

使用 GDB 查找发生错误时程序的确切执行位置。在此之后,您应该在代码中看到问题。

于 2014-03-06T21:27:09.600 回答