app实现dns解析

apk上层做了个类似dns解析的小功能,主要分为两步:

  • 1.判断当前网络是否通畅

涉及下面两个类
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

      boolean isNetworkAvailable(Context context) {  
            ConnectivityManager connectivity = (ConnectivityManager) context  
                    .getSystemService(Context.CONNECTIVITY_SERVICE);  
            if (connectivity != null) {  
                NetworkInfo info = connectivity.getActiveNetworkInfo();  
                if (info != null && info.isConnected())   
                {   
                    if (info.getState() == NetworkInfo.State.CONNECTED)   
                    {     
                        return true;  
                    }  
                }  
            }  
            return false;  
        }  
  • 2.解析域名

涉及下面类
import java.net.InetAddress;

    InetAddress address = InetAddress.getByName("www.baidu.com");
    //下面的hostaddress 既是类似180.97.33.108这样的点分形式
    String HostAddress = address.getHostAddress();      

下面是InetAddress.getByName的api文档,使用时需要注意输入和捕获异常,此外android也规定网络连接等耗时的操作需要另起一个线程,不能在主线程运行。

public static InetAddress getByName (String host)
Added in API level 1

Returns the address of a host according to the given host string name host. The host string may be either a machine name or a dotted string IP address. If the latter, the hostName field is determined upon demand. host can be null which means that an address of the loopback interface is returned.
Parameters
host the hostName to be resolved to an address or null.
Returns

    the InetAddress instance representing the host.

Throws
UnknownHostException if the address lookup fails. 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值