读取 /proc/net/tcp 并从字符串中获取 IP 地址



我正在从filereader读取proc/net/tcp文件并从regex解析数据以获取所需的内容。

proc/net/tcp 中的示例字符串是:

0: 0401A8C0:D366 FFB79E23:01BB 01 00000000:00000000 00:00000000 00000000 11269 0 14392479 1 00000000 30 4 30 10 -1

所以local addressport是:0401A8C0:D366,我尝试通过该方法将十六进制转换为字符串,但它没有返回有效数据....有人可以帮助如何读取数据吗?

它应该给出类似的东西:192.168.*.* .

要解析 ip 地址应该从这个0401A8C0小端字符串中获取字节数组,但无法解决

The Hex to String method :

public String fromHex(String hex) throws UnsupportedEncodingException {
    hex = hex.replaceAll("^(00)+", "");
    byte[] bytes = new byte[hex.length() / 2];
    for (int i = 0; i < hex.length(); i += 2) {
        bytes[i / 2] = (byte) ((Character.digit(hex.charAt(i), 16) << 4) + Character.digit(hex.charAt(i + 1), 16));
    }
    return new String(bytes);
}

我已经通过将字符串:0401A8C0转换为字节数组来解决它:

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}

并通过以下方式获取IP地址:

InetAddress addresses = InetAddresses.fromLittleEndianByteArray(byte[]);

最新更新