def __repr__(self): # Absent good types, make it best-effort to get these # renderable. If all characters are printable, we assume this # in not NBO. saddr, daddr, sport, dport = self.saddr, self.daddr, self.sport, self.dport if compat.have_real_bytes_type() and isinstance(saddr, bytes): saddr = self._addr_to_ascii(saddr) elif compat.is_ipaddress_type(saddr): saddr = saddr.exploded elif not all(c in string.printable for c in saddr): saddr = self._addr_to_ascii(saddr) if compat.have_real_bytes_type() and isinstance(daddr, bytes): daddr = self._addr_to_ascii(daddr) elif compat.is_ipaddress_type(daddr): daddr = daddr.exploded elif not all(c in string.printable for c in daddr): daddr = self._addr_to_ascii(daddr) if not isinstance(sport, int): sport = struct.unpack('!H', sport)[0] if not isinstance(self.dport, int): dport = struct.unpack('!H', dport)[0] return '[%s] %s/%s -> %s/%s' % (self.proto, saddr, sport, daddr, dport)
def get_data(self): """ Returns a FlowTuple.Data namedtuple with this flow tuple's data. The protocol is an integer number (e.g. 6 for TCP), saddr and daddr are ASCII-rendered/unpacked, and the ports are integers or None, if absent. """ # Absent good types, make it best-effort to get these # renderable. If all characters are printable, we assume this # in not NBO. saddr, daddr, sport, dport = self.saddr, self.daddr, self.sport, self.dport if compat.have_real_bytes_type() and isinstance(saddr, bytes): saddr = self._addr_to_ascii(saddr) elif compat.is_ipaddress_type(saddr): saddr = saddr.exploded elif not all(c in string.printable for c in saddr): saddr = self._addr_to_ascii(saddr) if compat.have_real_bytes_type() and isinstance(daddr, bytes): daddr = self._addr_to_ascii(daddr) elif compat.is_ipaddress_type(daddr): daddr = daddr.exploded elif not all(c in string.printable for c in daddr): daddr = self._addr_to_ascii(daddr) if sport is not None and not isinstance(sport, int): sport = struct.unpack("!H", sport)[0] if dport is not None and not isinstance(dport, int): dport = struct.unpack("!H", dport)[0] return FlowTuple.Data(self.proto, saddr, daddr, sport, dport)
def _addr_to_nbo(addr): if compat.is_ipaddress_type(addr): return addr.packed for family in (socket.AF_INET, socket.AF_INET6): try: return socket.inet_pton(family, addr) except (socket.error, TypeError): pass return addr
def _addr_to_ascii(addr): if compat.is_ipaddress_type(addr): return addr.exploded for family in (socket.AF_INET, socket.AF_INET6): try: return socket.inet_ntop(family, addr) except (socket.error, ValueError, TypeError): pass return addr
def addr_is_ipaddress_type(addr): return compat.is_ipaddress_type(addr)