Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_ipaddress_integer_operations_v4():
assert IPAddress('192.0.2.0') + 1 == IPAddress('192.0.2.1')
assert 1 + IPAddress('192.0.2.0') == IPAddress('192.0.2.1')
assert IPAddress('192.0.2.1') - 1 == IPAddress('192.0.2.0')
assert IPAddress('192.0.0.0') + IPAddress('0.0.0.42') == IPAddress('192.0.0.42')
assert IPAddress('192.0.0.42') - IPAddress('0.0.0.42') == IPAddress('192.0.0.0')
with pytest.raises(IndexError):
1 - IPAddress('192.0.2.1')
ip = IPAddress('10.0.0.1')
ip += 1
assert ip == IPAddress('10.0.0.2')
ip -= 1
assert ip == IPAddress('10.0.0.1')
ip += IPAddress('0.0.0.42')
assert ip == IPAddress('10.0.0.43')
def check_ips_within_subnet(module):
ips_to_check = [module.params['subnet']['gateway_ip'],
module.params['subnet']['allocation_pools'][0]['start'],
module.params['subnet']['allocation_pools'][0]['end']]
for ip in ips_to_check:
if netaddr.IPAddress(ip) not in netaddr.IPNetwork(module.params['subnet']['cidr']):
return False, ip
return True, None
:param router: The router on which the interface is added
:type router: LogicalRouter model object
:param router_port: The router interface being added
:type router_port: RouterInterface model object
"""
LOG.info("Adding new logical router interface = %r",
router_port)
local_network_id = router_port.lswitch.unique_key
parser = self.parser
ofproto = self.ofproto
mac = router_port.mac
router_unique_key = router.unique_key
dst_ip = router_port.network.ip
is_ipv4 = (netaddr.IPAddress(dst_ip).version ==
common_const.IP_VERSION_4)
# Add rule for making packets go from L2_LOOKUP_TABLE
# to L3_LOOKUP_TABLE
match = parser.OFPMatch()
match.set_metadata(local_network_id)
match.set_dl_dst(os_ken_mac_lib.haddr_to_bin(mac))
actions = [parser.OFPActionSetField(reg5=router_unique_key)]
action_inst = parser.OFPInstructionActions(
ofproto.OFPIT_APPLY_ACTIONS, actions)
goto_inst = parser.OFPInstructionGotoTable(const.L3_LOOKUP_TABLE)
inst = [action_inst, goto_inst]
self.mod_flow(
inst=inst,
table_id=const.L2_LOOKUP_TABLE,
priority=const.PRIORITY_HIGH,
@staticmethod
def unpack(data):
sip = struct.calcsize('>BIH')
scheme, ip, port = struct.unpack_from('>BIH', data)
scheme = SetProxy.well_known_proxy_schemes_decode[scheme]
ip = netaddr.IPAddress(ip)
data = data[sip:]
user = ''
password = ''
user_len = ord(data[0])
if user_len:
user = data[1:1+user_len]
data = data[1+user_len:]
pass_len = ord(data[0])
if pass_len:
password = data[1:1+pass_len]
return SetProxy(scheme, ip, port, user, password), sip+user_len+pass_len+2
def _is_local_network(self, address):
url = urlparse.urlparse(address)
try:
net = IPAddress(url).hostname
return net.is_private()
except (AddrFormatError, TypeError):
return False
for rh in host.relatedhosts.all():
if rh.available:
if kind == 'ipv4':
ifid = rh.interface_id_ipv4
netmask = host.netmask_ipv4
else: # kind == 'ipv6':
ifid = rh.interface_id_ipv6
netmask = host.netmask_ipv6
ifid = ifid.strip() if ifid else ifid
_delete = not ifid # leave ifid empty if you don't want this rh record
try:
rh_fqdn = FQDN(rh.name + '.' + fqdn.host, fqdn.domain)
if not _delete:
ifid = IPAddress(ifid)
network = IPNetwork("%s/%d" % (ipaddr, netmask))
rh_ipaddr = str(IPAddress(network.network) + int(ifid))
except (IndexError, AddrFormatError, ValueError) as e:
logger.warning("trouble computing address of related host %s [%s]" % (rh, e))
else:
if not _delete:
logger.info("updating related host %s -> %s" % (rh_fqdn, rh_ipaddr))
else:
logger.info("deleting related host %s" % (rh_fqdn, ))
try:
if not _delete:
update(rh_fqdn, rh_ipaddr)
else:
delete(rh_fqdn, rdtype)
except SameIpError:
msg = '%s - related hosts no-change update, ip: %s tls: %r' % (rh_fqdn, rh_ipaddr, secure)
logger.warning(msg)
host.register_client_result(msg, fault=True)
def refreshNetworkInfo():
try:
global iface_mac, ip_range, gw_ip, gw_mac, ip
iface_info = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]
iface_mac = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]["addr"]
netmask = iface_info["netmask"]
ip = iface_info["addr"]
ip_range = ip + "/" + str(IPAddress(netmask).netmask_bits())
gw_ip = False
for i in netifaces.gateways()[2]:
if i[1] == interface:
gw_ip = i[0]
if not gw_ip:
print("[!] Cant get gateway IP...")
else:
nm = nmap.PortScanner()
scan = nm.scan(hosts=gw_ip, arguments='-sn')
hosts = []
if gw_ip in scan["scan"]:
if "mac" in scan["scan"][gw_ip]["addresses"]:
gw_mac = scan["scan"][gw_ip]["addresses"]["mac"]
if not gw_mac:
print("[!] Cant get gateway MAC...")
return True
def contains_ip(self, ip):
"""ip is unicode or IPAddress object"""
if isinstance(ip, basestring):
try:
ip = IPAddress(ip)
except AddrFormatError:
return False
return rds.sismember(self.storekey, ip.value)
def get_netaddr(self):
try:
self.ifaddresses = netifaces.ifaddresses(self.name)[netifaces.AF_INET][0]
self.ip = netaddr.IPAddress(self.ifaddresses['addr'])
self.netmask = netaddr.IPAddress(self.ifaddresses['netmask'])
self.subnet = netaddr.IPNetwork('{0}/{1}'.format(self.ip, self.netmask))
except KeyError:
pass
:raises: ValueError, TypeError
"""
if not isinstance(ip, basestring):
raise TypeError("Expected basestring, got '%s' instead" % type(ipo))
try:
netaddr.IPAddress(ip)
except:
try:
m_listen = None
if ip.startswith("[") and ip.endswith("]"):
m_listen = ip[1:-1]
else:
m_listen = ip
netaddr.IPAddress(m_listen, version=6)
except:
raise ValueError("'%s' IP is not a valid IPv4 or IPv6 address" % str(ip))