I have a table of IP Ranges and I need to generate a list of networks to reject for a specific country.
So I can generate a list of ip ranges from my db using this.
SELECT
ip_from,
Inet_ntoa(ip_from),
ip_to,
Inet_ntoa(ip_to)
FROM
ip_address_data
WHERE
country_code = 'XX'
LIMIT 1
which generates this result
ip_from inet_ntoa(ip_from) ip_to inet_ntoa(ip_to)
16777472 1.0.1.0 16778239 1.0.3.255
But I need that output in CIDR format and sometimes the range will be more than one row returned like this.
1.0.1.0/24
1.0.2.0/23
Is there any way to dynamically generate these using a select statement? This syntax would be awesome but I'm assuming it'll have to be a stored procedure if it's going to return more than one output row per input row.
SELECT
CONCAT('/sbin/route add -net ', CONVERT_TO_CIDR(ip_from,ip_to), ' reject;') AS command
FROM
ip_info.ip_address_data
WHERE
country_code='XX'
The CIDR number is typically preceded by a slash “/” and follows the IP address. For example, an IP address of 131.10. 55.70 with a subnet mask of 255.0. 0.0 (which has 8 network bits) would be represented as 131.10.
The formula to calculate the number of assignable IP address to CIDR networks is similar to classful networking. Subtract the number of network bits from 32. Raise 2 to that power and subtract 2 for the network and broadcast addresses. For example, a /24 network has 232-24 - 2 addresses available for host assignment.
Click IP Address Manager > IP Addresses > Manage Subnets & IP Addresses. In the network tree pane on the left, click the subnet to which you want to add your new IP address range. Click Add IP Range. Enter the starting IP address and the ending IP address of your IP address range.
IPv4 addresses allow a maximum of 32 bits. The same CIDR notation can be applied to IPv6 addresses. The only difference would be that IPv6 addresses can contain up to 128 bits.
Here's a python script to do the conversion. Just need to convert this to a stored procedure.
Conversion from IP Range to CIDR Mask
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With