MySQL数据使用字符串存储IP地址
在保存IPv4地址时,一个IPv4最小需要7个字符,最大需要15个字符,所以使用VARCHAr(15)保存变长的字符串
MySQL数据库使用无符号整数存储IP地址
在保存IPv4地址时,一个IPv4使用4个字节的无符号整数来存储
MySQL数据库本身提供了相应的函数来支持字符串IPv4和数值类型的相互转换
使用INET_ATON函数将字符串格式的IP转换成整数
mysql> select inet_aton('192.168.0.1');
+--------------------------+
| inet_aton('192.168.0.1') |
+--------------------------+
| 3232235521 |
+--------------------------+
1 row in set (0.00 sec)
使用INET_NTOA将整数格式的IP转换成字符串
mysql> select inet_ntoa(3232235521); +-----------------------+ | inet_ntoa(3232235521) | +-----------------------+ | 192.168.0.1 | +-----------------------+ 1 row in set (0.00 sec)
编写C#代码实现字符串IPv4和数值类型的相互转换
public class IpUintUtils
{
///
/// 把字符串IP转换成uint
///
///
///
public static long ip2uint(String ipStr)
{
char[] chars = { '.', ' ' };
String[] ip = ipStr.Split(chars);
return (uint.Parse(ip[0]) << 24) + (uint.Parse(ip[1]) << 16)
+ (uint.Parse(ip[2]) << 8) + uint.Parse(ip[3]);
}
///
/// 把uint转换成字符串IP
///
///
///
public static String uint2Ip(uint ipUint)
{
StringBuilder ip = new StringBuilder();
ip.Append(ipUint >> 24).Append(".");
ip.Append((ipUint >> 16) & 0xFF).Append(".");
ip.Append((ipUint >> 8) & 0xFF).Append(".");
ip.Append(ipUint & 0xFF);
return ip.ToString();
}
}


