1
我需要知道,因为当我发送广播数据包时,我无法检查它是否来自我自己。我的代码问题是Android在桌面上工作正常。对于android它不断给我一个IPV6,但它给我的广播地址是正常的...如何从设备获取默认IP地址?
我需要知道,因为当我发送广播数据包时,我无法检查它是否来自我自己。我的代码问题是Android在桌面上工作正常。对于android它不断给我一个IPV6,但它给我的广播地址是正常的...如何从设备获取默认IP地址?
此功能将返回主机的IP地址。
private String getHostIpAddress() throws SocketException {
Enumeration<NetworkInterface> interfaces;
interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface current = interfaces.nextElement();
if (!current.isUp() || current.isLoopback() || current.isVirtual())
continue;
Enumeration<InetAddress> addresses = current.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress currentAddr = addresses.nextElement();
if (currentAddr.isSiteLocalAddress())
return currentAddr.getHostAddress();
}
}
return null;
}
您可以使用下面的代码用于获取设备的IP地址:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());