Rai*_*Son 8 java android udp broadcast android-networking
我正在为我的Android手机制作一个Client Server应用程序.
我创建了一个UDP服务器,Python其中坐着并侦听连接.
我可以IP直接放置服务器地址192.169.0.100,它可以很好地发送数据.我也可以放入192.168.0.255并找到服务器192.169.0.100.
是否可以获取我的Android手机所连接的网络的广播地址?我只会在我的Wifi网络或其他Wifi网络上使用此应用程序.
干杯
Sof*_*LLC 15
从
private InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
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));
return InetAddress.getByAddress(quads);
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处就是只看WIFI.我知道OP说"我只会在我的Wifi网络或其他Wifi网络上使用这个应用程序." 但值得一提的是,如果其他人需要非wifi替代品.
这是一个应该工作的方法:
public static String getBroadcast(){
String found_bcast_address=null;
System.setProperty("java.net.preferIPv4Stack", "true");
try
{
Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces();
while (niEnum.hasMoreElements())
{
NetworkInterface ni = niEnum.nextElement();
if(!ni.isLoopback()){
for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses())
{
found_bcast_address = interfaceAddress.getBroadcast().toString();
found_bcast_address = found_bcast_address.substring(1);
}
}
}
}
catch (SocketException e)
{
e.printStackTrace();
}
return found_bcast_address;
}
Run Code Online (Sandbox Code Playgroud)
Cri*_*ian -2
由于广播 IP 地址是当前 IP 地址,但以 255 结尾,因此您可以执行以下操作:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15600 次 |
| 最近记录: |