美文网首页
Android 获取IP信息

Android 获取IP信息

作者: sssssss_ | 来源:发表于2022-06-16 16:00 被阅读0次

获取连接热点的IP信息

private ArrayList getConnectIp() {
    ArrayList connectIpList = new ArrayList();
    try {
        Runtime runtime = Runtime.getRuntime();
        Process proc = runtime.exec("ip neigh show");
        proc.waitFor();
        BufferedReader br = new BufferedReader(new InputStreamReader(proc.getInputStream()));
        //BufferedReader br = new BufferedReader(new FileReader("/proc/net/arp"));
        String line;
        while ((line = br.readLine()) != null) {
            String[] splitted = line.split(" +");
            if (splitted != null && splitted.length >= 4) {
                String ip = splitted[0];
                connectIpList.add(ip);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return connectIpList;
}

运行结果

image.png

获取当前连接的WIFI的网关

public String getWifiIp() {
    if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.M) {
        return null;
    }
    WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(this.WIFI_SERVICE);
    if (!wifiManager.isWifiEnabled()) {
        return null;
    }
    if (!wifiManager.isWifiEnabled()) {
        wifiManager.setWifiEnabled(true);
    }
    DhcpInfo dhcpinfo = wifiManager.getDhcpInfo();
    String serverAddress = getCorrectIPAddress(dhcpinfo.serverAddress);
    return serverAddress;
}
/**
 * 将获取的int转为真正的ip地址
 **/
private String getCorrectIPAddress(int iPAddress) {
    StringBuilder sb = new StringBuilder();
    sb.append(iPAddress & 0xFF).append(".");
    sb.append((iPAddress >> 8) & 0xFF).append(".");
    sb.append((iPAddress >> 16) & 0xFF).append(".");
    sb.append((iPAddress >> 24) & 0xFF);
    return sb.toString();
}

相关文章

网友评论

      本文标题:Android 获取IP信息

      本文链接:https://www.haomeiwen.com/subject/gojqvrtx.html