Return IP interface data.
3164
def get_interfaces_ip(self):
        ''''''

        def extract_ip_info(parsed_intf_dict):
            '''
            IPv4:
              - Primary IP is in the '<ip>' tag. If no v4 is configured the return value is 'N/A'.
              - Secondary IP's are in '<addr>'. If no secondaries, this field is not returned by
                the xmltodict.parse() method.

            IPv6:
              - All addresses are returned in '<addr6>'. If no v6 configured, this is not returned
                either by xmltodict.parse().

            Example of XML response for an intf with multiple IPv4 and IPv6 addresses:

            <response status="success">
              <result>
                <ifnet>
                  <entry>
                    <name>ethernet1/5</name>
                    <zone/>
                    <fwd>N/A</fwd>
                    <vsys>1</vsys>
                    <dyn-addr/>
                    <addr6>
                      <member>fe80::d61d:71ff:fed8:fe14/64</member>
                      <member>2001::1234/120</member>
                    </addr6>
                    <tag>0</tag>
                    <ip>169.254.0.1/30</ip>
                    <id>20</id>
                    <addr>
                      <member>1.1.1.1/28</member>
                    </addr>
                  </entry>
                  {...}
                </ifnet>
                <hw>
                  {...}
                </hw>
              </result>
            </response>
            '''
            intf = parsed_intf_dict['name']
            _ip_info = {intf: {}}

            v4_ip = parsed_intf_dict.get('ip')
            secondary_v4_ip = parsed_intf_dict.get('addr')
            v6_ip = parsed_intf_dict.get('addr6')

            if v4_ip != 'N/A':
                address, pref = v4_ip.split('/')
                _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)}

            if secondary_v4_ip is not None:
                members = secondary_v4_ip['member']
                if not isinstance(members, list):
                    # If only 1 secondary IP is present, xmltodict converts field to a string, else
                    # it converts it to a list of strings.
                    members = [members]
                for address in members:
                    address, pref = address.split('/')
                    _ip_info[intf].setdefault('ipv4', {})[address] = {'prefix_length': int(pref)}

            if v6_ip is not None:
                members = v6_ip['member']
                if not isinstance(members, list):
                    # Same "1 vs many -> string vs list of strings" comment.
                    members = [members]
                for address in members:
                    address, pref = address.split('/')
                    _ip_info[intf].setdefault('ipv6', {})[address] = {'prefix_length': int(pref)}

            # Reset dictionary if no addresses were found.
            if _ip_info == {intf: {}}:
                _ip_info = {}

            return _ip_info

        ip_interfaces = {}
        cmd = "<show><interface>all</interface></show>"

        self.device.op(cmd=cmd)
        interface_info_xml = xmltodict.parse(self.device.xml_root())
        interface_info_json = json.dumps(
            interface_info_xml['response']['result']['ifnet']['entry']
        )
        interface_info = json.loads(interface_info_json)

        if isinstance(interface_info, dict):
            # Same "1 vs many -> dict vs list of dicts" comment.
            interface_info = [interface_info]

        for interface_dict in interface_info:
            ip_info = extract_ip_info(interface_dict)
            if ip_info:
                ip_interfaces.update(ip_info)

        return ip_interfaces
97757
def _get_interface_ip(self, interface_name):
        
        ios_cfg = self._get_running_config()
        parse = HTParser(ios_cfg)
        children = parse.find_children("^interface %s" % interface_name)
        for line in children:
            if 'ip address' in line:
                ip_address = line.strip().split(' ')[2]
                LOG.debug("IP Address:%s", ip_address)
                return ip_address
        LOG.warning("Cannot find interface: %s", interface_name)
        return None
489431
def get_ip(data):
    '''
    
    '''
    try:
        ip = data.public_ips[0]
    except Exception:
        ip = data.private_ips[0]
    return ip
48682
def convert_to_ip(self):
        """"""
        if not self.is_data_loaded:
            self._import_data()
        if self.is_ip is False:
            for coll in self._data:
                coll.convert_to_ip()
        self._is_ip = True
1211849
def interfaces(self):
        
        if 'interfaces' not in self._cached_values:
            self._cached_values['interfaces'] = []
            for name, interface in six.iteritems(self.settings.INTERFACES):
                interface_name = 'interface_%s' % name
                # Hostname:port + unix socket
                try:
                    listen = self.config_parser.get(interface_name, 'Listen')
                except CONFIGPARSER_EXC:
                    listen = interface.get('LISTEN')
                try:
                    unix_socket = self.config_parser.get(
                        interface_name, 'UnixSocket')
                except CONFIGPARSER_EXC:
                    unix_socket = interface.get('UNIX_SOCKET')
                if not listen and not unix_socket:
                    raise ValueError(
                        'Interface MUST listen either on TCP '
                        'or UNIX socket or both')
                host, port = parse_host(listen) if listen else (None, None)
                # Processes
                try:
                    processes = self.config_parser.getint(
                        interface_name, 'Processes')
                except CONFIGPARSER_EXC:
                    processes = int(interface.get('PROCESSES', 1))
                # Urls
                try:
                    urls_obj_name = self.config_parser.get(
                        interface_name, 'Urls')
                except CONFIGPARSER_EXC:
                    urls_obj_name = interface.get('URLS', '')
                if urls_obj_name:
                    urls = import_object(urls_obj_name)
                else:
                    urls = ()

                self._cached_values['interfaces'].append(
                    self.Interface(
                        name, host, port, unix_socket, processes, urls)
                )
        return self._cached_values['interfaces']
