C - Print connecting clients address

  • Thread starter James889
  • Start date
  • #1
192
1

Main Question or Discussion Point

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;
}
 

Answers and Replies

  • #2
rcgldr
Homework Helper
8,701
530
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:
  • #3
chiro
Science Advisor
4,790
132
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.
 
  • #4
rcgldr
Homework Helper
8,701
530
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:
  • #5
chiro
Science Advisor
4,790
132

Related Threads on C - Print connecting clients address

  • Last Post
Replies
1
Views
1K
  • Last Post
Replies
2
Views
2K
Replies
25
Views
19K
Replies
1
Views
1K
Replies
2
Views
2K
Replies
9
Views
1K
Replies
2
Views
2K
  • Last Post
Replies
4
Views
1K
Replies
10
Views
1K
  • Last Post
Replies
2
Views
2K
Top