我正在尝试开发一个系统,其中有不同的节点在不同的系统或同一系统的不同端口上运行。
现在,所有节点都会创建一个Socket,其中目标IP是称为引导节点的特殊节点的IP。然后,节点创建自己的ServerSocket
并开始侦听连接。
引导节点维护节点列表,并在查询时返回它们。
现在我需要的是,节点必须向引导节点注册其IP。我尝试使用cli.getInetAddress()
一旦客户端连接到引导节点的ServerSocket
,但那行不通。
- 如果PPP IP可用,则需要客户端注册其PPP IP;
- 否则,如果可用,则需要注册LAN IP;
- 否则,假定注册127.0.0.1表示它与相同计算机。
使用的代码:
System.out.println(Inet4Address.getLocalHost().getHostAddress());
或者System.out.println(InetAddress.getLocalHost().getHostAddress());
我的PPP连接IP地址是:117.204.44.192,但是上面的代码返回给我192.168.1.2。
编辑
我正在使用以下代码:
Enumeration e = NetworkInterface.getNetworkInterfaces();
while(e.hasMoreElements())
{
NetworkInterface n = (NetworkInterface) e.nextElement();
Enumeration ee = n.getInetAddresses();
while (ee.hasMoreElements())
{
InetAddress i = (InetAddress) ee.nextElement();
System.out.println(i.getHostAddress());
}
}
我能够获取所有与NetworkInterface
相关联的IP地址,但如何区分它们?这是我得到的输出:
127.0.0.1
192.168.1.2
192.168.56.1
117.204.44.19