Search code examples
c++htonl

Segmentation fault occurs in htonl


// something    
proxyRequest(setRequestFormat(request), respondBuffer, gethostbyname(hostname.c_str()));
// something

int proxyRequest(string request, char buffer[], struct hostent* host){
        int sockfd;
        struct sockaddr_in their_addr;
        if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){
            perror("Socket generating failed");
            return -1;
        }
        their_addr.sin_family = AF_INET;
        their_addr.sin_port = htons(SERVERPORT);
        their_addr.sin_addr.s_addr = htonl(((struct in_addr*)host->h_addr_list[0])->s_addr); // Here is where segmentation fault occurs
        if(connect(sockfd, (struct sockaddr*)&their_addr, sizeof(struct sockaddr)) == -1){
            perror("Connection failed");
            return -1;
        }
        cout << request.c_str() << endl;
        write(sockfd, request.c_str(), BUFSIZE);
        read(sockfd, buffer, BUFSIZE);
        cout << buffer << endl;
        close(sockfd);
        return 0;
    }

Hello. I'm making a basic proxy server. I'm new to Cpp socket programming, so I have had a hard time for understanding many structures related to socket programming like in_addr.

Like I said, segmentation fault occurs exactly that line. And I guess that it must be because of the syntax.

their_addr.sin_addr.s_addr = htonl(((struct in_addr*)host->h_addr_list[0])->s_addr);

It is not because of h_addr_list[0]. I already checked that it doesn't generate segmentation fault.

How can I correct this syntax?


Solution

  • htonl is too simple a macro to cause segfault. The problem happens when the arguments are computed.

    It is not because of h_addr_list[0]. I already checked that it doesn't generate segmentation fault.

    That is a good start, but it is not enough to conclude that segfault happens somewhere else. One more thing that happens after [0] is applied is that its content is cast to struct in_addr*, and then dereferenced. You must ensure that h_addr_list[0] points to a valid struct in_addr*.