#27 | Sort IPs in list. Added support for IPv6 so it can be sorted as well

This commit is contained in:
Jordi Albert 2022-09-05 10:12:37 +02:00
parent 086d7782e7
commit d295ad907c
2 changed files with 18 additions and 4 deletions

View File

@ -4,6 +4,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import frappe import frappe
import socket
from ipaddress import IPv4Address, IPv4Network from ipaddress import IPv4Address, IPv4Network
from frappe.model.document import Document from frappe.model.document import Document
@ -16,6 +17,7 @@ class IPNetwork(Document):
SELECT SELECT
ipa.name as ip_address_name, ipa.name as ip_address_name,
ipa.ip_address, ipa.ip_address,
ipa.protocol,
ito.name as it_object_name, ito.name as it_object_name,
ito.title, ito.title,
ito.type, ito.type,
@ -35,15 +37,19 @@ class IPNetwork(Document):
used_ips.append({ used_ips.append({
'ip_address': ip_network_reserved_range.start, 'ip_address': ip_network_reserved_range.start,
'title': ip_network_reserved_range.type, 'title': ip_network_reserved_range.type,
'type': 'DHCP Range Start' 'type': 'DHCP Range Start',
'protocol': ip_network_reserved_range.protocol
}) })
used_ips.append({ used_ips.append({
'ip_address': ip_network_reserved_range.end, 'ip_address': ip_network_reserved_range.end,
'title': ip_network_reserved_range.type, 'title': ip_network_reserved_range.type,
'type': 'DHCP Range End' 'type': 'DHCP Range End',
'protocol': ip_network_reserved_range.protocol
}) })
return used_ips # Sorting method is using inet_pton built in function which is used to convert IPs from string format to a packed, binary format to be able to compare them. It supports IPv4 and IPv6 IPs
# @see https://docs.python.org/3/library/socket.html#socket.inet_pton and https://stackoverflow.com/a/6545090 for more information
return sorted(used_ips, key=lambda item: socket.inet_pton(socket.AF_INET if item['protocol'] == 'IPv4' or not item['protocol'] else socket.AF_INET6 , item['ip_address']))
@frappe.whitelist() @frappe.whitelist()
def calculate_network_data(doc): def calculate_network_data(doc):

View File

@ -9,6 +9,7 @@
"start", "start",
"end", "end",
"type", "type",
"protocol",
"description" "description"
], ],
"fields": [ "fields": [
@ -35,12 +36,19 @@
"fieldname": "description", "fieldname": "description",
"fieldtype": "Text Editor", "fieldtype": "Text Editor",
"label": "Description" "label": "Description"
},
{
"default": "IPv4",
"fieldname": "protocol",
"fieldtype": "Select",
"label": "Protocol",
"options": "IPv4\nIPv6"
} }
], ],
"index_web_pages_for_search": 1, "index_web_pages_for_search": 1,
"istable": 1, "istable": 1,
"links": [], "links": [],
"modified": "2022-08-17 13:44:07.476976", "modified": "2022-09-05 09:57:47.527108",
"modified_by": "Administrator", "modified_by": "Administrator",
"module": "MSP", "module": "MSP",
"name": "IP Network Reserved Range", "name": "IP Network Reserved Range",