From 20ae076746a2d4ef186b6e3c5844b1d8fef03a02 Mon Sep 17 00:00:00 2001 From: Lee Miller Date: Wed, 17 Jul 2024 04:52:52 +0300 Subject: [PATCH] Separate methods for host encoding/decoding in structure.NetAddrNoPrefix --- minode/structure.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/minode/structure.py b/minode/structure.py index 405da1a..38507dc 100644 --- a/minode/structure.py +++ b/minode/structure.py @@ -162,14 +162,25 @@ class NetAddrNoPrefix(): return 'net_addr_no_prefix, services: {}, host: {}, port {}'.format( self.services, self.host, self.port) + @staticmethod + def decode_host(host): + if host.startswith( + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'): + return socket.inet_ntop(socket.AF_INET, host[-4:]) + return socket.inet_ntop(socket.AF_INET6, host) + + @staticmethod + def encode_host(host): + try: + host = socket.inet_pton(socket.AF_INET, host) + return b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + host + except socket.error: + return socket.inet_pton(socket.AF_INET6, host) + def to_bytes(self): b = b'' b += struct.pack('>Q', self.services) - try: - host = socket.inet_pton(socket.AF_INET, self.host) - b += b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + host - except socket.error: - b += socket.inet_pton(socket.AF_INET6, self.host) + b += self.encode_host(self.host) b += struct.pack('>H', int(self.port)) return b @@ -191,12 +202,7 @@ class NetAddrNoPrefix(): @classmethod def from_bytes(cls, b): services, host, port = struct.unpack('>Q16sH', b) - if host.startswith( - b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF'): - host = socket.inet_ntop(socket.AF_INET, host[-4:]) - else: - host = socket.inet_ntop(socket.AF_INET6, host) - return cls(services, host, port) + return cls(services, cls.decode_host(host), port) class NetAddr():