????????做为程序员,就一定会接触到ip地址的概念。它是用于标识网络设备的唯一标识。在Java开发项目中,经常涉及到ip地址与long型或者int型数据之间的转换。
????????ipv4地址主要由4点分十进制表示,每个部分的范围是0~255。例如 192.168.111.6
public class utils { public static void main(String[] args) { ??????????? String ipv4Str = "192.168.1.14"; ????????long ipl = ipv4ToLong(ipv4Str); ????????System.out.println("ip转long:"+ipl); ???????? String ips = longToIpv4(ipl); ????????System.out.println("long转ip:"+ips); } /** * ipv4 的IP地址转为长整型数字 * @param ipv4Str * @return */ public static long ipv4ToLong(String ipv4Str){ String[] temp = ipv4Str.split("\\."); long iplong = (Long.valueOf(temp[0])<< 24) + (Long.valueOf(temp[1])<< 16) + (Long.valueOf(temp[2])<< 8)+ Long.valueOf(temp[3]); return iplong; } /** * 长整型数字转为ip地址(ipv4) * @param ipv4Long * @return */ public static String longToIpv4(long ipv4Long){ StringBuilder sb = new StringBuilder(); sb.append(ipv4Long >>> 24).append(".") .append((ipv4Long>>>16)&0xFF).append(".") .append((ipv4Long>>>8)&0xFF).append(".") .append(ipv4Long&0xFF); return sb.toString(); } }
????????ip转long:3232235790
????????long转ip:192.168.1.14