1. 获取手机卡的网络IP
//获取手机卡的网络
private fun getHostIp() : String{
var ip : InetAddress ?= null
try {
var en : Enumeration<NetworkInterface> = NetworkInterface.getNetworkInterfaces()
while(en.hasMoreElements()){
val ni : NetworkInterface = en.nextElement()
val en_ip : Enumeration<InetAddress> = ni.inetAddresses
while(en_ip.hasMoreElements()){
ip = en_ip.nextElement()
if(!ip.isLoopbackAddress && ip.hostAddress.indexOf(":") == -1)
break
else
ip = null
}
if(ip != null){
break
}
}
}catch (e : Exception){
e.printStackTrace()
}
return ip.toString()
}
2. 获取Wi-Fi局域网的IP地址
//获取局域网Wi-Fi的ip地址
@RequiresApi(Build.VERSION_CODES.O)
private fun getLocalIpAddress(context: Context) : String{
val wifiManager : WifiManager = context.getSystemService(Context.WIFI_SERVICE) as WifiManager
if(wifiManager != null){
val wifiInfo : WifiInfo = wifiManager.connectionInfo
val ipAddres : String = IntToIpv4.intToIpv4(wifiInfo.ipAddress)
return ipAddres
}
return ""
}
3. 获取Wi-Fi外网的IP地址
//获取外网IP地址(非本地局域网地址)的方法
private fun getOutNetIp() : String {
var ipAddress : String = ""
try{
val address : String = "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"
val url : URL = URL(address)
val connection : HttpURLConnection = url.openConnection() as HttpURLConnection
connection.useCaches = false
connection.requestMethod = "GET"
//设置浏览器ua 保证不出现503
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")
if(connection.responseCode == HttpURLConnection.HTTP_OK){
val inputStream : InputStream = connection.inputStream
//将流转换为字符串
val reader : BufferedReader = BufferedReader(InputStreamReader(inputStream))
var tmpString : String
val retJSON : StringBuilder = java.lang.StringBuilder()
while((reader.readLine().also { tmpString = it }) != null){
retJSON.append(tmpString+"\n")
}
val jsonObject : JSONObject = JSONObject(retJSON.toString())
val code : String =jsonObject.getString("code")
if(code.equals("0")){
val date : JSONObject = jsonObject.getJSONObject("data")
ipAddress = date.getString("ip")
/* + "(" + data.getString("country")
+ data.getString("area") + "区"
+ data.getString("region") + data.getString("city")
+ data.getString("isp") + ")"*/
}else{
Log.d("获取外网IP" ,"IP接口异常,无法获取IP地址")
}
}else{
Log.d("获取外网IP", "网络连接异常,无法获取IP地址!");
}
}catch (e : Exception){
e.printStackTrace()
Log.e("获取外网IP", "获取IP地址时出现异常,异常信息是:"+e.toString());
}
return ipAddress
}
4. 综合运用
@RequiresApi(Build.VERSION_CODES.O)
fun getIpAddress(context : Context) : String{
if (context == null){
return "0.0.0.0"
}
val conManager : ConnectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
try{
val info : NetworkInfo? = conManager.activeNetworkInfo
if(info != null && info.isConnected){
//3/4g网络
if(info.type == ConnectivityManager.TYPE_MOBILE){
return getHostIp()
}else{
//局域网
return getLocalIpAddress(context)
}
}
}catch (e : Exception){
e.printStackTrace()
}
return "0.0.0.0"
}