Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

⚡️ Speed up function address_in_network by 79% #21

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions src/requests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -690,11 +690,12 @@ def address_in_network(ip, net):

:rtype: bool
"""
ipaddr = struct.unpack("=L", socket.inet_aton(ip))[0]
ipaddr = struct.unpack("!I", socket.inet_aton(ip))[0]
netaddr, bits = net.split("/")
netmask = struct.unpack("=L", socket.inet_aton(dotted_netmask(int(bits))))[0]
network = struct.unpack("=L", socket.inet_aton(netaddr))[0] & netmask
return (ipaddr & netmask) == (network & netmask)
bits = int(bits)
netmask = (1 << 32) - (1 << 32 - bits)
netaddr = struct.unpack("!I", socket.inet_aton(netaddr))[0]
return (ipaddr & netmask) == (netaddr & netmask)


def dotted_netmask(mask):
Expand All @@ -704,8 +705,7 @@ def dotted_netmask(mask):

:rtype: str
"""
bits = 0xFFFFFFFF ^ (1 << 32 - mask) - 1
return socket.inet_ntoa(struct.pack(">I", bits))
return socket.inet_ntoa(struct.pack(">I", (1 << 32) - (1 << 32 - mask)))


def is_ipv4_address(string_ip):
Expand Down