changes to replaces known usages of ipaddress, leaving only ipaddress.MacAddress

This commit is contained in:
Blake Harnden 2020-01-08 13:25:00 -08:00
parent f431254e15
commit fd10663323
15 changed files with 354 additions and 380 deletions

View file

@ -7,9 +7,10 @@ import threading
from contextlib import contextmanager
import grpc
import netaddr
from core.api.grpc import core_pb2, core_pb2_grpc
from core.nodes.ipaddress import Ipv4Prefix, Ipv6Prefix, MacAddress
from core.nodes.ipaddress import MacAddress
class InterfaceHelper:
@ -30,10 +31,10 @@ class InterfaceHelper:
self.ip4 = None
if ip4_prefix:
self.ip4 = Ipv4Prefix(ip4_prefix)
self.ip4 = netaddr.IPNetwork(ip4_prefix)
self.ip6 = None
if ip6_prefix:
self.ip6 = Ipv6Prefix(ip6_prefix)
self.ip6 = netaddr.IPNetwork(ip6_prefix)
def ip4_address(self, node_id):
"""
@ -45,7 +46,7 @@ class InterfaceHelper:
"""
if not self.ip4:
raise ValueError("ip4 prefixes have not been set")
return str(self.ip4.addr(node_id))
return str(self.ip4[node_id])
def ip6_address(self, node_id):
"""
@ -57,7 +58,7 @@ class InterfaceHelper:
"""
if not self.ip6:
raise ValueError("ip6 prefixes have not been set")
return str(self.ip6.addr(node_id))
return str(self.ip6[node_id])
def create_interface(self, node_id, interface_id, name=None, mac=None):
"""
@ -75,14 +76,14 @@ class InterfaceHelper:
ip4 = None
ip4_mask = None
if self.ip4:
ip4 = str(self.ip4.addr(node_id))
ip4 = self.ip4_address(node_id)
ip4_mask = self.ip4.prefixlen
# generate ip6 data
ip6 = None
ip6_mask = None
if self.ip6:
ip6 = str(self.ip6.addr(node_id))
ip6 = self.ip6_address(node_id)
ip6_mask = self.ip6.prefixlen
# random mac

View file

@ -24,7 +24,7 @@ from core.emulator.enumerations import (
RegisterTlvs,
SessionTlvs,
)
from core.nodes.ipaddress import IpAddress, MacAddress
from core.nodes.ipaddress import MacAddress
class CoreTlvData:
@ -258,7 +258,7 @@ class CoreTlvDataIpv4Addr(CoreTlvDataObj):
Utility class for packing/unpacking Ipv4 addresses.
"""
data_type = IpAddress.from_string
data_type = str
data_format = "!2x4s"
pad_len = 2
@ -267,21 +267,22 @@ class CoreTlvDataIpv4Addr(CoreTlvDataObj):
"""
Retrieve Ipv4 address value from object.
:param core.misc.ipaddress.IpAddress obj: ip address to get value from
:return:
:param str obj: ip address to get value from
:return: packed address
:rtype: bytes
"""
return obj.addr
return socket.inet_pton(socket.AF_INET, obj)
@staticmethod
def new_obj(value):
"""
Retrieve Ipv4 address from a string representation.
:param str value: value to get Ipv4 address from
:param bytes value: value to get Ipv4 address from
:return: Ipv4 address
:rtype: core.nodes.ipaddress.IpAddress
:rtype: str
"""
return IpAddress(af=socket.AF_INET, address=value)
return socket.inet_ntop(socket.AF_INET, value)
class CoreTlvDataIPv6Addr(CoreTlvDataObj):
@ -290,7 +291,7 @@ class CoreTlvDataIPv6Addr(CoreTlvDataObj):
"""
data_format = "!16s2x"
data_type = IpAddress.from_string
data_type = str
pad_len = 2
@staticmethod
@ -298,21 +299,22 @@ class CoreTlvDataIPv6Addr(CoreTlvDataObj):
"""
Retrieve Ipv6 address value from object.
:param core.nodes.ipaddress.IpAddress obj: ip address to get value from
:return:
:param str obj: ip address to get value from
:return: packed address
:rtype: bytes
"""
return obj.addr
return socket.inet_pton(socket.AF_INET6, obj)
@staticmethod
def new_obj(value):
"""
Retrieve Ipv6 address from a string representation.
:param str value: value to get Ipv4 address from
:param bytes value: value to get Ipv4 address from
:return: Ipv4 address
:rtype: core.nodes.ipaddress.IpAddress
:rtype: str
"""
return IpAddress(af=socket.AF_INET6, address=value)
return socket.inet_ntop(socket.AF_INET6, value)
class CoreTlvDataMacAddr(CoreTlvDataObj):

View file

@ -8,13 +8,13 @@ import threading
from collections import OrderedDict
from tempfile import NamedTemporaryFile
import netaddr
from fabric import Connection
from invoke import UnexpectedExit
from core import utils
from core.errors import CoreCommandError
from core.nodes.interface import GreTap
from core.nodes.ipaddress import IpAddress
from core.nodes.network import CoreNetwork, CtrlNet
LOCK = threading.Lock()
@ -196,7 +196,7 @@ class DistributedController:
:rtype: tuple
"""
host = server.host
key = self.tunnel_key(node.id, IpAddress.to_int(host))
key = self.tunnel_key(node.id, netaddr.IPAddress(host).value)
tunnel = self.tunnels.get(key)
if tunnel is not None:
return tunnel

