C - Print connecting clients address

  • Thread starter Thread starter James889
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
4 replies · 3K views
James889
Messages
190
Reaction score
1
Hi,

I'm currently trying to implement a simple client server program in C.

Needless to say i ran into troubles, and being a novice, i turned here for some advice.

I have a function to print the connecting peers address. I don't even know if this is the right way of doing it.

For some reason this function dumps core.

Code:
char * print_peer(struct addrinfo *client) {

        if(client == NULL)
         exit();

        void *ptr = malloc(INET_ADDRSTRLEN);
        struct addrinfo *p = client;
        for (; p != NULL; p = p->ai_next) {

                if(p->ai_family == AF_INET){
                 inet_ntop(AF_INET,&(p->ai_addr),ptr,INET_ADDRSTRLEN);
                 break;
                }

        }
        return ptr;
}
 
Physics news on Phys.org
Unless defined in some include file, ptr is an unitialized variable. correction - ptr was initialized, I'm not sure what the problem is.
 
Last edited:
rcgldr said:
Unless defined in some include file, ptr is an unitialized variable.

To be fair he did initialize the variable with the malloc statement (but for some reason it's a void and not a char pointer).

For the OP though, you should always check all your pointers for bad values and make sure you always initialize them to 0 (i.e. NULL) whenever you create a structure (you can over-ride your malloc statement to do this for all allocated memory so you don't have to do this every-time you call malloc).

I recommend doing this and then printing debug statements to the console, a file, or standard output in case of an error.
 
James889 said:
Code:
                 inet_ntop(AF_INET,&(p->ai_addr),ptr,INET_ADDRSTRLEN);
I'm wondering about &(p->ai_addr). If ai_addr is a pointer, then the call is passing a pointer to p->ai_addr instead of the content of p->ai_addr.
 
Last edited: