如何在android中同时获取wifi的ip和wifi热点的ip?
How to get both wifi's ip and wifi hotspot's ip in android?
我想获取wifi的IP和wifi热点的IP。
我的代码:
public static String getWifiIp(@NonNull Context context) {
WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService
(Context.WIFI_SERVICE);
if (wifimanager == null) {
return null;
}
WifiInfo wifiInfo = wifimanager.getConnectionInfo();
if (wifiInfo != null) {
return intToIp(wifiInfo.getIpAddress());
}
return null;
}
我使用此代码获取 wifi 的 IP。但是,如何同时获取 wifi 的 IP 和 wifi 热点的 IP?
尝试这个可能会有帮助。
手机ip:
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
wifi ip:
public String getWifiIPAddress() {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
return Formatter.formatIpAddress(ip);
}
清单中所需的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
用作:
String wifiIp = getWifiIPAddress();
String mobileIp = getMobileIPAddress();
我想获取wifi的IP和wifi热点的IP。
我的代码:
public static String getWifiIp(@NonNull Context context) {
WifiManager wifimanager = (WifiManager) context.getApplicationContext().getSystemService
(Context.WIFI_SERVICE);
if (wifimanager == null) {
return null;
}
WifiInfo wifiInfo = wifimanager.getConnectionInfo();
if (wifiInfo != null) {
return intToIp(wifiInfo.getIpAddress());
}
return null;
}
我使用此代码获取 wifi 的 IP。但是,如何同时获取 wifi 的 IP 和 wifi 热点的 IP?
尝试这个可能会有帮助。
手机ip:
public static String getMobileIPAddress() {
try {
List<NetworkInterface> interfaces =
Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
return addr.getHostAddress();
}
}
}
} catch (Exception ex) { } // for now eat exceptions
return "";
}
wifi ip:
public String getWifiIPAddress() {
WifiManager wifiMgr = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiMgr.getConnectionInfo();
int ip = wifiInfo.getIpAddress();
return Formatter.formatIpAddress(ip);
}
清单中所需的权限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
用作:
String wifiIp = getWifiIPAddress();
String mobileIp = getMobileIPAddress();