866363
def _find_interfaces_ip(mac):
    '''
    
    '''
    try:
        mac = napalm_helpers.convert(napalm_helpers.mac, mac)
    except AddrFormatError:
        return ('', '', [])

    all_interfaces = _get_mine('net.interfaces')
    all_ipaddrs = _get_mine('net.ipaddrs')

    for device, device_interfaces in six.iteritems(all_interfaces):
        if not device_interfaces.get('result', False):
            continue
        for interface, interface_details in six.iteritems(device_interfaces.get('out', {})):
            try:
                interface_mac = napalm_helpers.convert(napalm_helpers.mac, interface_details.get('mac_address'))
            except AddrFormatError:
                continue
            if mac != interface_mac:
                continue
            interface_ipaddrs = all_ipaddrs.get(device, {}).get('out', {}).get(interface, {})
            ip_addresses = interface_ipaddrs.get('ipv4', {})
            ip_addresses.update(interface_ipaddrs.get('ipv6', {}))
            interface_ips = ['{0}/{1}'.format(ip_addr,
                                              addr_details.get('prefix_length', '32'))
                             for ip_addr, addr_details in six.iteritems(ip_addresses)]
            return device, interface, interface_ips

    return ('', '', [])
989369
def _read_ip_hextet(self):
        """"""
        _htet = self._read_fileng(4).hex()
        _vers = _htet[0]                    # version number (6)
        _tcls = int(_htet[0:2], base=16)    # traffic class
        _flow = int(_htet[2:], base=16)     # flow label

        return (_vers, _tcls, _flow)
599073
def get_my_ips():
    """"""
    ips = list()
    if not os.path.exists("/sys/class/net"): # not linux
        return ['127.0.0.1']
    for ifdev in os.listdir("/sys/class/net"):
        if ifdev == "lo":
            continue
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            ips.append(socket.inet_ntoa(fcntl.ioctl(
                sock.fileno(),
                0x8915,  # SIOCGIFADDR
                struct.pack('256s', ifdev[:15].encode())
            )[20:24]))
        except OSError:
            pass
    return ips
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)
1034148
def ethernet_interfaces(self):
        """"""
        return ethernet_interface.EthernetInterfaceCollection(
            self._conn,
            self._get_hpe_sub_resource_collection_path('EthernetInterfaces'),
            redfish_version=self.redfish_version)
1206996
def get_interfaces(zone, permanent=True):
    '''
    
    '''
    cmd = '--zone={0} --list-interfaces'.format(zone)

    if permanent:
        cmd += ' --permanent'

    return __firewall_cmd(cmd).split()
902552
def get_ips(v6=False):
    """"""
    res = {}
    for iface in six.itervalues(IFACES):
        ips = []
        for ip in iface.ips:
            if v6 and ":" in ip:
                ips.append(ip)
            elif not v6 and ":" not in ip:
                ips.append(ip)
        res[iface] = ips
    return res
402401
def interface_ip(iface):
    '''
    
    '''
    iface_info, error = _get_iface_info(iface)

    if error is False:
        inet = iface_info.get(iface, {}).get('inet', None)
        return inet[0].get('address', '') if inet else ''
    else:
        return error
106039
def get_lan_ip(interface="default"):
    if sys.version_info < (3, 0, 0):
        if type(interface) == str:
            interface = unicode(interface)
    else:
        if type(interface) == bytes:
            interface = interface.decode("utf-8")

    # Get ID of interface that handles WAN stuff.
    default_gateway = get_default_gateway(interface)
    gateways = netifaces.gateways()
    wan_id = None
    if netifaces.AF_INET in gateways:
        gw_list = gateways[netifaces.AF_INET]
        for gw_info in gw_list:
            if gw_info[0] == default_gateway:
                wan_id = gw_info[1]
                break

    # Find LAN IP of interface for WAN stuff.
    interfaces = netifaces.interfaces()
    if wan_id in interfaces:
        families = netifaces.ifaddresses(wan_id)
        if netifaces.AF_INET in families:
            if_info_list = families[netifaces.AF_INET]
            for if_info in if_info_list:
                if "addr" in if_info:
                    return if_info["addr"]

    
    if platform.system() == "Linux":
        if ip is not None:
            return ip.routes["8.8.8.8"]["prefsrc"]

    return None
954346
def _get_ipv4_addrs(self):
        
        addrs = self._get_addrs()
        ipv4addrs = addrs.get(netifaces.AF_INET)
        if not ipv4addrs:
            return {}
        return ipv4addrs[0]
613683
def ips(self):
        """"""
        r = []
        names = ['X_FORWARDED_FOR', 'CLIENT_IP', 'X_REAL_IP', 'X_FORWARDED', 
               'X_CLUSTER_CLIENT_IP', 'FORWARDED_FOR', 'FORWARDED', 'VIA',
               'REMOTE_ADDR']

        for name in names:
            vs = self.get_header(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

            vs = self.environ.get(name, '')
            if vs:
                r.extend(map(lambda v: v.strip(), vs.split(',')))

        return r
911989
def GetForwardedIps(self, interface, interface_ip=None):
    
    try:
      ips = netifaces.ifaddresses(interface)
      ips = ips[netifaces.AF_INET]
    except (ValueError, IndexError):
      return []
    forwarded_ips = []
    for ip in ips:
      if ip['addr'] != interface_ip:
        full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits())
        forwarded_ips.append(full_addr)
    return self.ParseForwardedIps(forwarded_ips)