我使用它来连接到Wi-Fi时获取内部IP:
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipv4intAddress = wifiInfo.getIpAddress();
tempView = (TextView) findViewById(R.id.textViewIPv4Int2);
tempView.setText(myNetworkOperations.iptoDecimal(ipv4intAddress));
在移动设备或其他类型的连接上有没有类似的简单方法来获取IP?
答案 0 :(得分:1)
您可以尝试使用以下代码:
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 "ERROR Obtaining IP";
}
return "No IP Available";