因为网管系统对ip使用的比较多,然后网上搜索发现对ip的转为的封装比较少,所以我这就对其做了下简单封装,以便日后使用,如有不对还请指出。
代码如下:
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.StringTokenizer;
public class IPClass {
/**
*将ip转为long型数字
*/
public static long ipToLong(final String ipAddress) {
int[] ipSegment = parseIp(ipAddress);
if (ipSegment == null)
return 0;
long longIp = 0;
int k = 24;
for (int i = 0; i < ipSegment.length; i++) {
longIp += ((long) ipSegment[i]) << k;
k -= 8;
}
return longIp;
}
/**
*分解ip为数组
*/
public static int[] parseIp(final String ipAddress) {
if (!checkIp(ipAddress))
return null;
int[] ipSegment = new int[4];
StringTokenizer st = new StringTokenizer(ipAddress, ".");//x相当于String.split(".")
for (int i = 0; i < 4; i++)
ipSegment[i] = Integer.parseInt(st.nextToken());
return ipSegment;
}
/**
* 检查字符是否为ip
*/
public static boolean checkIp(final String ipAddress) {
boolean isValid = true;
try {
StringTokenizer st = new StringTokenizer(ipAddress, ".");
int len = st.countTokens();
if (len != 4)
return false;
int ipSegment = 0;
for (int i = 0; i < len; i++) {
ipSegment = Integer.parseInt(st.nextToken());
if (ipSegment < 0 || ipSegment > 255) {
isValid = false;
break;
}
}
} catch (Exception e) {
return false;
}
return isValid;
}
/**
* 在制定时间内是否能ping同一个ip
*/
public boolean testPing(String ip,int timeout) throws UnknownHostException, IOException {
return InetAddress.getByName(ip).isReachable(timeout);
}
/**
*将long型数字转为ip格式
*/
public static String longToIp(final long ip) {
int b[] = new int[4];
b[0] = (int) (ip >> 24 & 255L);//
b[1] = (int) (ip >> 16 & 255L);
b[2] = (int) (ip >> 8 & 255L);
b[3] = (int) (ip & 255L);
return b[0] + "." + b[1] + "." + b[2] + "." + b[3];
}
}