gpt4 book ai didi

c++ - 无法使用 gethostbyname() 获取本地 IP

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:00:36 25 4
gpt4 key购买 nike

一个 friend 使用了following snippet of code检索其 LAN 中主机的本地 IP 地址。

int buffersize = 512;
char name[buffersize];

if(gethostname(name, buffersize) == -1){
Exception excep("Failed to retrieve the name of the computer");
excep.raise();
}

struct hostent *hp = gethostbyname(name);
if(hp == NULL){
Exception excep("Failed to retrieve the IP address of the local host");
excep.raise();
}

struct in_addr **addr_list = (struct in_addr **)hp->h_addr_list;
for(int i = 0; addr_list[i] != NULL; i++) {
qDebug() << QString(inet_ntoa(*addr_list[i]));
}

它似乎在他的 Mac 上运行良好。他说该数组中的最后一个 IP 地址是他需要知道的。但是,我在我的 Linux 笔记本电脑上获得了这些值...

127.0.0.2
192.168.5.1
1.2.3.0

这些看起来与我的适配器使用的值相似,但并不相同。这是一些 ifconfig 数据:

eth0      Link encap:Ethernet  HWaddr 1C:C1:DE:91:54:1A  
UP BROADCAST MULTICAST MTU:1500 Metric:1
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
wlan0 Link encap:Ethernet HWaddr [bleep]
inet addr:192.168.1.6 Bcast:192.168.1.255 Mask:255.255.255.0

似乎有些位被加扰了。我们是否错过了关键的转换?

最佳答案

您建议的方法依赖于“正确”的本地主机名和“正确”配置的 DNS 系统。我将“正确”放在引号中,因为拥有一个未在 DNS 中注册的本地主机名对于除您的程序之外的所有用途都是完全有效的。

如果您有一个已连接的套接字(或可以生成一个已连接的套接字),我建议您使用getsockname() 来查找 本地IP 地址。 (注意:不是 本地 IP 地址 -- 您可以有多个。)

这是一个执行此操作的示例程序。显然,大部分是连接到 google.com 并打印结果。只有对 getsockname() 的调用与您的问题密切相关。

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>

#include <stdio.h>
#include <errno.h>
#include <unistd.h>


int main(int ac, char **av) {
addrinfo *res;
if(getaddrinfo("google.com", "80", 0, &res)) {
fprintf(stderr, "Can't lookup google.com\n");
return 1;
}

bool connected = false;
for(; res; res=res->ai_next) {
int fd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
if(fd < 0) {
perror("socket");
continue;
}

if( connect(fd, res->ai_addr, res->ai_addrlen) ) {
perror("connect");
close(fd);
continue;
}

sockaddr_in me;
socklen_t socklen = sizeof(me);
if( getsockname(fd, (sockaddr*)&me, &socklen) ) {
perror("getsockname");
close(fd);
continue;
}

if(socklen > sizeof(me)) {
close(fd);
continue;
}

char name[64];
if(getnameinfo((sockaddr*)&me, socklen, name, sizeof name, 0, 0, NI_NUMERICHOST)) {
fprintf(stderr, "getnameinfo failed\n");
close(fd);
continue;
}
printf("%s ->", name);

if(getnameinfo(res->ai_addr, res->ai_addrlen, name, sizeof name, 0, 0, NI_NUMERICHOST)) {
fprintf(stderr, "getnameinfo failed\n");
close(fd);
continue;
}
printf("%s\n", name);
close(fd);
}
}

关于c++ - 无法使用 gethostbyname() 获取本地 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8106882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com