2
// 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?

Andrei Suvorkov
  • 5,559
  • 5
  • 22
  • 48
James
  • 103
  • 7
  • 1
    if `their_addr.sin_addr` is NULL or an invalid pointer, dereferencing the `s_addr` member would cause a segfault. – JGroven May 25 '18 at 20:44
  • Seeing `string` and `char[]` in the same function isn't great. If you want to use C++, `const string&` is the best argument type. When working with C APIs you'll need a lot of conversion like `c_str`, but that's at least situational. – tadman May 25 '18 at 20:45

1 Answers1

3

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*.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • There's two pointer dereferences in there, and either one could break it. A debugger would be able to pin down the problem if a temporary variable set to the first dereferenced pointer was added to the code. – tadman May 25 '18 at 20:47
  • Thank you! I thought that htonl is a function, not a macro – James May 26 '18 at 03:27