直接上代碼
public String getIp() {
{//獲取 Wifi IP的方法
WifiManager wifiManager = (WifiManager) this
.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()
&& wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
if (wifiInfo != null) {
int ipAddress = wifiInfo.getIpAddress();
if (ipAddress == 0)
return "";
return ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff)
+ "." + (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
}
}
}
{//獲取 以太網(wǎng)ip 的方法, 需要源碼環(huán)境編譯, 文章后面有下載地址;
ConnectivityManager connectivityManager = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
LinkProperties properties = connectivityManager
.getLinkProperties(ConnectivityManager.TYPE_ETHERNET);
if (properties != null) {
String ipString = properties.getAddresses().toString();
Pattern pattern = Pattern.compile("\\d+.\\d+.\\d+.\\d+");
Matcher matcher = pattern.matcher(ipString);
if (matcher.find()) {
return matcher.group();
}
}
}
{//獲取 3G網(wǎng)絡(luò) ip的方法
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) {
ex.printStackTrace();
}
}
return "";
}
注意: 獲取不同設(shè)備網(wǎng)絡(luò)環(huán)境的IP,請使用不同的方法, 不可通用;請使用上面對應(yīng)的獲取方法;
源碼環(huán)境下載地址--> 點擊下載class4.2
至此: 文章就結(jié)束了,如有疑問: QQ群:274306954 歡迎您的加入.