我一直在网上搜索我的问题的一些解决方案,但我根本无法进行255.255.255.255
广播工作。
String broadip = "255.255.255.255";
DatagramSocket socket= new DatagramSocket(PORT);
InetAddress address = InetAddress.getByName(broadip);
socket.setReuseAddress(true);
socket.setBroadcast(true);
InetSocketAddress sAddress = new InetSocketAddress(broadip, PORT);
socket.bind(sAddress);
int length = this.buffer.length;
DatagramPacket packet = new DatagramPacket(this.buffer, length,address,PORT);
socket.send(packet);
socket.close();
当它到达socket.bind(sAddress)
行时,会抛出异常“无法绑定”。我也尝试“跳过”这个绑定行,套接字发送数据包,但其他机器永远不会收到这个数据包。
奇怪的是,下面的代码工作正常,但只将数据包发送到192.168.25.8
,而我需要广播:
String broadip = "192.168.25.8";
DatagramSocket socket= new DatagramSocket(PORT);
InetAddress address = InetAddress.getByName(broadip);
socket.setReuseAddress(true);
socket.setBroadcast(true);
int length = this.buffer.length;
DatagramPacket packet = new DatagramPacket(this.buffer, length,address,PORT);
socket.send(packet);
socket.close();
有Android清单权限:
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
任何人都可以提供帮助吗?