Separate methods for host encoding/decoding in structure.NetAddrNoPrefix
This commit is contained in:
parent
d106078dac
commit
20ae076746
|
@ -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():
|
||||
|
|
Loading…
Reference in New Issue
Block a user