你可以嘗試將字符串轉換成IP整數,然後構建由包含IP地址字節InetAddress對象。這裏的代碼
InetAddress inet = intToInetAddress(ipStringToInt("192.168.0.102"));
public static int ipStringToInt(String str) {
int result = 0;
String[] array = str.split("\\.");
if (array.length != 4) return 0;
try {
result = Integer.parseInt(array[3]);
result = (result << 8) + Integer.parseInt(array[2]);
result = (result << 8) + Integer.parseInt(array[1]);
result = (result << 8) + Integer.parseInt(array[0]);
} catch (NumberFormatException e) {
return 0;
}
return result;
}
public static InetAddress intToInetAddress(int hostAddress) {
InetAddress inetAddress;
byte[] addressBytes = { (byte)(0xff & hostAddress),
(byte)(0xff & (hostAddress >> 8)),
(byte)(0xff & (hostAddress >> 16)),
(byte)(0xff & (hostAddress >> 24)) };
try {
inetAddress = InetAddress.getByAddress(addressBytes);
} catch(UnknownHostException e) {
return null;
}
return inetAddress;
}