简体   繁体   English

如何从struct addrinfo获取我自己的IP地址

[英]How to get my own IP address from a struct addrinfo

I am binding a socket to my address to listen to connections. 我将套接字绑定到我的地址以侦听连接。 To do this, I get my address information using getaddrinfo() syscall, which grants me an ip independent way of doing what I want. 为此,我使用getaddrinfo() syscall获取地址信息,这为我提供了一种独立于ip的方式来执行我想要的事情。 The problem is that the structs which this syscall returns have the ip address field all blank. 问题是此系统调用返回的结构的ip地址字段全部为空。 For example: 例如:

struct addrinfo hints, *servinfo, *p;
int sock;

memset(&hints, 0, sizeof(struct addrinfo));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;

getaddrinfo(NULL, port, &hints, &servinfo)

for (p = servinfo; p != NULL; p = p->ai_next)
   if (p->ai_family == AF_INET6)
      break;

sock = socket(p->ai_family, p->sock_type, p->protocol);
bind(sock, p->ai_addr, p->ai_addrlen)

In the code above. 在上面的代码中。 the *p variable should have some kind of information on an IPv6 address of my machine since the bind succeeds, but the field p->ai_addr->sin6_addr (assume this would work without a casting) is blank. 由于绑定成功,因此*p变量应该在我的机器的IPv6地址上具有某种信息,但是字段p->ai_addr->sin6_addr (假设这无需转换就可以工作)为空。 How can I know exactly what address I will be using? 我如何确切知道我将使用什么地址?

The address is not blank - it is all zeroes, which is 0::0 . 地址不为空-全为零,即0::0 This is the special wildcard address which means to bind to all local interfaces. 这是特殊的通配符地址,表示绑定到所有本地接口。

You should not care what address(es) your host has - this list might change at any time, including immediately after you check it. 你不应该关心什么地址(ES)主机有-这个清单可能随时更改,你检查后立即包括。

Once you have a client connected, you can use getsockname() on the socket returned by accept() to determine which one of your local addresses that client connected to. 一旦连接了客户端,就可以在getsockname()返回的套接字上使用getsockname() accept()来确定该客户端连接到了哪个本地地址。

Why don't you bind to localhost (ie IPV4 127.0.0.1 ) or to ip6-localhost (ie IPV6 ::1 ) if you want to listen to local connections only? 如果只想听本地连接,为什么不绑定到localhost (即IPV4 127.0.0.1 )或ip6-localhost (即IPV6 ::1 )?

Otherwise, leave all zeroes in the address like @caf suggested. 否则,将所有零都保留在建议的@caf之类的地址中。

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

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