时间:2021-07-01 10:21:17 帮助过:2人阅读
BIGINT -9223372036854775808到9223372036854775807
所以mysql里面要存储ip的话,字段的类型要设置成BIGINT
接下来就是如何把一个ip转化成一个整型从而存储到mysql中,以及如何从mysql取到一个整型,转化成一个字符串类型。
1 public class IPUtils { 2 public static Long getIPNum(final String IP) { 3 Long IPNum = 0l; 4 final String IPStr = IP.trim(); 5 if (IP != null && IPStr.length() != 0) { 6 final String[] subips = IPStr.split("\\."); 7 for (final String str : subips) { 8 // 向左移8位 9 IPNum = IPNum << 8; 10 IPNum += Integer.parseInt(str); 11 } 12 } 13 return IPNum; 14 } 15 16 public static String getIPString(final Long IPNum) { 17 final Long andNumbers[] = { 0xff000000L, 0x00ff0000L, 0x0000ff00L, 0x000000ffL }; 18 final StringBuilder IPStrSb = new StringBuilder(); 19 for (int i = 0; i < 4; i++) { 20 IPStrSb.append(String.valueOf((IPNum & andNumbers[i]) >> 8 * (3 - i))); 21 if (i != 3) { 22 IPStrSb.append("."); 23 } 24 } 25 return IPStrSb.toString(); 26 } 27 28 public static void main(final String[] args) { 29 final String IPStr = "192.185.11.11"; 30 System.out.println(getIPNum(IPStr)); 31 32 final Long IPNum = 3233352459L; 33 System.out.println(getIPString(IPNum)); 34 } 35 36 }
IP使用整数存储到数据库
标签: