繁体   English   中英

如何通过 java.net InetAddress 或其他 API 知道 ip 地址

[英]How to know ip address with java.net InetAddress or other API

我有 UDP 服务器来监听消息,我需要绑定到设备 IP 地址。 其他设备在 UDP 服务器上发送消息。 我使用下一个:

InetAddress address = InetAddress.getLocalHost();  // gives 127.0.1.1 (1)
address = InetAddress.getLoopbackAddress(); // 127.0.0.1              (2)
address = InetAddress.getByName("123.45.67.89"); // the same          (3)
address = InetAddress.getByName("localhost");  //                     (4)

我在不同的环境中运行我的代码,然后看下一个:在我的本地机器上,win10.getByName("localhost") 有效,.getLocalHost() 无效。 其他设备(模拟器)也在“localhost”上发送消息。

在其他带有 Win7 和一些 IP 的远程 PC 上,我正在使用 (1) 并且它可以工作。 物理设备在服务器 IP 上发送消息并对其进行处理。 另外,我正在使用桥接器来允许设备相互通信,即放置在不同网络中的设备(我不明白这个配置,这不是我的)。

在这台远程 PC 上,但在 Linux 中,我只能手动设置地址,即变体 (3)。 但我需要自动指定它。

我无法通过任何方法获得正确的服务器地址。 如何获取设备地址? 也许还有其他方法或 API?

UPD:我正在使用标准配置的 netty udp 服务器:

@Override
public void run() {
    final NioEventLoopGroup group = new NioEventLoopGroup();
    try {
        log.info("Started listening logs ...");
        final Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioDatagramChannel.class)
                .option(ChannelOption.SO_BROADCAST, true)
                .handler(new ChannelInitializer<NioDatagramChannel>() {
                    @Override
                    public void initChannel(final NioDatagramChannel nioDatagramChannel) {
                        ChannelPipeline channelPipeline = nioDatagramChannel.pipeline();
                        channelPipeline.addLast(encryptedPacketHandlerChain);
                    }
                });

        // Bind and start to accept incoming connections.
        InetAddress address = InetAddress.getLocalHost();
        System.out.println("InetAddress..getLocalHost() == " + address.getHostAddress());
        address = InetAddress.getLoopbackAddress();
        System.out.println("InetAddress.getLoopbackAddress == " + address.getHostAddress());
        address = InetAddress.getByName(ip);
        System.out.println("InetAddress.getByName " + ip + " == " + address.getHostAddress());

        bootstrap.bind(address, LOG_PORT).sync().channel().closeFuture().await();

    } catch (Exception e) {......

一个主机可能有几个网络接口连接到不同的网络,绑定地址告诉系统你想监听哪个接口。 这通常由应用程序的用户(系统管理员)配置,因为网络有不同的用途(例如,数据平面与控制计划:系统和网络管理员使用一个网络来控制机器,另一个网络用于生产流量)

如果你不知道应该监听哪个接口,你可以监听所有本地接口。 您可以通过绑定到特殊的0.0.0.0 或:: IP 地址来做到这一点。

创建 0.0.0.0 地址的一种方法是首先使用 InetSocketAddress(int port) 构造函数创建一个SocketAddress ,然后从中检索地址:

InetAddress anyAddress = new InetSocketAddress(LOG_PORT).getAddress();

另一种方法是直接创建地址:

InetAddress anyAddress = InetAddress.getByAddress(new byte[4]);

暂无
暂无

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

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