Android开发,获取当前手机网络地址

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"
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值