剛好有個項目需要獲取網(wǎng)絡(luò)IP地址。由于設(shè)備可以連接wifi,也可以連接有線網(wǎng)絡(luò)。特此做個獲取IP地址的筆記,代碼如下:文章來源:http://www.zghlxwxcb.cn/news/detail-776704.html
// 獲取ip地址
private String getLocalIpAddress() {
ConnectivityManager netManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = netManager.getActiveNetworkInfo();
// 網(wǎng)絡(luò)是否連接
if (info != null && info.isConnected()) {
// wifi類型
if (info.getType() == TYPE_WIFI) {
return getWifiIpAddress();
} else {
// 其他類型
return getEthIpAddress();
}
}
return "0.0.0.0";
}
獲取WiFi的ip地址
// 獲取wifi的ip地址
private String getWifiIpAddress() {
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
// 獲取32位整型IP地址
int ipAddress = wifiInfo.getIpAddress();
//返回整型地址轉(zhuǎn)換成“*.*.*.*”地址
return String.format("%d.%d.%d.%d",
(ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
}
獲取有線網(wǎng)絡(luò)的ip4地址
// 獲取有線網(wǎng)絡(luò)的ip4地址
private String getEthIpAddress() {
String infaceName = "eth0";
String ip = "0.0.0.0";
try {
Enumeration<NetworkInterface> netInterface = NetworkInterface.getNetworkInterfaces();
while (netInterface.hasMoreElements()) {
NetworkInterface inface = netInterface.nextElement();
if (!inface.isUp()) {
continue;
}
// eth0 有線網(wǎng)絡(luò)判斷
if (!infaceName.equals(inface.getDisplayName())) {
continue;
}
Enumeration<InetAddress> netAddressList = inface.getInetAddresses();
while (netAddressList.hasMoreElements()) {
InetAddress inetAddress = netAddressList.nextElement();
// 獲取IP4地址
if (inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (Exception e) {
}
return ip;
}
如果對您有幫忙,請點贊支持。如有不合理的地方,請指正!謝謝~文章來源地址http://www.zghlxwxcb.cn/news/detail-776704.html
到了這里,關(guān)于Android 獲取IP地址(有線和無線網(wǎng)絡(luò)IP地址)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!