获取wifi网关和ip

 
 
public class CheckWireLess { 
     private static WifiManager wifiManager; 
     private static DhcpInfo dhcpInfo; 
     private static WifiInfo wifiInfo; 
      
     //ip获取  
     public static String getIp(Context context){ 
       wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
       dhcpInfo = wifiManager.getDhcpInfo(); 
       wifiInfo = wifiManager.getConnectionInfo(); 
      //wifiInfo返回当前的Wi-Fi连接的动态信息  
      int ip = wifiInfo.getIpAddress(); 
      return "wifi_ip:"+FormatIP(ip); 
     } 
      
     //网关获取  
     public static String getGateWay(Context context){ 
         wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
         dhcpInfo = wifiManager.getDhcpInfo(); 
          
       //dhcpInfo获取的是最后一次成功的相关信息,包括网关、ip等  
      return "dh_ip:"+FormatIP(dhcpInfo.ipAddress)+"\n"+"dh_gateway"+FormatIP(dhcpInfo.gateway);      
     } 
      
     // IP地址转化为字符串格式  
     public static String FormatIP(int IpAddress) { 
      return Formatter.formatIpAddress(IpAddress); 
      } 
 

 

public class CheckWireLess {
   private static WifiManager wifiManager;
   private static DhcpInfo dhcpInfo;
   private static WifiInfo wifiInfo;
 
  //ip获取
     public static String getIp(Context context){
       wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
       dhcpInfo = wifiManager.getDhcpInfo();
       wifiInfo = wifiManager.getConnectionInfo();
      //wifiInfo返回当前的Wi-Fi连接的动态信息
      int ip = wifiInfo.getIpAddress();
      return "wifi_ip:"+FormatIP(ip);
     }
    
     //网关获取
     public static String getGateWay(Context context){
      wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
         dhcpInfo = wifiManager.getDhcpInfo();
        
   //dhcpInfo获取的是最后一次成功的相关信息,包括网关、ip等
      return "dh_ip:"+FormatIP(dhcpInfo.ipAddress)+"\n"+"dh_gateway"+FormatIP(dhcpInfo.gateway); 
     }
    
     // IP地址转化为字符串格式
    public static String FormatIP(int IpAddress) {
     return Formatter.formatIpAddress(IpAddress);
     }

}

所以在使用的时候要注意ip获取方式的选择,两种方式是有区别的,上述代码经过本地手机测试。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值