簡體   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