View file

@ -1,6 +1,8 @@
import netaddr
from core.emane.nodes import EmaneNet
from core.emulator.enumerations import LinkTypes
from core.nodes.ipaddress import Ipv4Prefix, Ipv6Prefix, MacAddress
from core.nodes.ipaddress import MacAddress
from core.nodes.physical import PhysicalNode
@ -164,10 +166,10 @@ class IpPrefixes:
self.ip4 = None
if ip4_prefix:
self.ip4 = Ipv4Prefix(ip4_prefix)
self.ip4 = netaddr.IPNetwork(ip4_prefix)
self.ip6 = None
if ip6_prefix:
self.ip6 = Ipv6Prefix(ip6_prefix)
self.ip6 = netaddr.IPNetwork(ip6_prefix)
def ip4_address(self, node):
"""
@ -179,7 +181,7 @@ class IpPrefixes:
"""
if not self.ip4:
raise ValueError("ip4 prefixes have not been set")
return str(self.ip4.addr(node.id))
return str(self.ip4[node.id])
def ip6_address(self, node):
"""
@ -191,7 +193,7 @@ class IpPrefixes:
"""
if not self.ip6:
raise ValueError("ip6 prefixes have not been set")
return str(self.ip6.addr(node.id))
return str(self.ip6[node.id])
def create_interface(self, node, name=None, mac=None):
"""
@ -212,14 +214,14 @@ class IpPrefixes:
ip4 = None
ip4_mask = None
if self.ip4:
ip4 = str(self.ip4.addr(node.id))
ip4 = self.ip4_address(node)
ip4_mask = self.ip4.prefixlen
# generate ip6 data
ip6 = None
ip6_mask = None
if self.ip6:
ip6 = str(self.ip6.addr(node.id))
ip6 = self.ip6_address(node)
ip6_mask = self.ip6.prefixlen
# random mac

View file

@ -1764,7 +1764,7 @@ class Session:
control_ip = node.id
try:
address = control_net.prefix.addr(control_ip)
address = control_net.prefix[control_ip]
prefix = control_net.prefix.prefixlen
addrlist = [f"{address}/{prefix}"]
except ValueError:

View file

@ -5,9 +5,7 @@ Defines the base logic for nodes used within core.
import logging
import os
import shutil
import socket
import threading
from socket import AF_INET, AF_INET6
import netaddr
@ -16,7 +14,7 @@ from core.constants import MOUNT_BIN, VNODED_BIN
from core.emulator.data import LinkData, NodeData
from core.emulator.enumerations import LinkTypes, NodeTypes
from core.errors import CoreCommandError
from core.nodes import client, ipaddress
from core.nodes import client
from core.nodes.interface import TunTap, Veth
from core.nodes.netclient import get_net_client
@ -741,25 +739,24 @@ class CoreNode(CoreNodeBase):
Add interface address.
:param int ifindex: index of interface to add address to
:param core.nodes.ipaddress.IpAddress addr: address to add to interface
:param str addr: address to add to interface
:return: nothing
"""
interface = self._netif[ifindex]
interface.addaddr(addr)
if self.up:
address = str(addr)
# ipv6 check
# ipv4 check
broadcast = None
if ":" not in address:
if netaddr.valid_ipv4(addr):
broadcast = "+"
self.node_net_client.create_address(interface.name, address, broadcast)
self.node_net_client.create_address(interface.name, addr, broadcast)
def deladdr(self, ifindex, addr):
"""
Delete address from an interface.
:param int ifindex: index of interface to delete address from
:param core.nodes.ipaddress.IpAddress addr: address to delete from interface
:param str addr: address to delete from interface
:return: nothing
:raises CoreCommandError: when a non-zero exit status occurs
"""
@ -771,7 +768,7 @@ class CoreNode(CoreNodeBase):
logging.exception("trying to delete unknown address: %s", addr)
if self.up:
self.node_net_client.delete_address(interface.name, str(addr))
self.node_net_client.delete_address(interface.name, addr)
def ifup(self, ifindex):
"""
@ -1018,14 +1015,10 @@ class CoreNetworkBase(NodeBase):
ip, _sep, mask = address.partition("/")
mask = int(mask)
if netaddr.valid_ipv4(ip):
family = AF_INET
ipl = socket.inet_pton(family, ip)
interface2_ip4 = ipaddress.IpAddress(af=family, address=ipl)
interface2_ip4 = ip
interface2_ip4_mask = mask
else:
family = AF_INET6
ipl = socket.inet_pton(family, ip)
interface2_ip6 = ipaddress.IpAddress(af=family, address=ipl)
interface2_ip6 = ip
interface2_ip6_mask = mask
link_data = LinkData(

View file

@ -202,255 +202,255 @@ class IpAddress:
return struct.unpack("!I", value)[0]
class IpPrefix:
"""
Provides ip address generation and prefix utilities.
"""
def __init__(self, af, prefixstr):
"""
Create a IpPrefix instance.
:param int af: address family for ip prefix
:param str prefixstr: ip prefix string
"""
# prefixstr format: address/prefixlen
tmp = prefixstr.split("/")
if len(tmp) > 2:
raise ValueError(f"invalid prefix: {prefixstr}")
self.af = af
if self.af == AF_INET:
self.addrlen = 32
elif self.af == AF_INET6:
self.addrlen = 128
else:
raise ValueError(f"invalid address family: {self.af}")
if len(tmp) == 2:
self.prefixlen = int(tmp[1])
else:
self.prefixlen = self.addrlen
self.prefix = socket.inet_pton(self.af, tmp[0])
self.prefix = bytes(self.prefix)
if self.addrlen > self.prefixlen:
addrbits = self.addrlen - self.prefixlen
netmask = ((1 << self.prefixlen) - 1) << addrbits
prefix = bytes(b"")
for i in range(-1, -(addrbits >> 3) - 2, -1):
prefix = bytes([self.prefix[i] & (netmask & 0xFF)]) + prefix
netmask >>= 8
self.prefix = self.prefix[:i] + prefix
def __str__(self):
"""
String representation of an ip prefix.
:return: string representation
:rtype: str
"""
address = socket.inet_ntop(self.af, self.prefix)
return f"{address}/{self.prefixlen}"
def __eq__(self, other):
"""
Compare equality with another ip prefix.
:param IpPrefix other: other ip prefix to compare with
:return: True is equal, False otherwise
:rtype: bool
"""
if not isinstance(other, IpPrefix):
return False
elif self is other:
return True
else:
return (
other.af == self.af
and other.prefixlen == self.prefixlen
and other.prefix == self.prefix
)
def __add__(self, other):
"""
Add a value to this ip prefix.
:param int other: value to add
:return: added ip prefix instance
:rtype: IpPrefix
"""
try:
tmp = int(other)
except ValueError:
logging.exception("error during addition")
return NotImplemented
a = IpAddress(self.af, self.prefix) + (tmp << (self.addrlen - self.prefixlen))
prefixstr = f"{a}/{self.prefixlen}"
if self.__class__ == IpPrefix:
return self.__class__(self.af, prefixstr)
else:
return self.__class__(prefixstr)
def __sub__(self, other):
"""
Subtract value from this ip prefix.
:param int other: value to subtract
:return: subtracted ip prefix instance
:rtype: IpPrefix
"""
try:
tmp = -int(other)
except ValueError:
logging.exception("error during subtraction")
return NotImplemented
return self.__add__(tmp)
def addr(self, hostid):
"""
Create an ip address for a given host id.
:param hostid: host id for an ip address
:return: ip address
:rtype: IpAddress
"""
tmp = int(hostid)
if tmp in [-1, 0, 1] and self.addrlen == self.prefixlen:
return IpAddress(self.af, self.prefix)
if (
tmp == 0
or tmp > (1 << (self.addrlen - self.prefixlen)) - 1
or (
self.af == AF_INET and tmp == (1 << (self.addrlen - self.prefixlen)) - 1
)
):
raise ValueError(f"invalid hostid for prefix {self}: {hostid}")
addr = bytes(b"")
prefix_endpoint = -1
for i in range(-1, -(self.addrlen >> 3) - 1, -1):
prefix_endpoint = i
addr = bytes([self.prefix[i] | (tmp & 0xFF)]) + addr
tmp >>= 8
if not tmp:
break
addr = self.prefix[:prefix_endpoint] + addr
return IpAddress(self.af, addr)
def min_addr(self):
"""
Return the minimum ip address for this prefix.
:return: minimum ip address
:rtype: IpAddress
"""
return self.addr(1)
def max_addr(self):
"""
Return the maximum ip address for this prefix.
:return: maximum ip address
:rtype: IpAddress
"""
if self.af == AF_INET:
return self.addr((1 << (self.addrlen - self.prefixlen)) - 2)
else:
return self.addr((1 << (self.addrlen - self.prefixlen)) - 1)
def num_addr(self):
"""
Retrieve the number of ip addresses for this prefix.
:return: maximum number of ip addresses
:rtype: int
"""
return max(0, (1 << (self.addrlen - self.prefixlen)) - 2)
def prefix_str(self):
"""
Retrieve the prefix string for this ip address.
:return: prefix string
:rtype: str
"""
return socket.inet_ntop(self.af, self.prefix)
def netmask_str(self):
"""
Retrieve the netmask string for this ip address.
:return: netmask string
:rtype: str
"""
addrbits = self.addrlen - self.prefixlen
netmask = ((1 << self.prefixlen) - 1) << addrbits
netmaskbytes = struct.pack("!L", netmask)
return IpAddress(af=AF_INET, address=netmaskbytes).__str__()
# class IpPrefix:
# """
# Provides ip address generation and prefix utilities.
# """
#
# def __init__(self, af, prefixstr):
# """
# Create a IpPrefix instance.
#
# :param int af: address family for ip prefix
# :param str prefixstr: ip prefix string
# """
# # prefixstr format: address/prefixlen
# tmp = prefixstr.split("/")
# if len(tmp) > 2:
# raise ValueError(f"invalid prefix: {prefixstr}")
# self.af = af
# if self.af == AF_INET:
# self.addrlen = 32
# elif self.af == AF_INET6:
# self.addrlen = 128
# else:
# raise ValueError(f"invalid address family: {self.af}")
# if len(tmp) == 2:
# self.prefixlen = int(tmp[1])
# else:
# self.prefixlen = self.addrlen
# self.prefix = socket.inet_pton(self.af, tmp[0])
# self.prefix = bytes(self.prefix)
# if self.addrlen > self.prefixlen:
# addrbits = self.addrlen - self.prefixlen
# netmask = ((1 << self.prefixlen) - 1) << addrbits
# prefix = bytes(b"")
# for i in range(-1, -(addrbits >> 3) - 2, -1):
# prefix = bytes([self.prefix[i] & (netmask & 0xFF)]) + prefix
# netmask >>= 8
# self.prefix = self.prefix[:i] + prefix
#
# def __str__(self):
# """
# String representation of an ip prefix.
#
# :return: string representation
# :rtype: str
# """
# address = socket.inet_ntop(self.af, self.prefix)
# return f"{address}/{self.prefixlen}"
#
# def __eq__(self, other):
# """
# Compare equality with another ip prefix.
#
# :param IpPrefix other: other ip prefix to compare with
# :return: True is equal, False otherwise
# :rtype: bool
# """
# if not isinstance(other, IpPrefix):
# return False
# elif self is other:
# return True
# else:
# return (
# other.af == self.af
# and other.prefixlen == self.prefixlen
# and other.prefix == self.prefix
# )
#
# def __add__(self, other):
# """
# Add a value to this ip prefix.
#
# :param int other: value to add
# :return: added ip prefix instance
# :rtype: IpPrefix
# """
# try:
# tmp = int(other)
# except ValueError:
# logging.exception("error during addition")
# return NotImplemented
#
# a = IpAddress(self.af, self.prefix) + (tmp << (self.addrlen - self.prefixlen))
# prefixstr = f"{a}/{self.prefixlen}"
# if self.__class__ == IpPrefix:
# return self.__class__(self.af, prefixstr)
# else:
# return self.__class__(prefixstr)
#
# def __sub__(self, other):
# """
# Subtract value from this ip prefix.
#
# :param int other: value to subtract
# :return: subtracted ip prefix instance
# :rtype: IpPrefix
# """
# try:
# tmp = -int(other)
# except ValueError:
# logging.exception("error during subtraction")
# return NotImplemented
#
# return self.__add__(tmp)
#
# def addr(self, hostid):
# """
# Create an ip address for a given host id.
#
# :param hostid: host id for an ip address
# :return: ip address
# :rtype: IpAddress
# """
# tmp = int(hostid)
# if tmp in [-1, 0, 1] and self.addrlen == self.prefixlen:
# return IpAddress(self.af, self.prefix)
#
# if (
# tmp == 0
# or tmp > (1 << (self.addrlen - self.prefixlen)) - 1
# or (
# self.af == AF_INET and tmp == (1 << (self.addrlen - self.prefixlen)) - 1
# )
# ):
# raise ValueError(f"invalid hostid for prefix {self}: {hostid}")
#
# addr = bytes(b"")
# prefix_endpoint = -1
# for i in range(-1, -(self.addrlen >> 3) - 1, -1):
# prefix_endpoint = i
# addr = bytes([self.prefix[i] | (tmp & 0xFF)]) + addr
# tmp >>= 8
# if not tmp:
# break
# addr = self.prefix[:prefix_endpoint] + addr
# return IpAddress(self.af, addr)
#
# def min_addr(self):
# """
# Return the minimum ip address for this prefix.
#
# :return: minimum ip address
# :rtype: IpAddress
# """
# return self.addr(1)
#
# def max_addr(self):
# """
# Return the maximum ip address for this prefix.
#
# :return: maximum ip address
# :rtype: IpAddress
# """
# if self.af == AF_INET:
# return self.addr((1 << (self.addrlen - self.prefixlen)) - 2)
# else:
# return self.addr((1 << (self.addrlen - self.prefixlen)) - 1)
#
# def num_addr(self):
# """
# Retrieve the number of ip addresses for this prefix.
#
# :return: maximum number of ip addresses
# :rtype: int
# """
# return max(0, (1 << (self.addrlen - self.prefixlen)) - 2)
#
# def prefix_str(self):
# """
# Retrieve the prefix string for this ip address.
#
# :return: prefix string
# :rtype: str
# """
# return socket.inet_ntop(self.af, self.prefix)
#
# def netmask_str(self):
# """
# Retrieve the netmask string for this ip address.
#
# :return: netmask string
# :rtype: str
# """
# addrbits = self.addrlen - self.prefixlen
# netmask = ((1 << self.prefixlen) - 1) << addrbits
# netmaskbytes = struct.pack("!L", netmask)
# return IpAddress(af=AF_INET, address=netmaskbytes).__str__()
class Ipv4Prefix(IpPrefix):
"""
Provides an ipv4 specific class for ip prefixes.
"""
def __init__(self, prefixstr):
"""
Create a Ipv4Prefix instance.
:param str prefixstr: ip prefix
"""
super().__init__(AF_INET, prefixstr)
class Ipv6Prefix(IpPrefix):
"""
Provides an ipv6 specific class for ip prefixes.
"""
def __init__(self, prefixstr):
"""
Create a Ipv6Prefix instance.
:param str prefixstr: ip prefix
"""
super().__init__(AF_INET6, prefixstr)
def is_ip_address(af, addrstr):
"""
Check if ip address string is a valid ip address.
:param int af: address family
:param str addrstr: ip address string
:return: True if a valid ip address, False otherwise
:rtype: bool
"""
try:
socket.inet_pton(af, addrstr)
return True
except IOError:
return False
def is_ipv4_address(addrstr):
"""
Check if ipv4 address string is a valid ipv4 address.
:param str addrstr: ipv4 address string
:return: True if a valid ipv4 address, False otherwise
:rtype: bool
"""
return is_ip_address(AF_INET, addrstr)
def is_ipv6_address(addrstr):
"""
Check if ipv6 address string is a valid ipv6 address.
:param str addrstr: ipv6 address string
:return: True if a valid ipv6 address, False otherwise
:rtype: bool
"""
return is_ip_address(AF_INET6, addrstr)
# class Ipv4Prefix(IpPrefix):
# """
# Provides an ipv4 specific class for ip prefixes.
# """
#
# def __init__(self, prefixstr):
# """
# Create a Ipv4Prefix instance.
#
# :param str prefixstr: ip prefix
# """
# super().__init__(AF_INET, prefixstr)
#
#
# class Ipv6Prefix(IpPrefix):
# """
# Provides an ipv6 specific class for ip prefixes.
# """
#
# def __init__(self, prefixstr):
# """
# Create a Ipv6Prefix instance.
#
# :param str prefixstr: ip prefix
# """
# super().__init__(AF_INET6, prefixstr)
#
#
# def is_ip_address(af, addrstr):
# """
# Check if ip address string is a valid ip address.
#
# :param int af: address family
# :param str addrstr: ip address string
# :return: True if a valid ip address, False otherwise
# :rtype: bool
# """
# try:
# socket.inet_pton(af, addrstr)
# return True
# except IOError:
# return False
#
#
# def is_ipv4_address(addrstr):
# """
# Check if ipv4 address string is a valid ipv4 address.
#
# :param str addrstr: ipv4 address string
# :return: True if a valid ipv4 address, False otherwise
# :rtype: bool
# """
# return is_ip_address(AF_INET, addrstr)
#
#
# def is_ipv6_address(addrstr):
# """
# Check if ipv6 address string is a valid ipv6 address.
#
# :param str addrstr: ipv6 address string
# :return: True if a valid ipv6 address, False otherwise
# :rtype: bool
# """
# return is_ip_address(AF_INET6, addrstr)

