Question

I am trying to convert the IP address of any client that connect to my server to a text form as following:

    struct sockaddr_in *client_addr = NULL;
    socklen_t addrlen = sizeof(struct sockaddr_in);
    char client_ip[INET_ADDRSTRLEN];

    printf("Waiting for incomming connections!\n");
    if ((client.fd = accept(server_fd, (struct sockaddr *) client_addr, &addrlen)) < 0)
    {
        perror("Accept() API failed.");
        continue;
    }

    // Convert Client address from binary to text.
    strcpy(client_ip, inet_ntoa(client_addr->sin_addr));

When I run the previous code, I get Segmentation fault (core dumped).

I also replaced the last line witt the following, but I got the same error:

    inet_ntop(AF_INET, &(client_addr->sin_addr), client_ip, INET_ADDRSTRLEN);

So What's the problem?

Was it helpful?

Solution 2

Looks like you have to allocate space for client_addr (with malloc)

There is some code on the answer here: How to map sockaddr_in C Structure to Java using SWIG

OTHER TIPS

You have not allocated memory for client_addr. It could simply be

struct sockaddr_in client_addr

instead of

 struct sockaddr_in *client_addr = NULL;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top