問題小結(8)-獲取wifi網關和ip

[java]
package com.schogini.dhcp; 
 
import android.content.Context; 
import android.net.DhcpInfo; 
import android.net.wifi.WifiInfo; 
import android.net.wifi.WifiManager; 
import android.text.format.Formatter; 
 
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); 
      } 
 

package com.schogini.dhcp;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter;

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獲取方式的選擇,兩種方式是有區別的,上述代碼經過本地手機測試。
作者:agods
 

發佈留言