import java.net.InetAddress; import java.net.UnknownHostException; public class IpV4Util { /** * å°ip转为int * * @param ip * @return intå¯è½ä¸ºè´æ° * @throws UnknownHostException */ public static int ipToInt(String ip) throws UnknownHostException { byte[] addr = ipToBytes(ip); int address = addr[3] & 0xFF; address |= ((addr[2] << 8) & 0xFF00); address |= ((addr[1] << 16) & 0xFF0000); address |= ((addr[0] << 24) & 0xFF000000); return address; } /** * å°ip转为int * * @param ip * @return xxx.xxx.xxx.xxx */ public static String intToIp(int ip) { byte[] addr = new byte[4]; addr[0] = (byte) ((ip >>> 24) & 0xFF); addr[1] = (byte) ((ip >>> 16) & 0xFF); addr[2] = (byte) ((ip >>> 8) & 0xFF); addr[3] = (byte) (ip & 0xFF); return bytesToIp(addr); } /** * å°byteæ°ç»è½¬ä¸ºipå符串 * * @param src * @return xxx.xxx.xxx.xxx */ public static String bytesToIp(byte[] src) { return (src[0] & 0xff) + "." + (src[1] & 0xff) + "." + (src[2] & 0xff) + "." + (src[3] & 0xff); } /** * å°ipå符串转为byteæ°ç»,注æ:ipä¸å¯ä»¥æ¯åå,å¦åä¼è¿è¡ååè§£æ * * @param ip * @return byte[] * @throws UnknownHostException */ public static byte[] ipToBytes(String ip) throws UnknownHostException { return InetAddress.getByName(ip).getAddress(); } }