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 爱生日祝福语简短独特