mirror of
https://github.com/netfun2000/ip2region.git
synced 2026-02-27 09:44:31 +08:00
Standardized code and add comments
This commit is contained in:
@@ -1,42 +1,47 @@
|
||||
# Created by leolin49 on 2022/7/7.
|
||||
# Copyright (C) 2022 leolin49. All rights reserved.
|
||||
|
||||
shift_index = (24, 16, 8, 0)
|
||||
# Util function
|
||||
# Copyright 2022 The Ip2Region Authors. All rights reserved.
|
||||
# Use of this source code is governed by a Apache2.0-style
|
||||
# license that can be found in the LICENSE file.
|
||||
#
|
||||
# Author: leolin49 <leolin49@foxmail.com>
|
||||
#
|
||||
_SHIFT_INDEX = (24, 16, 8, 0)
|
||||
|
||||
|
||||
def checkip(ip: str) -> int:
|
||||
"""Convert ip string to integer."""
|
||||
def check_ip(ip: str) -> int:
|
||||
"""
|
||||
Convert ip string to integer.
|
||||
Return -1 if ip is not the correct ipv4 address.
|
||||
"""
|
||||
if not is_ipv4(ip):
|
||||
return -1
|
||||
ps = ip.split(".")
|
||||
if len(ps) != 4:
|
||||
return 0
|
||||
val = 0
|
||||
for i in range(len(ps)):
|
||||
d = int(ps[i])
|
||||
if d < 0 or d > 255:
|
||||
return 0
|
||||
val |= d << shift_index[i]
|
||||
val |= d << _SHIFT_INDEX[i]
|
||||
return val
|
||||
|
||||
|
||||
def long2ip(num: int) -> str:
|
||||
"""Convert integer to ip string."""
|
||||
return "{}.{}.{}.{}".format((num >> 24) & 0xFF, (num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF)
|
||||
|
||||
|
||||
def mid_ip(sip: int, eip: int):
|
||||
"""Get the middle ip between sip and eip."""
|
||||
return (sip + eip) >> 1
|
||||
"""
|
||||
Convert integer to ip string.
|
||||
Return empty string if the num greater than UINT32_MAX or less than 0.
|
||||
"""
|
||||
if num < 0 or num > 0xFFFFFFFF:
|
||||
return ""
|
||||
return "{}.{}.{}.{}".format(
|
||||
(num >> 24) & 0xFF, (num >> 16) & 0xFF, (num >> 8) & 0xFF, num & 0xFF
|
||||
)
|
||||
|
||||
|
||||
def is_ipv4(ip: str) -> bool:
|
||||
"""Determine whether it is an ipv4 address."""
|
||||
p = ip.split(".")
|
||||
if len(p) != 4:
|
||||
"""
|
||||
Determine whether it is an ipv4 address.
|
||||
"""
|
||||
ps = ip.split(".")
|
||||
if len(ps) != 4:
|
||||
return False
|
||||
for pp in p:
|
||||
if not pp.isdigit() or len(pp) > 3 or int(pp) > 255:
|
||||
for p in ps:
|
||||
if not p.isdigit() or len(p) > 3 or (int(p) < 0 or int(p) > 255):
|
||||
return False
|
||||
return True
|
||||
|
||||
Reference in New Issue
Block a user