View file

@ -3,10 +3,8 @@ Defines network nodes used within core.
"""
import logging
import socket
import threading
import time
from socket import AF_INET, AF_INET6
import netaddr
@ -15,7 +13,6 @@ from core.constants import EBTABLES_BIN, TC_BIN
from core.emulator.data import LinkData
from core.emulator.enumerations import LinkTypes, NodeTypes, RegisterTlvs
from core.errors import CoreCommandError, CoreError
from core.nodes import ipaddress
from core.nodes.base import CoreNetworkBase
from core.nodes.interface import GreTap, Veth
from core.nodes.netclient import get_net_client
@ -752,28 +749,30 @@ class CtrlNet(CoreNetwork):
:param serverintf: server interface
:return:
"""
self.prefix = ipaddress.Ipv4Prefix(prefix)
self.prefix = netaddr.IPNetwork(prefix).cidr
self.hostid = hostid
self.assign_address = assign_address
self.updown_script = updown_script
self.serverintf = serverintf
super().__init__(session, _id, name, start, server)
def add_addresses(self, address):
def add_addresses(self, index):
"""
Add addresses used for created control networks,
:param core.nodes.interfaces.IpAddress address: starting address to use
:return:
:param int index: starting address index
:return: nothing
"""
use_ovs = self.session.options.get_config("ovs") == "True"
address = self.prefix[index]
current = f"{address}/{self.prefix.prefixlen}"
net_client = get_net_client(use_ovs, utils.cmd)
net_client.create_address(self.brname, current)
servers = self.session.distributed.servers
for name in servers:
server = servers[name]
address -= 1
index -= 1
address = self.prefix[index]
current = f"{address}/{self.prefix.prefixlen}"
net_client = get_net_client(use_ovs, server.remote_cmd)
net_client.create_address(self.brname, current)
@ -792,11 +791,9 @@ class CtrlNet(CoreNetwork):
logging.info("added control network bridge: %s %s", self.brname, self.prefix)
if self.hostid and self.assign_address:
address = self.prefix.addr(self.hostid)
self.add_addresses(address)
self.add_addresses(self.hostid)
elif self.assign_address:
address = self.prefix.max_addr()
self.add_addresses(address)
self.add_addresses(-2)
if self.updown_script:
logging.info(
@ -911,14 +908,10 @@ class PtpNet(CoreNetwork):
ip, _sep, mask = address.partition("/")
mask = int(mask)
if netaddr.valid_ipv4(ip):
family = AF_INET
ipl = socket.inet_pton(family, ip)
interface1_ip4 = ipaddress.IpAddress(af=family, address=ipl)
interface1_ip4 = ip
interface1_ip4_mask = mask
else:
family = AF_INET6
ipl = socket.inet_pton(family, ip)
interface1_ip6 = ipaddress.IpAddress(af=family, address=ipl)
interface1_ip6 = ip
interface1_ip6_mask = mask
interface2_ip4 = None
@ -929,14 +922,10 @@ class PtpNet(CoreNetwork):
ip, _sep, mask = address.partition("/")
mask = int(mask)
if netaddr.valid_ipv4(ip):
family = AF_INET
ipl = socket.inet_pton(family, ip)
interface2_ip4 = ipaddress.IpAddress(af=family, address=ipl)
interface2_ip4 = ip
interface2_ip4_mask = mask
else:
family = AF_INET6
ipl = socket.inet_pton(family, ip)
interface2_ip6 = ipaddress.IpAddress(af=family, address=ipl)
interface2_ip6 = ip
interface2_ip6_mask = mask
link_data = LinkData(

View file

@ -5,7 +5,6 @@ nrl.py: defines services provided by NRL protolib tools hosted here:
import netaddr
from core import utils
from core.nodes.ipaddress import Ipv4Prefix
from core.services.coreservices import CoreService
@ -39,8 +38,7 @@ class NrlService(CoreService):
for a in ifc.addrlist:
a = a.split("/")[0]
if netaddr.valid_ipv4(a):
pre = Ipv4Prefix("%s/%s" % (a, prefixlen))
return str(pre)
return f"{a}/{prefixlen}"
# raise ValueError, "no IPv4 address found"
return "0.0.0.0/%s" % prefixlen

View file

@ -8,7 +8,6 @@ import netaddr
from core import constants, utils
from core.errors import CoreCommandError
from core.nodes.ipaddress import Ipv4Prefix, Ipv6Prefix
from core.services.coreservices import CoreService, ServiceMode
@ -89,19 +88,15 @@ class DefaultRouteService(UtilService):
@staticmethod
def addrstr(x):
addr = x.split("/")[0]
if netaddr.valid_ipv6(addr):
net = Ipv6Prefix(x)
else:
net = Ipv4Prefix(x)
if net.max_addr() == net.min_addr():
net = netaddr.IPNetwork(x)
if net[1] == net[-2]:
return ""
else:
if os.uname()[0] == "Linux":
rtcmd = "ip route add default via"
else:
raise Exception("unknown platform")
return "%s %s" % (rtcmd, net.min_addr())
return "%s %s" % (rtcmd, net[1])
class DefaultMulticastRouteService(UtilService):
@ -152,19 +147,18 @@ class StaticRouteService(UtilService):
def routestr(x):
addr = x.split("/")[0]
if netaddr.valid_ipv6(addr):
net = Ipv6Prefix(x)
dst = "3ffe:4::/64"
else:
net = Ipv4Prefix(x)
dst = "10.9.8.0/24"
if net.max_addr() == net.min_addr():
net = netaddr.IPNetwork(x)
if net[-2] == net[1]:
return ""
else:
if os.uname()[0] == "Linux":
rtcmd = "#/sbin/ip route add %s via" % dst
else:
raise Exception("unknown platform")
return "%s %s" % (rtcmd, net.min_addr())
return "%s %s" % (rtcmd, net[1])
class SshService(UtilService):
@ -289,11 +283,11 @@ ddns-update-style none;
if netaddr.valid_ipv6(addr):
return ""
else:
addr = x.split("/")[0]
net = Ipv4Prefix(x)
net = netaddr.IPNetwork(x)
# divide the address space in half
rangelow = net.addr(net.num_addr() / 2)
rangehigh = net.max_addr()
index = (net.size - 2) / 2
rangelow = net[index]
rangehigh = net[-2]
return """
subnet %s netmask %s {
pool {
@ -303,8 +297,8 @@ subnet %s netmask %s {
}
}
""" % (
net.prefix_str(),
net.netmask_str(),
net.ip,
net.netmask,
rangelow,
rangehigh,
addr,
@ -710,8 +704,7 @@ interface %s
"""
addr = x.split("/")[0]
if netaddr.valid_ipv6(addr):
net = Ipv6Prefix(x)
return str(net)
return x
else:
return ""

View file

@ -5,6 +5,7 @@ import os
import time
import mock
import netaddr
import pytest
from mock import MagicMock
@ -26,7 +27,6 @@ from core.emulator.enumerations import (
)
from core.errors import CoreError
from core.location.mobility import BasicRangeModel
from core.nodes.ipaddress import Ipv4Prefix
def dict_to_str(values):
@ -101,8 +101,8 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
switch = 2
coretlv.session.add_node(_id=switch, _type=NodeTypes.SWITCH)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -125,8 +125,8 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
switch = 2
coretlv.session.add_node(_id=switch, _type=NodeTypes.SWITCH)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -149,9 +149,9 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
node_two = 2
coretlv.session.add_node(_id=node_two)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
interface_two = ip_prefix.addr(node_two)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
interface_two = str(ip_prefix[node_two])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -179,8 +179,8 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
switch = 2
coretlv.session.add_node(_id=switch, _type=NodeTypes.SWITCH)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -221,9 +221,9 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
node_two = 2
coretlv.session.add_node(_id=node_two)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
interface_two = ip_prefix.addr(node_two)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
interface_two = str(ip_prefix[node_two])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -265,8 +265,8 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
switch = 2
coretlv.session.add_node(_id=switch, _type=NodeTypes.SWITCH)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[
@ -301,8 +301,8 @@ class TestGui:
coretlv.session.add_node(_id=node_one)
switch = 2
coretlv.session.add_node(_id=switch, _type=NodeTypes.SWITCH)
ip_prefix = Ipv4Prefix("10.0.0.0/24")
interface_one = ip_prefix.addr(node_one)
ip_prefix = netaddr.IPNetwork("10.0.0.0/24")
interface_one = str(ip_prefix[node_one])
message = coreapi.CoreLinkMessage.create(
MessageFlags.ADD.value,
[

View file

@ -8,13 +8,12 @@ import logging
import optparse
import sys
import netaddr
import ns.core
import ns.mobility
from corens3.obj import Ns3LteNet
from corens3.obj import Ns3Session
from core.nodes import ipaddress
def ltesession(opt):
"""
@ -28,10 +27,10 @@ def ltesession(opt):
stream = ascii_helper.CreateFileStream('/tmp/ns3lte.tr')
lte.lte.EnableAsciiAll(stream)
prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
prefix = netaddr.IPNetwork("10.0.0.0/16")
mobb = None
nodes = []
for i in xrange(1, opt.numnodes + 1):
for i in range(1, opt.numnodes + 1):
node = session.addnode(name="n%d" % i)
mob = ns.mobility.ConstantPositionMobilityModel()
mob.SetPosition(ns.core.Vector3D(10.0 * i, 0.0, 0.0))
@ -39,7 +38,7 @@ def ltesession(opt):
# first node is nodeb
lte.setnodeb(node)
mobb = mob
node.newnetif(lte, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
node.newnetif(lte, ["%s/%s" % (prefix[i], prefix.prefixlen)])
nodes.append(node)
if i == 1:
_tmp, ns3dev = lte.findns3dev(node)

View file

@ -26,12 +26,11 @@ import logging
import optparse
import sys
import netaddr
import ns.core
from corens3.obj import Ns3Session
from corens3.obj import Ns3WifiNet
from core.nodes import ipaddress
def add_to_server(session):
"""
@ -60,11 +59,11 @@ def wifisession(opt):
wifi.setposition(30, 30, 0)
wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0))
prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
prefix = netaddr.IPNetwork("10.0.0.0/16")
nodes = []
for i in xrange(1, opt.numnodes + 1):
for i in range(1, opt.numnodes + 1):
node = session.addnode(name="n%d" % i)
node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
node.newnetif(wifi, ["%s/%s" % (prefix[i], prefix.prefixlen)])
nodes.append(node)
session.setupconstantmobility()
wifi.usecorepositions()

View file

@ -16,13 +16,12 @@ import optparse
import sys
from builtins import range
import netaddr
import ns.core
import ns.network
from corens3.obj import Ns3Session
from corens3.obj import Ns3WifiNet
from core.nodes import ipaddress
def add_to_server(session):
"""
@ -51,12 +50,12 @@ def wifisession(opt):
# for improved connectivity
wifi.phy.Set("RxGain", ns.core.DoubleValue(18.0))
prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
prefix = netaddr.IPNetwork("10.0.0.0/16")
services_str = "zebra|OSPFv3MDR|IPForward"
nodes = []
for i in range(1, opt.numnodes + 1):
node = session.addnode(name="n%d" % i)
node.newnetif(wifi, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
node.newnetif(wifi, ["%s/%s" % (prefix[i], prefix.prefixlen)])
nodes.append(node)
session.services.add_services(node, "router", services_str.split("|"))
session.services.boot_services(node)

View file

@ -14,11 +14,10 @@ import optparse
import sys
from builtins import range
import netaddr
from corens3.obj import Ns3Session
from corens3.obj import Ns3WimaxNet
from core.nodes import ipaddress
def wimaxsession(opt):
"""
@ -28,7 +27,7 @@ def wimaxsession(opt):
wimax = session.create_node(cls=Ns3WimaxNet, name="wlan1")
# wimax.wimax.EnableLogComponents()
prefix = ipaddress.Ipv4Prefix("10.0.0.0/16")
prefix = netaddr.IPNetwork("10.0.0.0/16")
# create one classifier for ICMP (protocol 1) traffic
# src port low/high, dst port low/high, protocol, priority
# classifier = (0, 65000, 0, 65000, 1, 1)
@ -38,7 +37,7 @@ def wimaxsession(opt):
node = session.addnode(name="n%d" % i)
if i == 1:
wimax.setbasestation(node)
node.newnetif(wimax, ["%s/%s" % (prefix.addr(i), prefix.prefixlen)])
node.newnetif(wimax, ["%s/%s" % (prefix[i], prefix.prefixlen)])
if i > 2:
wimax.addflow(nodes[-1], node, classifier, classifier)
nodes.append(node)