Return parsed IPv4 info from ifconfig(8) binary.
551217
def ifconfig_inet (iface):
    """"""
    res = pipecmd(["ifconfig", iface], ["grep", "inet "])
    info = {}
    lastpart = None
    for part in res.split():
        # Linux systems have prefixes for each value
        if part.startswith("addr:"):
            info["address"] = part[5:]
        elif part.startswith("Bcast:"):
            info["broadcast"] = part[6:]
        elif part.startswith("Mask:"):
            info["netmask"] = part[5:]
        elif lastpart == "inet":
            info["address"] = part
        elif lastpart in ("netmask", "broadcast"):
            info[lastpart] = part
        lastpart = part
    return info
695558
def _get_afi(self, ip):
        

        parts = unicode(ip).split("/")
        if len(parts) == 1:
            # just an address
            if self._is_ipv4(ip):
                return 4
            elif self._is_ipv6(ip):
                return 6
            else:
                return None
        elif len(parts) == 2:
            # a prefix!
            try:
                pl = int(parts[1])
            except ValueError:
                # if casting parts[1] to int failes, this is not a prefix..
                return None

            if self._is_ipv4(parts[0]):
                if pl >= 0 and pl <= 32:
                    # prefix mask must be between 0 and 32
                    return 4
                # otherwise error
                return None
            elif self._is_ipv6(parts[0]):
                if pl >= 0 and pl <= 128:
                    # prefix mask must be between 0 and 128
                    return 6
                # otherwise error
                return None
            else:
                return None
        else:
            # more than two parts.. this is neither an address or a prefix
            return None
940452
def _get_tcpip_interface_info(interface):
    '''
    
    '''
    base_information = _get_base_interface_info(interface)
    if base_information['ipv4']['requestmode'] == 'static':
        settings = _load_config(interface.name, ['IP_Address', 'Subnet_Mask', 'Gateway', 'DNS_Address'])
        base_information['ipv4']['address'] = settings['IP_Address']
        base_information['ipv4']['netmask'] = settings['Subnet_Mask']
        base_information['ipv4']['gateway'] = settings['Gateway']
        base_information['ipv4']['dns'] = [settings['DNS_Address']]
    elif base_information['up']:
        base_information['ipv4']['address'] = interface.sockaddrToStr(interface.addr)
        base_information['ipv4']['netmask'] = interface.sockaddrToStr(interface.netmask)
        base_information['ipv4']['gateway'] = '0.0.0.0'
        base_information['ipv4']['dns'] = _get_dns_info()
        with salt.utils.files.fopen('/proc/net/route', 'r') as route_file:
            pattern = re.compile(r'^{interface}\t[0]{{8}}\t([0-9A-Z]{{8}})'.format(interface=interface.name),
                                 re.MULTILINE)
            match = pattern.search(route_file.read())
            iface_gateway_hex = None if not match else match.group(1)
        if iface_gateway_hex is not None and len(iface_gateway_hex) == 8:
            base_information['ipv4']['gateway'] = '.'.join([str(int(iface_gateway_hex[i:i + 2], 16))
                                                            for i in range(6, -1, -2)])
    return base_information
978031
def addr_info(addr):
    

    # If it's a string, it's in the UNIX family
    if isinstance(addr, basestring):
        return socket.AF_UNIX

    # Verify that addr is a tuple
    if not isinstance(addr, collections.Sequence):
        raise ValueError("address is not a tuple")

    # Make sure it has at least 2 fields
    if len(addr) < 2:
        raise ValueError("cannot understand address")

    # Sanity-check the port number
    if not (0 <= addr[1] < 65536):
        raise ValueError("cannot understand port number")

    # OK, first field should be an IP address; suck it out...
    ipaddr = addr[0]

    # Empty string means IPv4
    if not ipaddr:
        if len(addr) != 2:
            raise ValueError("cannot understand address")

        return socket.AF_INET

    # See if it's valid...
    if netaddr.valid_ipv6(ipaddr):
        if len(addr) > 4:
            raise ValueError("cannot understand address")

        return socket.AF_INET6
    elif netaddr.valid_ipv4(ipaddr):
        if len(addr) != 2:
            raise ValueError("cannot understand address")

        return socket.AF_INET

    raise ValueError("cannot understand address")
