Thread: Little problem with revolving and printing a host name

  1. #1
    Registered User
    Join Date
    Feb 2008

    Question Little problem with revolving and printing a host name


    I have a small Server (written in C language). It communicates with a Client.
    This Server receives some data from the Client with the recvefrom().
    In this case my recvfrom() is:
    if ((recvMsgSize = recvfrom(sock, echoBuffer, BUFMAX, 0,
                (struct sockaddr *) &echoClntAddr, &cliAddrLen)) < 0)
                printError("\nrecvfrom() failed.");
    It works well.

    I know my Client address (network byte order) is stored in echoClntAddr. I'd like to have some help in converting this address in its corresponding host name and print it.


    I'm not an expert .

    PS: I use eclipse on Win.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    segmentation fault
    echoClntAddr is cast here as a struct sockaddr. Presuming it is really a struct sockaddr_in, it has a member sin_addr which is actually a struct in_addr. The actual network order byte address (on my system) is an unint32_t called s_addr in sin_addr. You can cast this as a const char* and use gethostbyaddr. This returns a struct hostent whose member h_name is the proper hostname:

    struct hostent *info=malloc(sizeof(struct hostent));
    if ((info=gethostbyaddr((const char*)&echoClntAddr.sin_addr.s_addr,4,AF_NET))==NULL)
         printf("gethostbyaddr errno: &#37;d\n",h_errno);
    else puts(info->h_name);
    And it works!
    Last edited by MK27; 11-27-2008 at 01:09 PM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Feb 2008


    Many thanks! It works very fine...

Popular pages Recent additions subscribe to a feed

Tags for this Thread