Little problem with revolving and printing a host name

This is a discussion on Little problem with revolving and printing a host name within the Networking/Device Communication forums, part of the General Programming Boards category; Hello! I have a small Server (written in C language). It communicates with a Client. This Server receives some data ...

  1. #1
    Registered User
    Join Date
    Feb 2008
    Posts
    26

    Question Little problem with revolving and printing a host name

    Hello!

    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:
    Code:
    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.

    Thanks.

    I'm not an expert .

    PS: I use eclipse on Win.

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    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:

    Code:
    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
    Posts
    26

    !

    Many thanks! It works very fine...

Popular pages Recent additions subscribe to a feed

Tags for this Thread


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21