111187
def _interfaces_ipconfig(out):
    '''
    
    '''
    ifaces = dict()
    iface = None
    adapter_iface_regex = re.compile(r'adapter (\S.+):$')

    for line in out.splitlines():
        if not line:
            continue
        # TODO what does Windows call Infiniband and 10/40gige adapters
        if line.startswith('Ethernet'):
            iface = ifaces[adapter_iface_regex.search(line).group(1)]
            iface['up'] = True
            addr = None
            continue
        if iface:
            key, val = line.split(',', 1)
            key = key.strip(' .')
            val = val.strip()
            if addr and key == 'Subnet Mask':
                addr['netmask'] = val
            elif key in ('IP Address', 'IPv4 Address'):
                if 'inet' not in iface:
                    iface['inet'] = list()
                addr = {'address': val.rstrip('(Preferred)'),
                        'netmask': None,
                        'broadcast': None}  # TODO find the broadcast
                iface['inet'].append(addr)
            elif 'IPv6 Address' in key:
                if 'inet6' not in iface:
                    iface['inet'] = list()
                # XXX What is the prefixlen!?
                addr = {'address': val.rstrip('(Preferred)'),
                        'prefixlen': None}
                iface['inet6'].append(addr)
            elif key == 'Physical Address':
                iface['hwaddr'] = val
            elif key == 'Media State':
                # XXX seen used for tunnel adaptors
                # might be useful
                iface['up'] = (val != 'Media disconnected')
844448
def _in6_getifaddr(ifname):
    

    # Get the output of ifconfig
    try:
        f = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError:
        log_interactive.warning("Failed to execute ifconfig.")
        return []

    # Iterate over lines and extract IPv6 addresses
    ret = []
    for line in f:
        if "inet6" in line:
            addr = line.rstrip().split(None, 2)[1]  # The second element is the IPv6 address  # noqa: E501
        else:
            continue
        if '%' in line:  # Remove the interface identifier if present
            addr = addr.split("%", 1)[0]

        # Check if it is a valid IPv6 address
        try:
            inet_pton(socket.AF_INET6, addr)
        except (socket.error, ValueError):
            continue

        # Get the scope and keep the address
        scope = in6_getscope(addr)
        ret.append((addr, scope, ifname))

    return ret
613703
def __get_vpc_info(self, ifarr):
        '''
        
        '''
        if (self.vpc_vbtbl == None):
            self.vpc_vbtbl = self.snmpobj.get_bulk(OID_VPC_PEERLINK_IF)
        if ((self.vpc_vbtbl == None) | (len(self.vpc_vbtbl) == 0)):
            return (None, None)
        domain = natlas_snmp.get_last_oid_token(self.vpc_vbtbl[0][0][0])
        ifidx  = str(self.vpc_vbtbl[0][0][1])
        ifname = self.snmpobj.cache_lookup(ifarr, OID_ETH_IF_DESC + '.' + ifidx)
        ifname = self.shorten_port_name(ifname)
        return (domain, ifname)
545526
def __getIP(self, public):
        """"""

        maybeNot = (lambda x: x) if public else (lambda x: not x)
        nets_id = [net.id for net in self.networks if maybeNot(net.isPublic())]
        for s in self.systems:
            i = 0
            while True:
                value = s.getValue("net_interface.%d.connection" % i)
                if not value:
                    break
                if value in nets_id:
                    ip = s.getValue("net_interface.%d.ip" % i)
                    if ip:
                        return ip
                i += 1
        return None
939489
def get_ipv4_range(start_addr=None, end_addr=None, return_fields=None, **api_opts):
    '''
    
    '''
    infoblox = _get_infoblox(**api_opts)
    return infoblox.get_range(start_addr, end_addr, return_fields)
