app实现dns解析

来源:互联网 发布:免费下载cad2008软件 编辑:程序博客网 时间:2024/05/18 15:52

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 1Returns 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.Parametershost the hostName to be resolved to an address or null.Returns    the InetAddress instance representing the host.ThrowsUnknownHostException if the address lookup fails. 
0 0
原创粉丝点击