通过URL获取IP地址 [英] Get IP-address by URL

查看:305
本文介绍了通过URL获取IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这有效

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

但是我想从网站URL中放入IP

but I want to put the IP from a website URL

我尝试过

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

在我使用gethostbyaddr()之前,我的corse做了WSAStartup

I of corse did WSAStartup before I used gethostbyaddr();

我已经尝试过了

target.sin_addr.s_addr = inet_addr(host_ip);

我也尝试了一些类似的方法,但是没有用. 有人可以告诉我如何正确执行此操作.

I've tried a few simmilar ones too but it isn't working. Could someone show me how to do this correctly.

谢谢!

当我这样做

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

它给了我

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

推荐答案

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

inet_addr() accepts an IPv4 address string as input and returns the binary representation of that address. That is not what you want in this situation, since you don't have a IP address, you have a hostname instead.

使用gethostby...()处于正确的位置,但是您需要使用gethostbyname()(按主机名查找)而不是gethostbyaddr()(按IP地址查找) 1 .而且您不能将完整的URL传递给它们中的任何一个. gethostbyname()仅接受一个主机名作为输入,因此您需要解析URL并提取其主机名,然后您可以执行以下操作:

You are on the right track by using gethostby...(), but you need to use gethostbyname() (lookup by hostname) instead of gethostbyaddr() (lookup by IP address) 1. And you cannot pass a full URL to either of them. gethostbyname() takes only a hostname as input, so you need to parse the URL and extract its hostname, and then you can do something like this:

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().

1 BTW, the gethostby...() functions are deprecated, use getaddrinfo() and getnameinfo() instead.

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

这篇关于通过URL获取IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