526659
def get_if_raw_addr(ifname):
    """"""  # noqa: E501

    # Get ifconfig output
    try:
        fd = os.popen("%s %s" % (conf.prog.ifconfig, ifname))
    except OSError as msg:
        warning("Failed to execute ifconfig: (%s)", msg)
        return b"\0\0\0\0"

    # Get IPv4 addresses
    addresses = [l for l in fd if l.find("inet ") >= 0]
    if not addresses:
        warning("No IPv4 address found on %s !", ifname)
        return b"\0\0\0\0"

    # Pack the first address
    address = addresses[0].split(' ')[1]
    if '/' in address:  # NetBSD 8.0
        address = address.split("/")[0]
    return socket.inet_pton(socket.AF_INET, address)
205676
def ipv4_reassembly(packet, *, count=NotImplemented):
    """"""
    if 'IP' in packet:
        ipv4 = packet['IP']
        if ipv4.flags.DF:       # dismiss not fragmented packet
            return False, None
        data = dict(
            bufid=(
                ipaddress.ip_address(ipv4.src),         # source IP address
                ipaddress.ip_address(ipv4.dst),         # destination IP address
                ipv4.id,                                # identification
                TP_PROTO.get(ipv4.proto).name,          # payload protocol type
            ),
            num=count,                                  # original packet range number
            fo=ipv4.frag,                               # fragment offset
            ihl=ipv4.ihl,                               # internet header length
            mf=bool(ipv4.flags.MF),                     # more fragment flag
            tl=ipv4.len,                                # total length, header includes
            header=bytearray(ipv4.raw_packet_cache),    # raw bytearray type header
            payload=bytearray(bytes(ipv4.payload)),     # raw bytearray type payload
        )
        return True, data
    return False, None
448959
def interfaces_info():
    
    def replace(value):
        if value == netifaces.AF_LINK:
            return 'link'
        if value == netifaces.AF_INET:
            return 'ipv4'
        if value == netifaces.AF_INET6:
            return 'ipv6'
        return value

    results = {}
    for iface in netifaces.interfaces():
        addrs = netifaces.ifaddresses(iface)
        results[iface] = {replace(k): v for k, v in addrs.items()}

    return results
662141
def get_interfaces_ip(self):
        """"""
        interfaces_ip = {}

        interface_table = junos_views.junos_ip_interfaces_table(self.device)
        interface_table.get()
        interface_table_items = interface_table.items()

        _FAMILY_VMAP_ = {
            "inet": "ipv4",
            "inet6": "ipv6"
            # can add more mappings
        }
        _FAMILY_MAX_PREFIXLEN = {"inet": 32, "inet6": 128}

        for interface_details in interface_table_items:
            ip_network = interface_details[0]
            ip_address = ip_network.split("/")[0]
            address = napalm.base.helpers.convert(
                napalm.base.helpers.ip, ip_address, ip_address
            )
            try:
                interface_details_dict = dict(interface_details[1])
                family_raw = interface_details_dict.get("family")
                interface = py23_compat.text_type(
                    interface_details_dict.get("interface")
                )
            except ValueError:
                continue
            prefix = napalm.base.helpers.convert(
                int, ip_network.split("/")[-1], _FAMILY_MAX_PREFIXLEN.get(family_raw)
            )
            family = _FAMILY_VMAP_.get(family_raw)
            if not family or not interface:
                continue
            if interface not in interfaces_ip.keys():
                interfaces_ip[interface] = {}
            if family not in interfaces_ip[interface].keys():
                interfaces_ip[interface][family] = {}
            if address not in interfaces_ip[interface][family].keys():
                interfaces_ip[interface][family][address] = {}
            interfaces_ip[interface][family][address]["prefix_length"] = prefix

        return interfaces_ip
