c - 通过 URL 获取 IP 地址

标签 c sockets tcp network-programming

这有效

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

最佳答案

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

关于c - 通过 URL 获取 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32639539/

相关文章:

sockets - C++ - 如何从 struct sockaddr 获取 IP 和端口

java - 使用具有特定 IP 地址的打印机在 Android 中进行打印

linux - 已连接套接字上的 read() 函数能否返回零字节?

c# - 与经典 TCP 套接字通信

java - Sockets编程中SOCKS、DIRECT和HTTP的区别

objective-c - 使用 GCDAyncSocket 将任意信息与套接字相关联

自定义 shell 仅采用一个参数

c++ - native 使用程序集引用

c - 在 LGPL/GPL 许可下是否有面向堆栈的编程语言的解释器?

c - 释放 malloc 指针时出错