Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C - Print connecting clients address

  1. Jun 9, 2012 #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 (Text):
     
    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;
    }
     
     
  2. jcsd
  3. Jun 9, 2012 #2

    rcgldr

    User Avatar
    Homework Helper

    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: Jun 10, 2012
  4. Jun 9, 2012 #3

    chiro

    User Avatar
    Science Advisor

    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.
     
  5. Jun 10, 2012 #4

    rcgldr

    User Avatar
    Homework Helper

    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: Jun 10, 2012
  6. Jun 10, 2012 #5

    chiro

    User Avatar
    Science Advisor

Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: C - Print connecting clients address
Loading...