690330
def parse(self, ifconfig=None):  # noqa: max-complexity=12
        
        if not ifconfig:
            ifconfig, __, __ = exec_cmd(self.get_command())
        self.ifconfig_data = ifconfig
        cur = None
        patterns = self.get_patterns()
        for line in self.ifconfig_data.splitlines():
            for pattern in patterns:
                m = re.match(pattern, line)
                if not m:
                    continue
                groupdict = m.groupdict()
                # Special treatment to trigger which interface we're
                # setting for if 'device' is in the line.  Presumably the
                # device of the interface is within the first line of the
                # device block.
                if 'device' in groupdict:
                    cur = groupdict['device']
                    self.add_device(cur)
                elif cur is None:
                    raise RuntimeError(
                        "Got results that don't belong to a device"
                    )

                for k, v in groupdict.items():
                    if k in self._interfaces[cur]:
                        if self._interfaces[cur][k] is None:
                            self._interfaces[cur][k] = v
                        elif hasattr(self._interfaces[cur][k], 'append'):
                            self._interfaces[cur][k].append(v)
                        elif self._interfaces[cur][k] == v:
                            # Silently ignore if the it's the same value as last. Example: Multiple
                            # inet4 addresses, result in multiple netmasks. Cardinality mismatch
                            continue
                        else:
                            raise RuntimeError(
                                "Tried to add {}={} multiple times to {}, it was already: {}".format(
                                    k,
                                    v,
                                    cur,
                                    self._interfaces[cur][k]
                                )
                            )
                    else:
                        self._interfaces[cur][k] = v

        # Copy the first 'inet4' ip address to 'inet' for backwards compatibility
        for device, device_dict in self._interfaces.items():
            if len(device_dict['inet4']) > 0:
                device_dict['inet'] = device_dict['inet4'][0]

        # fix it up
        self._interfaces = self.alter(self._interfaces)
579654
def info():
    """"""
    try:
        platform_info = {
            'system': platform.system(),
            'release': platform.release(),
        }
    except IOError:
        platform_info = {
            'system': 'Unknown',
            'release': 'Unknown',
        }

    implementation_info = _implementation()
    urllib3_info = {'version': urllib3.__version__}
    chardet_info = {'version': chardet.__version__}

    pyopenssl_info = {
        'version': None,
        'openssl_version': '',
    }
    if OpenSSL:
        pyopenssl_info = {
            'version': OpenSSL.__version__,
            'openssl_version': '%x' % OpenSSL.SSL.OPENSSL_VERSION_NUMBER,
        }
    cryptography_info = {
        'version': getattr(cryptography, '__version__', ''),
    }
    idna_info = {
        'version': getattr(idna, '__version__', ''),
    }

    system_ssl = ssl.OPENSSL_VERSION_NUMBER
    system_ssl_info = {
        'version': '%x' % system_ssl if system_ssl is not None else ''
    }

    return {
        'platform': platform_info,
        'implementation': implementation_info,
        'system_ssl': system_ssl_info,
        'using_pyopenssl': pyopenssl is not None,
        'pyOpenSSL': pyopenssl_info,
        'urllib3': urllib3_info,
        'chardet': chardet_info,
        'cryptography': cryptography_info,
        'idna': idna_info,
        'requests': {
            'version': requests_version,
        },
    }
574449
def bin_to_text(ip):
    
    if len(ip) == 4:
        return ipv4_to_str(ip)
    elif len(ip) == 16:
        return ipv6_to_str(ip)
    else:
        raise struct.error('Invalid ip address length: %s' % len(ip))
88175
def cli(env, ip_version):
    """"""

    mgr = SoftLayer.NetworkManager(env.client)

    table = formatting.Table(['id', 'ip', 'assigned', 'target'])

    version = None
    if ip_version == 'v4':
        version = 4
    elif ip_version == 'v6':
        version = 6

    ips = mgr.list_global_ips(version=version)

    for ip_address in ips:
        assigned = 'No'
        target = 'None'
        if ip_address.get('destinationIpAddress'):
            dest = ip_address['destinationIpAddress']
            assigned = 'Yes'
            target = dest['ipAddress']
            virtual_guest = dest.get('virtualGuest')
            if virtual_guest:
                target += (' (%s)'
                           % virtual_guest['fullyQualifiedDomainName'])
            elif ip_address['destinationIpAddress'].get('hardware'):
                target += (' (%s)'
                           % dest['hardware']['fullyQualifiedDomainName'])

        table.add_row([ip_address['id'],
                       ip_address['ipAddress']['ipAddress'],
                       assigned,
                       target])
    env.fout(table)