需求
android 获取本机 ip 地址
解决
public class NetworkHelper {
private static final String TAG = "NetworkHelper";
private Context context;
public NetworkHelper(Context context) {
this.context = context;
}
// 获取ip地址
@RequiresApi(api = Build.VERSION_CODES.M)
public String getLocalIpAddress() {
// ConnectivityManager netManager = (ConnectivityManager) getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
ConnectivityManager netManager = (ConnectivityManager) context.getApplicationContext().getSystemService(CONNECTIVITY_SERVICE);
// NetworkInfo info = netManager.getActiveNetworkInfo();
// // 网络是否连接
// if (info != null && info.isConnected()) {
// // wifi类型
// if (info.getType() == TYPE_WIFI) {
// return getWifiIpAddress();
// } else {
// // 其他类型
// return getEthIpAddress();
// }
// }
try {
NetworkInfo info = netManager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 3/4g网络
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
return getEthIpAddress();
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
return getWifiIpAddress(context);
} else if (info.getType() == ConnectivityManager.TYPE_ETHERNET) {
// 以太网有限网络
return getEthIpAddress(); // 局域网地址
// return getGlobalIPAddress(); // 外网地址
}
}
} catch (Exception e) {
return "";
}
return "0.0.0.0";
}
// 获取wifi的ip地址
private String getWifiIpAddress(Context context) {
// WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
// 获取32位整型IP地址
int ipAddress = wifiInfo.getIpAddress();
//返回整型地址转换成“*.*.*.*”地址
return String.format("%d.%d.%d.%d",
(ipAddress & 0xff), (ipAddress >> 8 & 0xff),
(ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
}
// 获取有线网络的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 有线网络判断
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) {
DLog.d(TAG, Log.getStackTraceString(e));
}
return ip;
}
/**
* 获取外网ip地址(非本地局域网地址)的方法
*/
public static String getGlobalIPAddress() {
String ipAddress = "";
try {
String address = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip";
URL url = new URL(address);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setUseCaches(false);
connection.setRequestMethod("GET");
connection.setRequestProperty("user-agent",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.7 Safari/537.36"); //设置浏览器ua 保证不出现503
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = connection.getInputStream();
// 将流转化为字符串
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
String tmpString;
StringBuilder retJSON = new StringBuilder();
while ((tmpString = reader.readLine()) != null) {
retJSON.append(tmpString + "\n");
}
JSONObject jsonObject = new JSONObject(retJSON.toString());
String code = jsonObject.getString("code");
Log.e(TAG, "提示:" +retJSON.toString());
if (code.equals("0")) {
JSONObject data = jsonObject.getJSONObject("data");
ipAddress = data.getString("ip")/* + "(" + data.getString("country")
+ data.getString("area") + "区"
+ data.getString("region") + data.getString("city")
+ data.getString("isp") + ")"*/;
Log.e(TAG, "您的IP地址是:" + ipAddress);
} else {
Log.e(TAG, "IP接口异常,无法获取IP地址!");
}
} else {
Log.e(TAG, "网络连接异常,无法获取IP地址!");
}
} catch (Exception e) {
Log.e(TAG, "获取IP地址时出现异常,异常信息是:" + e.toString());
}
return ipAddress;
}
}
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />