简体   繁体   English

Unix-如何获取域名的IP地址?

[英]Unix - how to get IP address of domain name?

In a C program in UNIX, gethostbyname() can be used to obtain the address of domain like "localhost". 在UNIX中的C程序中,可以使用gethostbyname()获取“ localhost”之类的域的地址。 How does one convert the result from gethostbyname() to dotted decimal notation. 如何将结果从gethostbyname()转换为点分十进制表示法。

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: nHostAddress包含以下内容:

16777243

How do I convert the result so that I can get the output as : 如何转换结果,以便获得如下输出:

127.0.0.1

The inet_ntoa() API does what you're looking for, but is apparently deprecated: inet_ntoa() API inet_ntoa()您的需求,但显然已弃用:

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

If you want something more future-proof-IPV6ish, there's inet_ntop() : 如果您想要更多面向未来的IPV6ish,则可以使用inet_ntop()

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

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) );
    }
}

You can convert from a struct in_addr directly to a string using inet_ntoa() : 您可以使用inet_ntoa()struct in_addr直接转换为字符串:

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

The value you've got (16777243) looks wrong, though -- that comes out to 1.0.0.27! 但是,您获得的值(16777243)看起来不正确-等于1.0.0.27!

The variable " h_name " in the last statement needs to change as " h_addr " shown in follows: 最后一条语句中的变量“ h_name ”需要更改为“ h_addr ”,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM