我需要知道,因为当我发送广播包时,我无法检查它是否来自我自己。我的代码问题是Android,它在桌面上工作正常。对于Android它一直给我一个IPV6但它给我的广播地址是正常的......
答案 0 :(得分:1)
此函数将返回主机的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;
}
答案 1 :(得分:0)
您可以使用以下代码获取设备的IP地址:
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());