How to store and search for an IP Address

前端 未结 7 1365
北海茫月
北海茫月 2021-01-20 02:56

I have the 4 sources of IP addresses , I want to store them in SQL Server and allow the ranges, that can be categorised by the originating country code, to be maked in an E

7条回答
  •  庸人自扰
    2021-01-20 03:24

    You can efficiently do it provided you store your IPv4 start addresses in the right data type. A varchar (or other string type) is not right - you need to use an int.

    For IPv4, store the IP number in an unsigned in which is big enough, then store it as a INET_ATON format (which is easy enough to generate; I'm not sure how in C# but it ain't difficult).

    You can then easily and efficiently look up which range an IP address is part of by arranging for the database to do a range scan.

    By using LIMIT (or SELECT TOP 1 in MSSQL) you can have it stop once it finds a record.

    SELECT TOP 1 networkidorwhatever, IPNumber, IPNumberUpperBoundOrWhateverYouCallIt 
    FROM networks 
    WHERE IPNumber <= IPNUMBERTOQUERY ORDER BY IPNumber DESC 
    

    Should find the highest numbered network number which is <= the IP number, then it's a trivial check to determine whether that IP address is within it.

    It should be efficient provided there is a conventional index on IPNumber.

    For IPv6 the types are different but the principle is the same.

提交回复
热议问题