Skip to content

Commit

Permalink
Refactor is_local_ip function
Browse files Browse the repository at this point in the history
  • Loading branch information
Lekuruu committed Jan 3, 2024
1 parent a1b9896 commit 4b9bd3d
Showing 1 changed file with 20 additions and 19 deletions.
39 changes: 20 additions & 19 deletions helpers/external/location.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@
from dataclasses import dataclass
from functools import cache

import ipaddress
import config
import struct
import socket
import app

@dataclass(slots=True)
Expand Down Expand Up @@ -39,27 +38,29 @@ def download_database():
f.write(response.content)

def is_local_ip(ip: str) -> bool:
if ':' in ip:
# TODO: IPv6 parsing
return False
address = ipaddress.ip_address(ip)

private = (
[ 2130706432, 4278190080 ], # 127.0.0.0
[ 3232235520, 4294901760 ], # 192.168.0.0
[ 2886729728, 4293918720 ], # 172.16.0.0
[ 167772160, 4278190080 ], # 10.0.0.0
)
if address.version == 6:
private = [
ipaddress.IPv6Network('fc00::/7'),
ipaddress.IPv6Network('::1/128')
]

f = struct.unpack(
'!I',
socket.inet_pton(
socket.AF_INET,
ip
)
)[0]
for net in private:
if address in net:
return True

return False

private = [
ipaddress.IPv4Network('127.0.0.0/8'),
ipaddress.IPv4Network('192.168.0.0/16'),
ipaddress.IPv4Network('172.16.0.0/12'),
ipaddress.IPv4Network('10.0.0.0/8')
]

for net in private:
if (f & net[1]) == net[0]:
if address in net:
return True

return False
Expand Down

0 comments on commit 4b9bd3d

Please sign in to comment.