[MSSQL] Хранение ip в базе
От: Smilless Россия  
Дата: 09.10.10 09:02
Оценка:
Собственно сабж, решил погуглить, для интереса

Нашел такой код:

using System;
using System.Data.SqlTypes;
using System.Net;
using System.Text;

/// <summary>
/// INet_NtoA and INet_AtoN MSSQL CLR.
/// This code will allow you to store IPv4 Addresses as INT64 values in the database, rather than a text string.
/// This allows you to sort the IP Address, where as it is difficult to do this if IP Addresses are stored as strings.
/// The INT 64 will allow you to sort it in proper subnet order.
/// </summary>

public partial class UserDefinedFunctions
{
    /// <summary>
    /// This function will take in an Int64 value, and convert it into a well formed IP Address.
    /// </summary>
    /// <param name="IP">Int64 Value that is the IP Address that wants converting.</param>
    /// <returns>Well formatted IP Address in string format. i.e. 10.10.10.254</returns>
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlString INET_NTOA(long IP)
    {
        try
        {
            IPAddress ip = new IPAddress(IP);
            string szIpAddress = ip.ToString();
            string[] octets = szIpAddress.Split('.');
            int iCnt = octets.GetUpperBound(0);
            StringBuilder ipReversed = new StringBuilder();
            while (iCnt >= 0)
            {
                ipReversed.Append(octets[iCnt]);
                if (iCnt >= 1)
                {
                    ipReversed.Append(".");
                }
                iCnt--;
            }
            IPAddress address;
            if (!IPAddress.TryParse(ipReversed.ToString(), out address))
            {
                throw new ApplicationException("The IP provided to INET_AtoN is not valid.");
            }
            return ipReversed.ToString();
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Unhandled exception occured converting, the following value '" + IP.ToString() + "' into a well formed IP Address. See inner exception for details", ex);
        }
    }
    /// <summary>
    /// Convert a well formed IP address back into its Int64, value for storing or sorting.
    /// </summary>
    /// <param name="IP">Well formed valid IP Address i.e. 10.10.10.10</param>
    /// <returns>SQLInt64 value of the converted IP Address string.</returns>
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlInt64 INET_ATON(string IP)
    {
        try
        {
            IPAddress address;
            if (!IPAddress.TryParse(IP, out address))
            {
                throw new ApplicationException("The IP provided to INet_AtoN is not valid.");
            }
            string[] szIpReverse = IP.Split('.');
            StringBuilder sbIPReversed = new StringBuilder();
            int iCntRv = szIpReverse.GetUpperBound(0);
            while (iCntRv >= 0)
            {
                sbIPReversed.Append(szIpReverse[iCntRv]);
                if (iCntRv >= 1)
                {
                    sbIPReversed.Append(".");
                }
                iCntRv--;
            }
            IPAddress oIP = IPAddress.Parse(sbIPReversed.ToString());
            byte[] byteIP = oIP.GetAddressBytes();
            uint uip = (uint)byteIP[3] << 24;
            uip += (uint)byteIP[2] << 16;
            uip += (uint)byteIP[1] << 8;
            uip += (uint)byteIP[0];
            return (SqlInt64)Convert.ToInt64(uip);
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Unhandled exception whilst converting INet_AtoN address into a valid Int64 representation. Please see inner exception for details", ex);
        }
    }

};


И вот никак не могу понять, зачем он риверсирует IP? Т.е. можно же просто строку парсим и число сохраняем. И при обратном число достали в конструктор и на выход строку.
По дороге разочарований снова очарованный пойду
 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.