gethostname and gethostbyname

This is a discussion on gethostname and gethostbyname within the C Programming forums, part of the General Programming Boards category; Hi guys, I need to write a programme, when it executes, it should display the hostname and the ip address ...

  1. #1
    Registered User
    Join Date
    Jul 2007
    Posts
    9

    Smile gethostname and gethostbyname

    Hi guys,
    I need to write a programme, when it executes, it should display the hostname and the ip address of the machine it resides. I have written a code. It gives the username. But it dosent gives the correct ip address?

    Pls help me to solve this?

    Code:
    int main()
    {
        char abc[MAX_PATH];
        
        WSADATA wsaData;
        SOCKET sockfd;          
        WSAStartup(MAKEWORD(2, 0),&wsaData);   
        sockfd=socket(AF_INET,SOCK_STREAM,0);
        
        struct sockaddr_in sa;
        struct hostent *hp;
        gethostname(abc, sizeof(abc));
        puts(abc);
        
        hp = gethostbyname(abc);
        sa.sin_family = hp->h_addrtype;
        printf("\n\n%s\n\n",inet_ntoa(sa.sin_addr));
        system("pause");
    }

  2. #2
    Woof, woof! zacs7's Avatar
    Join Date
    Mar 2007
    Location
    Australia
    Posts
    3,459

  3. #3
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    You need to copy the address as well as the address type:
    Code:
        hp = gethostbyname(abc);
        sa.sin_family = hp->h_addrtype;
        memcpy(&sa.sin_addr, hp->h_addr, sizeof(sa.sin_addr));
        printf("\n\n%s\n\n",inet_ntoa(sa.sin_addr));

Popular pages Recent additions subscribe to a feed

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