How do you do a lookup of an IP address using your database?
- If you are using a database like MySQL, you can use the inet_aton (https://dev.mysql.com/doc/refman/8.0/en/miscellaneous-functions.html#function_inet-aton) function and a query will look like this:
SELECT * FROM the_ip_table WHERE start_ip < INET_ATON('201.17.127.247') AND end_ip > INET_ATON('201.17.127.247')
- if you are using postgresql, you can create a function to convert the start_ip and end_ip to integers and then use the BETWEEN function when looking up an IP. Here is an example:
-- function to convert ip to int
CREATE FUNCTION ip2int(text) RETURNS bigint AS $
SELECT split_part($1,'.',1)::bigint*16777216 + split_part($1,'.',2)::bigint*65536 +
split_part($1,'.',3)::bigint*256 + split_part($1,'.',4)::bigint;
$ LANGUAGE SQL IMMUTABLE RETURNS NULL ON NULL INPUT;
-- sample query using the function
SELECT *
FROM ip_geolocation
WHERE ip2int('200.233.1.2') BETWEEN ip2int(start_ip) AND ip2int(end_ip)`