wifi获取网关ip的方法
wifi获取网关ip是比较简单的,可以通过获取DhcpInfo来获取网关ip,而DhcpInfo可以通过Wifimanager来获取。
/**
* wifi获取 路由ip地址
*
* @param context
* @return
*/
private static String getWifiRouteIPAddress(Context context) {
WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
// WifiInfo wifiinfo = wifi_service.getConnectionInfo();
// System.out.println("Wifi info----->" + wifiinfo.getIpAddress());
// System.out.println("DHCP info gateway----->" + Formatter.formatIpAddress(dhcpInfo.gateway));
// System.out.println("DHCP info netmask----->" + Formatter.formatIpAddress(dhcpInfo.netmask));
//DhcpInfo中的ipAddress是一个int型的变量,通过Formatter将其转化为字符串IP地址
String routeIp = Formatter.formatIpAddress(dhcpInfo.gateway);
Log.d(TAG, "wifi route ip:" + routeIp);
return routeIp;
}
以太网获取网关ip
网上给的很多获取网关ip的方式,比如:EthernetManager和EthernetDevInfo来获取,具体的我在这里就不说了,因为默认sdk是没有提供的,引包会出问题。
这里换个角度给一种获取的方式:
1) 首先,我们通过命令执行来获取网关信息:ip route show
2) 执行命令之后获取到信息输出后,在匹配出网关ip就可以了。
直接给出获取方式:
/**
* 以太网获取路由id地址
*
* @return
*/
private static String getEthernetRouteIpAddress() {
String ip = "";
try {
Process p = Runtime.getRuntime().exec("ip route show");
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
String ipHave = "";
String line = null;
//获取到的可能包含ip的信息如下:
// default via 192.168.2.1 dev eth0
// default via 192.168.2.1 dev eth0 metric 206
// 192.168.2.0/24 dev eth0 scope link
// 192.168.2.0/24 dev eth0 proto kernel scope link src 192.168.2.21 metric 206
// 192.168.2.0 dev eth0 scope link
while ((line = in.readLine()) != null
&& !line.equals("null")) {
if (line.contains("default via ")) {
ipHave += line;
break;
}
}
if (!"".equals(ipHave)) {
//获取网关ip信息
String patternS = "default via (\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}) dev eth0 ";
Pattern p1 = Pattern.compile(patternS);
Matcher matcher = p1.matcher(ipHave);
if (matcher.matches())
ip = matcher.group(1);
Log.d(TAG, "ethernet route ip:" + ip);
return ip;//拿到ip则返回了
}
} catch (IOException e) {
e.printStackTrace();
}
return ip;
}