def ip_to_binary(ip): for family in (socket.AF_INET, socket.AF_INET6): try: data = socket.inet_pton(family, ip) except socket.error: continue return BinaryAddress(addr=data) raise socket.error("illegal IP address string: {}".format(ip))
def ip_str_to_addr(addr_str): ''' :param addr_str: ip address in string representation :returns: thrift struct BinaryAddress :rtype: ip_types.BinaryAddress ''' # Try v4 try: addr = socket.inet_pton(socket.AF_INET, addr_str) return BinaryAddress(addr=addr) except socket.error: pass # Try v6 addr = socket.inet_pton(socket.AF_INET6, addr_str) return BinaryAddress(addr=addr)
def parse_nexthops(nexthops): bin_addresses = [] for nh_iface in nexthops: iface, addr = None, None # Nexthop may or may not be link-local. Handle it here well if '@' in nh_iface: addr, iface = nh_iface.split('@') elif '%' in nh_iface: addr, iface = nh_iface.split('%') else: addr = nh_iface bin_addresses.append( BinaryAddress(addr=ipaddress.ip_address(addr).packed, ifName=iface)) return bin_addresses
def parse_nexthops(nexthops): nhts = [] for nh in nexthops: iface = None weight = 0 # Nexthop may have weight. if "x" in nh: addr_iface, _, weight = nh.rpartition("x") weight = int(weight) else: addr_iface = nh # Nexthop may or may not be link-local. Handle it here well if "@" in addr_iface: addr, _, iface = addr_iface.rpartition("@") elif "%" in addr_iface: addr, _, iface = addr_iface.rpartition("%") else: addr = addr_iface binaddr = BinaryAddress(addr=ipaddress.ip_address(addr).packed, ifName=iface) nhts.append(NextHopThrift(address=binaddr, weight=weight)) return nhts
def parse_prefix(prefix): network = ipaddress.ip_network(prefix) return IpPrefix( ip=BinaryAddress(addr=network.network_address.packed), prefixLength=network.prefixlen, )
def parse_nexthops(args): return [ BinaryAddress(addr=ipaddr.IPAddress(nh).packed) for nh in args.nexthop ]
def parse_prefix(args): network = ipaddr.IPNetwork(args.prefix) return IpPrefix(ip=BinaryAddress(addr=network.ip.packed), prefixLength=network.prefixlen)