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 教师闺蜜祝福语简短