我有一个int网络字节顺序的IP地址,我想转换为一个InetAddress对象.我看到有一个InetAddress构造函数需要一个byte[],是否有必要将其转换int为byte[]第一个,还是有另一种方式?
小智 27
经过测试和工作:
int ip = ... ;
String ipStr =
String.format("%d.%d.%d.%d",
(ip & 0xff),
(ip >> 8 & 0xff),
(ip >> 16 & 0xff),
(ip >> 24 & 0xff));
Run Code Online (Sandbox Code Playgroud)
ska*_*man 12
这应该工作:
int ipAddress = ....
byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray();
InetAddress address = InetAddress.getByAddress(bytes);
Run Code Online (Sandbox Code Playgroud)
您可能必须交换字节数组的顺序,我无法弄清楚数组是否将以正确的顺序生成.