質問

In a C program in UNIX, gethostbyname() can be used to obtain the address of domain like "localhost". How does one convert the result from gethostbyname() to dotted decimal notation.

struct hostent* pHostInfo;
long nHostAddress;

/* get IP address from name */
pHostInfo=gethostbyname("localhost");

if(!pHostInfo){
    printf("Could not resolve host name\n");
    return 0;
}

/* copy address into long */
memset(&nHostAddress, 0, sizeof(nHostAddress));
memcpy(&nHostAddress,pHostInfo->h_addr,pHostInfo->h_length);

nHostAddress contains the following:

16777243

How do I convert the result so that I can get the output as :

127.0.0.1
役に立ちましたか?

解決

You can convert from a struct in_addr directly to a string using inet_ntoa():

char *address = inet_ntoa(pHostInfo->h_addr);

The value you've got (16777243) looks wrong, though -- that comes out to 1.0.0.27!

他のヒント

It is easy Just Compile This Code

#include<stdio.h>
#include<netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
    struct hostent *ghbn=gethostbyname("www.kamonesium.in");//change the domain name
    if (ghbn) {
        printf("Host Name->%s\n", ghbn->h_name);
        printf("IP ADDRESS->%s\n",inet_ntoa(*(struct in_addr *)ghbn->h_name) );
    }
}

The inet_ntoa() API does what you're looking for, but is apparently deprecated:

https://beej.us/guide/bgnet/html/multi/inet_ntoaman.html

If you want something more future-proof-IPV6ish, there's inet_ntop():

https://beej.us/guide/bgnet/html/multi/inet_ntopman.html

The variable "h_name" in the last statement needs to change as "h_addr" shown in follows:

printf("IP ADDRESS->%s\n",inet_ntoa(*(struct in_addr *)ghbn->h_addr) );

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top