gpt4 book ai didi

android - 如何在Android手机的wifi网络中广播

转载 作者:行者123 更新时间:2023-11-29 22:05:44 26 4
gpt4 key购买 nike

我有一个安卓手机网络,其中一部手机充当服务器。我尝试使用目标 IP 作为 '255.255.255.255.' 进行广播。但它无法发送消息。我在下面给出了 logcat。服务器 IP 为 192.168.43.1。我也尝试过使用 '192.168.43.255'。但最终也无功而返。对于代码,我引用了 http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/

05-30 20:17:40.970: E/ClientActivity(698): java.net.UnknownHostException: /192.168.43.255
05-30 20:17:40.970: E/ClientActivity(698): at java.net.InetAddress.lookupHostByName(InetAddress.java:506)
05-30 20:17:40.970: E/ClientActivity(698): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:294)
05-30 20:17:40.970: E/ClientActivity(698): at java.net.InetAddress.getByName(InetAddress.java:325)
05-30 20:17:40.970: E/ClientActivity(698): at project.android.aec.ConnectActivity$ClientThread.run(ConnectActivity.java:139)
05-30 20:17:40.970: E/ClientActivity(698): at java.lang.Thread.run(Thread.java:1019)

下面是获取广播IP的代码

   private InetAddress getBroadcastAddress() throws IOException {
mWifi= (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = mWifi.getDhcpInfo();
if (dhcp == null) {
Log.d("BCast Address Fetch", "Could not get dhcp info");
return null;
}

int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);
}

最佳答案

这是我用来获取广播地址的方法

for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (InterfaceAddress address : intf.getInterfaceAddresses()) {
System.out.println(address.getBroadcast().toString().substring(1));;
}
}

引用链接中的代码是一个简单的 TCP 服务器/客户端。如果您发布用于执行 UDP 广播的代码会更好。

关于android - 如何在Android手机的wifi网络中广播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com