Android广播地址
我正在为我的 Android
手机制作客户端服务器应用程序.
I am making a Client Server application for my Android
phone.
我在 Python
中创建了一个 UDP
服务器,用于监听连接.
I have created a UDP
Server in Python
which sits and listens for connections.
我可以像 192.169.0.100
一样直接输入服务器 IP
地址,它可以正常发送数据.我也可以输入 192.168.0.255
并在 192.169.0.100
上找到服务器.
I can put either the server IP
address in directly like 192.169.0.100
and it sends data fine. I can also put in 192.168.0.255
and it find the server on 192.169.0.100
.
是否可以获取我的 Android 手机所连接网络的广播地址?我只会在我的 Wifi
网络或其他 Wifi
网络上使用此应用程序.
Is it possible to get the broadcast address of the network my Android phone is connected to? I am only ever going to use this application on my Wifi
network or other Wifi
networks.
干杯
推荐答案
由于广播IP地址是当前IP地址但以255结尾,你可以这样做:
As the broadcast IP address is the current IP address but finishing with 255, you can do something like this:
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {}
return null;
}
public static String getBroadcast() throws SocketException {
System.setProperty("java.net.preferIPv4Stack", "true");
for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements();) {
NetworkInterface ni = niEnum.nextElement();
if (!ni.isLoopback()) {
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
return interfaceAddress.getBroadcast().toString().substring(1);
}
}
}
return null;
}
相关文章