简体   繁体   English

将struct in_addr转换为文本

[英]convert struct in_addr to text

只是想知道我是否有一个结构in_addr,如何将其转换回主机名?

You can use getnameinfo() by wrapping your struct in_addr in a struct sockaddr_in : 您可以通过将struct in_addr包装在struct sockaddr_in来使用getnameinfo()

int get_host(struct in_addr addr, char *host, size_t hostlen)
{
    struct sockaddr_in sa = { .sin_family = AF_INET, .sin_addr = my_in_addr };

    return getnameinfo(&sa, sizeof sa, host, hostlen, 0, 0, 0);
}

Modern code should not use struct in_addr directly, but rather sockaddr_in . 现代代码不应该直接使用struct in_addr ,而应该使用sockaddr_in Even better would be to never directly create or access any kind of sockaddr structures at all, and do everything through the getaddrinfo and getnameinfo library calls. 更好的方法是永远不要直接创建或访问任何类型的sockaddr结构,并通过getaddrinfogetnameinfo库调用来完成所有工作。 For example, to lookup a hostname or text-form ip address: 例如,要查找主机名或文本格式的ip地址:

struct addrinfo *ai;
if (getaddrinfo("8.8.8.8", 0, 0, &ai)) < 0) goto error;

And to get the name (or text-form ip address if it does not reverse-resolve) of an address: 并获取地址的名称(或文本形式的IP地址,如果它不反向解析):

if (getnameinfo(ai.ai_addr, ai.ai_addrlen, buf, sizeof buf, 0, 0, 0) < 0) goto error;

The only other time I can think of when you might need any sockaddr type structures is when using getpeername or getsockname on a socket, or recvfrom . 我可以想到你可能需要任何sockaddr类型结构的唯一另一个时间是在套接字上使用getpeernamegetsockname ,或者recvfrom Here you should use sockaddr_storage unless you know the address family a priori. 除非您事先了解地址族,否则应使用sockaddr_storage

I give this advice for 3 reasons: 我提出这个建议有三个原因:

  1. It's a lot easier doing all of your string-to-address-and-back conversion with these two functions than writing all the cases (to handle lookup failures and trying to parse the address as an ip, etc.) separately. 使用这两个函数进行所有字符串到地址和后向转换要比分别编写所有情况(处理查找失败并尝试将地址解析为ip等)容易得多。
  2. Coding this way makes it trivial to support IPv6 (and potentially other non-IPv4) protocols. 以这种方式编码使得支持IPv6(以及可能的其他非IPv4)协议变得微不足道。
  3. The old functions gethostbyname and gethostbyaddr were actually removed from the latest version of POSIX because they were considered so obsolete/deprecated/broken. 旧函数gethostbynamegethostbyaddr实际上已从最新版本的POSIX中删除,因为它们被认为是过时/弃用/损坏的。

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

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