Android获取路由ip

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;
    }
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值