如何在 Java 中以字符串形式从 IP 获取 byte[] 表示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2984601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get a byte[] representation from a IP in String form in Java
提问by Manuel Aráoz
Suppose I have the IP stored in a String:
假设我将 IP 存储在一个字符串中:
String ip = "192.168.2.1"
字符串 ip = "192.168.2.1"
and I want to get the byte array with the four ints. How can I do it? Thanks!
我想用四个整数获取字节数组。我该怎么做?谢谢!
采纳答案by Inv3r53
Something like this:
像这样的东西:
InetAddress ip = InetAddress.getByName("192.168.2.1");
byte[] bytes = ip.getAddress();
for (byte b : bytes) {
System.out.println(b & 0xFF);
}
回答by Tal Pressman
Each number is a byte, so in your case the appropriate byte[] would be { 192, 168, 2, 1 }.
每个数字都是一个字节,因此在您的情况下,适当的字节 [] 将是 { 192, 168, 2, 1 }。
To be more specific, if you have the string, you first have to split it by the "."s and then parse a byte from each resulting string.
更具体地说,如果你有字符串,你首先必须用“.”分割它,然后从每个结果字符串中解析一个字节。