无法在客户端中绑定到广播地址-Java/Scala [英] Can't Bind to Broadcast Address in Client -- Java/Scala

查看:69
本文介绍了无法在客户端中绑定到广播地址-Java/Scala的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个简单的UDP心跳信号,以广播到整个子网中给定端口上的所有侦听节点.

I'm trying to write a simple UDP heartbeat to broadcast to all listening nodes on a given port throughout my subnet.

我在创建/绑定客户端DatagramSocket时遇到问题.我正在尝试这样的代码:

I'm having trouble creating/binding the client DatagramSocket. I'm trying code like this:

// My IP is 192.168.201.57, so I'm using 192.168.201.255 for broadcast.  Right?
val socket = new DatagramSocket(9099, InetAddress.getByName("192.168.201.255"))

这产生了一个异常:java.net.BindException:无法分配请求的地址.

This produced an exception: java.net.BindException: Can't assign requested address.

我也尝试了255.255.255.255,结果相同. 还根据我在另一篇文章中阅读的内容尝试了类似的操作:

I've also tried 255.255.255.255 with the same result. Also tried something like this based on something I read in another post:

val socket = new DatagramSocket(null)
socket.bind( new InetSocketAddress(broadcastIp, port) )  // where I tried several broadcastIp values

这也给出了相同的例外.我还应该补充一点,我尝试了不同的端口值,并确保机器上的其他端口都没有在使用我尝试的端口.

This also gave the same exception. I should also add that I've tried different port values and made sure nothing else on the machine is using the ports I'm trying.

推荐答案

以下是我通常使用的代码:

Here is the code I usually used:

public static final String HOST_DST = "148.140.60.29";
public static final int    PORT_DST = 2416;
public static final int    PORT_SRC = 2802;

void method() {
   DatagramSocket    sock    = new DatagramSocket( PORT_SRC );
   InetSocketAddress dst     = new InetSocketAddress( HOST_DST, PORT_DST );
   ByteBuffer        message = ByteBuffer.allocate( MESSAGE_SIZE );
   for(...) {
      message.clear();
      message.putFloat( ... );
      message.putInt( ... );
      ...
      message.flip();
      sock.send( new DatagramPacket( message.array(), message.limit(), dst ));
   }
}

这篇关于无法在客户端中绑定到广播地址-Java/Scala的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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