ip地址存入数据库使用什么类型

56 阅读1分钟

使用的数据类型

类型数据类型
IPv4无符号int
IPv6varbinary

好处

相对字符串存储,使用无符号整数来存储有如下的好处:

  • 节省空间,不管是数据存储空间,还是索引存储空间
  • 便于使用范围查询(BETWEEN...AND),且效率更高

直接使用sql函数存储及查询

// 插入IPv4
insert into ip_address (ipv4_address) values (inet_aton('127.0.0.1'));

// 查询IPv4地址
select (inet_ntoa(ipv4_address)) ipv4_address from ip_address

// 插入IPv6
insert into ip_address (ipv6_address) values (inet_aton('2001:db8:85a3::8a2e:370:7334'));

// 查询IPv6地址
select (inet6_ntoa(ipv6_address)) ipv6_address from ip_address

java代码转换字符串IPv4和数值类型

/**
 * 把字符串IP转换成long
 *
 * @param ipStr 字符串IP
 * @return IP对应的long值
 */
public static long ip2Long(String ipStr) { 
    String[] ip = ipStr.split("\\."); 
    return (Long.valueOf(ip[0]) << 24) 
    + (Long.valueOf(ip[1]) << 16) 
    + (Long.valueOf(ip[2]) << 8) 
    + Long.valueOf(ip[3]); 
}

/**
 * 把IP的long值转换成字符串
 *
 * @param ipLong IP的long值
 * @return long值对应的字符串
 */
public static String long2Ip(long ipLong) {
    StringBuilder ip = new StringBuilder();
    ip.append(ipLong >>> 24).append(".");
    ip.append((ipLong >>> 16) & 0xFF).append(".");
    ip.append((ipLong >>> 8) & 0xFF).append(".");
    ip.append(ipLong & 0xFF);
    return ip.toString();
}