【问题标题】:Get IP-address by URL通过 URL 获取 IP 地址
【发布时间】:2020-06-10 06:11:14
【问题描述】:

这行得通

target.sin_addr.s_addr = inet_addr("127.0.0.1");

但我想从网站 URL 中输入 IP

我试过了

const char host[] = "http://www.google.com/";
struct hostent *host_ip;
host_ip = gethostbyaddr(host, strlen(host), 0);

我在使用 gethostbyaddr(); 之前做了 WSAStartup;

我试过了

target.sin_addr.s_addr = inet_addr(host_ip);

我也尝试了一些类似的方法,但它不起作用。 有人可以告诉我如何正确地做到这一点。

谢谢!

编辑:

当我这样做时

host_ip = gethostbyaddr((char *)&host, strlen(host), 0);
std::cout << host_ip->h_addr;

它给了我

httpa104-116-116-112.deploy.static.akamaitechnologies.com

【问题讨论】:

  • 将您的完整代码缩减为minimal reproducible example,并将其发布在您的问题中。因为它在 Stack Overflow 上是无用且离题的。
  • 我用谷歌搜索了“nslookup 源代码”,并被发送到 (opensource.apple.com/source/bind9/bind9-44/bind9/bin/dig/…)。可能其他来源更好,我不知道。谷歌是你的朋友。 ;-)
  • 这里是完整的代码,如果你想看的话pastebin.com/H4kvbfpy
  • 网上有 很多 的资源。 “当然”你已经尝试过它们,“但它不起作用”。没有必要在这里重复它们。
  • 当我做 host_ip = gethostbyaddr((char *)&host, strlen(host), 0); std::cout h_addr;它给了我 httpa104-116-116-112.deploy.static.akamaitechnologies.com

标签: c sockets tcp network-programming


【解决方案1】:

inet_addr() 接受 IPv4 地址字符串作为输入并返回该地址的二进制表示。在这种情况下,这不是您想要的,因为您没有 IP 地址,而是有一个主机名。

使用gethostby...() 是正确的,但您需要使用gethostbyname()(按主机名查找)而不是gethostbyaddr()(按IP 地址查找)1。而且您不能将完整的 URL 传递给其中任何一个。 gethostbyname() 只接受一个主机名作为输入,所以你需要解析 URL 并提取它的主机名,然后你可以这样做:

const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself
target.sin_addr.s_addr = inet_addr(host);
if (target.sin_addr.s_addr == INADDR_NONE)
{
    struct hostent *phost = gethostbyname(host);
    if ((phost) && (phost->h_addrtype == AF_INET))
        target.sin_addr = *(in_addr*)(phost->h_addr);
    ...
}
else
    ...

1 顺便说一句,gethostby...() 函数已弃用,请改用 getaddrinfo()getnameinfo()

const char host[] = ...; // an IP address or a hostname, like "www.google.com" by itself

addrinfo hints = {0};
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;

addrinfo *addr = NULL;

int ret = getaddrinfo(host, NULL, &hints, &addr);
if (ret == EAI_NONAME) // not an IP, retry as a hostname
{
    hints.ai_flags = 0;
    ret = getaddrinfo(host, NULL, &hints, &addr);
}
if (ret == 0)
{
    target = *(sockaddr_in*)(addr->ai_addr);
    freeaddrinfo(addr);
    ...
}
else
    ...

【讨论】:

    【解决方案2】:

    尝试使用 getaddrinfo。这里有一个使用它的快速指南:http://beej.us/guide/bgnet/output/html/multipage/getaddrinfoman.html

    【讨论】:

      猜你喜欢
      • 2018-01-02
      • 2011-10-18
      • 2015-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-21
      相关资源
      最近更新 更多