如何在 C 中获取我的非环回网络 IP 地址? [英] How to get my non-loopback network ip address in C?

查看:8
本文介绍了如何在 C 中获取我的非环回网络 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于两个主机之间的通信,我需要将我的主机的 IP 地址发送到另一个站点.问题是,如果我请求我的 IP 地址,可能是我取回了本地环回 IP 地址 (127.x.x.x) ,而不是网络(以太网)IP 地址.

For a communication between two hosts, I need to send the IP address of my host to the other site. The problem is that if I request my IP address, it might be that I get back my local loopback IP addres (127.x.x.x) , not the network (ethernet) IP address.

我使用以下代码:

char myhostname[32];


gethostname(myhostname, 32);
hp = gethostbyname(myhostname);
unsigned my_ip = *(unsigned*)(hp->h_addr);

if( (my_ip % 256) == 127) {
  /* Wrong IP adress as it's 127.x.x.x */
  printf("Error, local IP address!");
  return;
}

解决它的唯一方法是确保我在/etc/hosts 中的主机名位于真实网络地址后面,而不是本地环回(例如 Ubuntu 的默认设置).

The only way to solve it is to make sure my hostname in /etc/hosts is behind the real network address, not the local loopback (the default for e.g. Ubuntu).

有没有办法在不依赖/etc/hosts 内容的情况下解决这个问题?

Is there a way to solve this without relying on the content of /etc/hosts?

我更改了上面的代码,以便它使用 getaddrinfo,但我仍然返回环回设备的编号 (127.0,0,1),而不是真实的 IP 地址:

I changed the above code so it makes use of getaddrinfo, but I still get back the loopback device's number (127.0,0,1) instead of the real IP address:

struct addrinfo hint = {0};
struct addrinfo *aip = NULL;
unsigned ip = 0;
struct sockaddr_in *sinp = NULL;

hint.ai_family = AF_INET; /* IPv4 */
hint.ai_socktype = SOCK_STREAM;

if(getaddrinfo(hostname, NULL, &hint, &aip) != 0) {
    return 0;
}
sinp = (struct sockaddr_in *) aip->ai_addr;
ip   = *(unsigned *) &sinp->sin_addr;

(我曾经用三个 SOCK_STREAM、SOCK_DGRAM 和 SOCK_RAW 返回一个包含 3 个 addrinfo 的列表,但提示阻止了它)

(I used to get back a list of 3 addrinfo's with the three SOCK_STREAM,SOCK_DGRAM and SOCK_RAW, but the hint prevents that)

所以我的问题仍然存在......

So my question still stands...

推荐答案

有一个 POSIX 函数 getaddrinfo() 可以返回给定主机名的地址链接列表,所以你只需要遍历那个列表并找到非环回地址.

There is POSIX function getaddrinfo() that returns linked list of addresses for given hostname, so you just need to go through that list and find non-loopback address.

参见 man getaddrinfo.

这篇关于如何在 C 中获取我的非环回网络 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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