我正在从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 address
:port
是: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[]);