Java如何将原始IP地址转换为String?
本示例说明如何将方法调用byte返回的原始IP地址(数组)转换InetAddress.getAddress()为其字符串表示形式。
package org.nhooo.example.network;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class RawIPToString {
public static void main(String[] args) {
byte[] ip = new byte[0];
try {
InetAddress address = InetAddress.getLocalHost();
ip = address.getAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
String ipAddress = RawIPToString.getIpAddress(ip);
System.out.println("IP Address = " + ipAddress);
try {
InetAddress address = InetAddress.getByName("google.com");
ip = address.getAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
ipAddress = RawIPToString.getIpAddress(ip);
System.out.println("IP Address = " + ipAddress);
}
/**
* Convert raw IP address to string.
*
* @param rawBytes raw IP address.
* @return a string representation of the raw ip address.
*/
private static String getIpAddress(byte[] rawBytes) {
int i = 4;
StringBuilder ipAddress = new StringBuilder();
for (byte raw : rawBytes) {
ipAddress.append(raw & 0xFF);
if (--i > 0) {
ipAddress.append(".");
}
}
return ipAddress.toString();
}
}此示例将打印如下内容:
IP Address = 182.0.135.67 IP Address = 209.85.132.104
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短