Finding immediate parent prefix for an IP address

45 views
Skip to first unread message

Tom Kivlin

unread,
May 17, 2021, 11:03:29 AMMay 17
to NetBox
Hi - I am trying to work out if there is a shortcut to getting the most immediate parent prefix for a particular CIDR from the API?


And I will get 3 prefixes back:
"prefix": "10.50.0.0/16",
"prefix": "10.50.128.0/17",
"prefix": "10.50.130.0/23",

Obviously I could do some handling my side to check the netmask etc. to try and match them up but I wondered if there was a "magic" API query that exists to do this?

Brian Candler

unread,
May 17, 2021, 12:11:52 PMMay 17
to NetBox
Sort by prefix length and take the last.  They do appear to be already sorted in your case, but I don't know if that's accidental or guaranteed.

The Netbox data model duplicates prefix information, because every IP address object also stores a prefix length.  Given that you're looking for the prefix containing "10.50.130.22/23", you already know implicitly that it should be 10.50.130.0/23, without even making any API query.

In practice, I find people wrongly entering "/24" all the time, regardless of the true prefix length - so don't rely on it.

Tom Kivlin

unread,
May 17, 2021, 1:41:23 PMMay 17
to NetBox
Thanks, Brian - you got me thinking about this in a different way.  The background to this was that I am using Ansible to automate some infra.  Turns out Ansible has a built-in filter, ipsubnet(), which I can use to do exactly what you mentioned.
Ta,
Tom

Reply all
Reply to author
Forward
0 new messages