【发布时间】:2020-10-28 20:53:43
【问题描述】:
我有 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 的远程 PC 和我正在使用的一些 IP (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 会发生什么?这可能意味着bind to all available interfaces
-
@Joni 工作意味着我绑定到 ip 并获取消息,不工作意味着我绑定到 IP 并且不接收消息,即服务器在另一台主机上侦听(其他设备在正确的端口主机和服务器上发送必须绑定到它)。
标签: java udp ip-address inetaddress