query
stringlengths
9
60
language
stringclasses
1 value
code
stringlengths
105
25.7k
url
stringlengths
91
217
get current ip address
python
def get_ip(): """ Get the default local IP address. From: https://stackoverflow.com/a/28950776 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: s.connect(('10.255.255.255', 1)) ip = s.getsockname()[0] except (socket.error, IndexError): ip = '127.0.0.1' finally: s.close() return ip
https://github.com/mozilla-iot/webthing-python/blob/65d467c89ed79d0bbc42b8b3c8f9e5a320edd237/webthing/utils.py#L17-L32
get current ip address
python
def get_ip_address(ifname): """ Hack to get IP address from the interface """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', ifname[:15]) )[20:24])
https://github.com/ska-sa/montblanc/blob/8a2e742e7500bcc6196489b735f87b233075dd2d/montblanc/impl/rime/tensorflow/helpers/cluster_gen.py#L26-L34
get current ip address
python
def get_ip_address(): """Simple utility to get host IP address.""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("8.8.8.8", 80)) ip_address = s.getsockname()[0] except socket_error as sockerr: if sockerr.errno != errno.ENETUNREACH: raise sockerr ip_address = socket.gethostbyname(socket.getfqdn()) finally: s.close() return ip_address
https://github.com/yahoo/TensorFlowOnSpark/blob/5e4b6c185ab722fd0104ede0377e1149ea8d6f7c/tensorflowonspark/util.py#L41-L54
get current ip address
python
def get_local_ip_address(target): """ Get the local ip address to access one specific target. """ ip_adr = '' try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect((target, 8000)) ip_adr = s.getsockname()[0] s.close() except: pass return ip_adr
https://github.com/ronhanson/python-tbx/blob/87f72ae0cadecafbcd144f1e930181fba77f6b83/tbx/network.py#L24-L37
get current ip address
python
def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ remote_addr = request.META.get('REMOTE_ADDR', '') if remote_addr and is_valid_ip(remote_addr): return remote_addr.strip() return '127.0.0.1'
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L32-L38
get current ip address
python
def get_my_ip(): """Returns this computers IP address as a string.""" ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1] return ip.strip()
https://github.com/piface/pifacedigitalio/blob/d231a82bdb55d5f57f44ba7aec00bfd6c0b9a9d4/examples/simplewebcontrol.py#L72-L75
get current ip address
python
def get_ip(source='aws'): ''' a method to get current public ip address of machine ''' if source == 'aws': source_url = 'http://checkip.amazonaws.com/' else: raise Exception('get_ip currently only supports queries to aws') import requests try: response = requests.get(url=source_url) except Exception as err: from labpack.handlers.requests import handle_requests from requests import Request request_object = Request(method='GET', url=source_url) request_details = handle_requests(request_object) raise Exception(request_details['error']) current_ip = response.content.decode() current_ip = current_ip.strip() return current_ip
https://github.com/collectiveacuity/labPack/blob/52949ece35e72e3cc308f54d9ffa6bfbd96805b8/labpack/records/ip.py#L5-L26
get current ip address
python
def get_ip4(): """ return all ip v4 address of current computer :return: """ addresses = [] shell_cmd = "ifconfig | awk '/inet addr/{print substr($2,6)}'" proc = subprocess.Popen([shell_cmd], stdout=subprocess.PIPE, shell=True) (out, err) = proc.communicate() ip_addresses = out.split('\n') for addr in ip_addresses: if re.match(r'\d{1,4}\.\d{1,4}\.\d{1,4}\.\d{1,4}', addr): addresses.append(addr) return addresses
https://github.com/telminov/sw-python-utils/blob/68f976122dd26a581b8d833c023f7f06542ca85c/swutils/network.py#L6-L20
get current ip address
python
def get_ip(interface=0): """This method return the IP address :param interface: (int) Interface number (e.g. 0 for eth0) :return: (str) IP address or None """ log = logging.getLogger(mod_logger + '.get_ip') log.info('Getting the IP address for this system...') ip_address = None try: log.info('Attempting to get IP address by hostname...') ip_address = socket.gethostbyname(socket.gethostname()) except socket.error: log.info('Unable to get IP address for this system using hostname, ' 'using a bash command...') command = 'ip addr show eth%s | grep inet | grep -v inet6 | ' \ 'awk \'{ print $2 }\' | cut -d/ -f1 ' \ '>> /root/ip' % interface try: log.info('Running command: %s', command) subprocess.check_call(command, shell=True) except(OSError, subprocess.CalledProcessError): _, ex, trace = sys.exc_info() msg = 'Unable to get the IP address of this system\n{e}'.format( e=str(ex)) log.error(msg) raise CommandError, msg, trace else: ip_file = '/root/ip' log.info('Command executed successfully, pulling IP address from ' 'file: %s', ip_file) if os.path.isfile(ip_file): with open(ip_file, 'r') as f: for line in f: ip_address = line.strip() log.info('Found IP address from file: %s', ip_address) else: msg = 'File not found: {f}'.format(f=ip_file) log.error(msg) raise CommandError(msg) log.info('Returning IP address: %s', ip_address) return ip_address
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L677-L719
get current ip address
python
def _get_ip_address(self, request): """Get the remote ip address the request was generated from. """ ipaddr = request.META.get("HTTP_X_FORWARDED_FOR", None) if ipaddr: # X_FORWARDED_FOR returns client1, proxy1, proxy2,... return ipaddr.split(",")[0].strip() return request.META.get("REMOTE_ADDR", "")
https://github.com/aschn/drf-tracking/blob/1910f413bd5166bbeaf694c7c0101f331af4f47d/rest_framework_tracking/base_mixins.py#L100-L106
get current ip address
python
def get_ip_address(self, x, y): """Get the IP address of a particular SpiNNaker chip's Ethernet link. Returns ------- str or None The IPv4 address (as a string) of the chip's Ethernet link or None if the chip does not have an Ethernet connection or the link is currently down. """ chip_info = self.get_chip_info(x=x, y=y) return chip_info.ip_address if chip_info.ethernet_up else None
https://github.com/project-rig/rig/blob/3a3e053d3214899b6d68758685835de0afd5542b/rig/machine_control/machine_controller.py#L488-L499
get current ip address
python
def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') ip_address = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') if x_forwarded_for and ',' not in x_forwarded_for: if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for): ip_address = x_forwarded_for.strip() else: ips = [ip.strip() for ip in x_forwarded_for.split(',')] for ip in ips: if ip.startswith(PRIVATE_IPS_PREFIX): continue elif not is_valid_ip(ip): continue else: ip_address = ip break if not ip_address: x_real_ip = request.META.get('HTTP_X_REAL_IP', '') if x_real_ip: if not x_real_ip.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_real_ip): ip_address = x_real_ip.strip() if not ip_address: remote_addr = request.META.get('REMOTE_ADDR', '') if remote_addr: if not remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr): ip_address = remote_addr.strip() if remote_addr.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(remote_addr): ip_address = remote_addr.strip() if not ip_address: ip_address = '127.0.0.1' return ip_address
https://github.com/robromano/django-adminrestrict/blob/f05fd21e49677731e3d291da956b84bcac9a5c69/adminrestrict/middleware.py#L44-L78
get current ip address
python
def get_ip(request): """ get the ip address from the request """ if config.BEHIND_REVERSE_PROXY: ip_address = request.META.get(config.REVERSE_PROXY_HEADER, '') ip_address = ip_address.split(",", 1)[0].strip() if ip_address == '': ip_address = get_ip_address_from_request(request) else: ip_address = get_ip_address_from_request(request) return ip_address
https://github.com/kencochrane/django-defender/blob/e3e547dbb83235e0d564a6d64652c7df00412ff2/defender/utils.py#L41-L50
get current ip address
python
def get_ip(): """Return machine's origin IP address. """ try: r = requests.get(HTTPBIN_URL) ip, _ = r.json()['origin'].split(',') return ip if r.status_code == 200 else None except requests.exceptions.ConnectionError: return None
https://github.com/pv8/noipy/blob/e37342505a463d02ea81b18a060eb7d84a5d1c27/noipy/utils.py#L24-L32
get current ip address
python
async def get_ip(self) -> Union[IPv4Address, IPv6Address]: """ get ip address of client :return: """ xff = await self.get_x_forwarded_for() if xff: return xff[0] ip_addr = self._request.transport.get_extra_info('peername')[0] return ip_address(ip_addr)
https://github.com/fy0/slim/blob/9951a910750888dbe7dd3e98acae9c40efae0689/slim/base/view.py#L128-L136
get current ip address
python
def getip(): """ getip() Returns the IP address of the computer. Helpful for those hosts that might sit behind gateways and report a hostname that is a little strange (I'm looking at you oco3-sim1). """ return [(s.connect(('8.8.8.8', 80)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]
https://github.com/NASA-AMMOS/AIT-Core/blob/9d85bd9c738e7a6a6fbdff672bea708238b02a3a/ait/core/gds.py#L228-L236
get current ip address
python
def _get_ip(self, interface): """ Returns the interface's IPv4 address if device exists and has a valid ip address. Otherwise, returns an empty string """ if interface in ni.interfaces(): addresses = ni.ifaddresses(interface) if ni.AF_INET in addresses: return addresses[ni.AF_INET][0]["addr"] return ""
https://github.com/ultrabug/py3status/blob/4c105f1b44f7384ca4f7da5f821a47e468c7dee2/py3status/modules/wwan_status.py#L168-L177
get current ip address
python
def ip_address(): """Get the IP address used for public connections.""" s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # 8.8.8.8 is the google public DNS s.connect(("8.8.8.8", 53)) ip = s.getsockname()[0] s.close() return ip
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L155-L162
get current ip address
python
def get_current_ip(self): """ Get the current IP Tor is using. :returns str :raises TorIpError """ response = get(ICANHAZIP, proxies={"http": self.local_http_proxy}) if response.ok: return self._get_response_text(response) raise TorIpError("Failed to get the current Tor IP")
https://github.com/DusanMadar/TorIpChanger/blob/c2c4371e16f239b01ea36b82d971612bae00526d/toripchanger/changer.py#L82-L94
get current ip address
python
def get_my_ip(): """ Asks and external server what your ip appears to be (useful is running from behind a NAT/wifi router). Of course, incoming port to the router must be forwarded correctly. """ if 'OPENSHIFT_SECRET_TOKEN' in os.environ: my_ip = os.environ['OPENSHIFT_APP_DNS'] else: my_ip = json.load(urllib2.urlopen( 'http://httpbin.org/ip' ))['origin'].split(',')[0] return my_ip
https://github.com/NYUCCL/psiTurk/blob/7170b992a0b5f56c165929cf87b3d3a1f3336c36/psiturk/utils.py#L5-L17
get current ip address
python
def get_ipaddress(self, name, retries=3, delay=3): '''get the ip_address of an inserted instance. Will try three times with delay to give the instance time to start up. Parameters ========== name: the name of the instance to get the ip address for. retries: the number of retries before giving up delay: the delay between retry Note from @vsoch: this function is pretty nasty. ''' for rr in range(retries): # Retrieve list of instances instances = self._get_instances() for instance in instances['items']: if instance['name'] == name: # Iterate through network interfaces for network in instance['networkInterfaces']: if network['name'] == 'nic0': # Access configurations for subnet in network['accessConfigs']: if subnet['name'] == 'External NAT': if 'natIP' in subnet: return subnet['natIP'] sleep(delay) bot.warning('Did not find IP address, check Cloud Console!')
https://github.com/singularityhub/sregistry-cli/blob/abc96140a1d15b5e96d83432e1e0e1f4f8f36331/sregistry/main/google_storage/build.py#L197-L229
get current ip address
python
def ip_address(self): """ Public ip_address """ ip = None for eth in self.networks['v4']: if eth['type'] == 'public': ip = eth['ip_address'] break if ip is None: raise ValueError("No public IP found") return ip
https://github.com/changhiskhan/poseidon/blob/6d1cecbe02f1e510dd185fe23f88f7af35eb737f/poseidon/droplet.py#L485-L496
get current ip address
python
def get_ip(self): """ Retrieve a complete list of bought ip address related only to PRO Servers. It create an internal object (Iplist) representing all of the ips object iterated form the WS. @param: None @return: None """ json_scheme = self.gen_def_json_scheme('GetPurchasedIpAddresses') json_obj = self.call_method_post(method='GetPurchasedIpAddresses ', json_scheme=json_scheme) self.iplist = IpList() for ip in json_obj['Value']: r = Ip() r.ip_addr = ip['Value'] r.resid = ip['ResourceId'] r.serverid = ip['ServerId'] if 'None' not in str(ip['ServerId']) else None self.iplist.append(r)
https://github.com/Arubacloud/pyArubaCloud/blob/ec4aecd8ca342b1e1a4f16b7cc87cb5e697cfcd4/ArubaCloud/PyArubaAPI.py#L325-L341
get current ip address
python
def get_ip(host): ''' Return the ip associated with the named host CLI Example: .. code-block:: bash salt '*' hosts.get_ip <hostname> ''' hosts = _list_hosts() if not hosts: return '' # Look for the op for addr in hosts: if host in hosts[addr]: return addr # ip not found return ''
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/hosts.py#L99-L117
get current ip address
python
def get_ips(self, instance_id): """Retrieves all IP addresses associated to a given instance. :return: tuple (IPs) """ self._init_os_api() instance = self._load_instance(instance_id) try: ip_addrs = set([self.floating_ip]) except AttributeError: ip_addrs = set([]) for ip_addr in sum(instance.networks.values(), []): ip_addrs.add(ip_addr) log.debug("VM `%s` has IP addresses %r", instance_id, ip_addrs) return list(ip_addrs)
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/openstack.py#L622-L636
get current ip address
python
def get_ip(self, access='public', addr_family=None, strict=None): """ Return the server's IP address. Params: - addr_family: IPv4, IPv6 or None. None prefers IPv4 but will return IPv6 if IPv4 addr was not available. - access: 'public' or 'private' """ if addr_family not in ['IPv4', 'IPv6', None]: raise Exception("`addr_family` must be 'IPv4', 'IPv6' or None") if access not in ['private', 'public']: raise Exception("`access` must be 'public' or 'private'") if not hasattr(self, 'ip_addresses'): self.populate() # server can have several public or private IPs ip_addrs = [ ip_addr for ip_addr in self.ip_addresses if ip_addr.access == access ] # prefer addr_family (or IPv4 if none given) preferred_family = addr_family if addr_family else 'IPv4' for ip_addr in ip_addrs: if ip_addr.family == preferred_family: return ip_addr.address # any IP (of the right access) will do if available and addr_family is None return ip_addrs[0].address if ip_addrs and not addr_family else None
https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/server.py#L402-L433
get current ip address
python
def get_reserved_ip_address(self, name): ''' Retrieves information about the specified reserved IP address. name: Required. Name of the reserved IP address. ''' _validate_not_none('name', name) return self._perform_get(self._get_reserved_ip_path(name), ReservedIP)
https://github.com/Azure/azure-sdk-for-python/blob/d7306fde32f60a293a7567678692bdad31e4b667/azure-servicemanagement-legacy/azure/servicemanagement/servicemanagementservice.py#L1286-L1294
get current ip address
python
def get_ipaddr(self): ''' Return the best IP address for this device. Returns the first matching IP: - Lowest Loopback interface - Lowest SVI address/known IP ''' # Loopbacks - first interface if (len(self.loopbacks)): ips = self.loopbacks[0].ips if (len(ips)): ips.sort() return util.strip_slash_masklen(ips[0]) # SVIs + all known - lowest address ips = [] for svi in self.svis: ips.extend(svi.ip) ips.extend(self.ip) if (len(ips)): ips.sort() return util.strip_slash_masklen(ips[0]) return ''
https://github.com/MJL85/natlas/blob/5e7ae3cc7b5dd7ad884fa2b8b93bbdd9275474c4/natlas/node.py#L713-L736
get current ip address
python
def ip(args): """ %prog describe Show current IP address from JSON settings. """ if len(args) != 0: sys.exit(not p.print_help()) s = InstanceSkeleton() print("IP address:", s.private_ip_address, file=sys.stderr) print("Instance type:", s.instance_type, file=sys.stderr)
https://github.com/tanghaibao/jcvi/blob/d2e31a77b6ade7f41f3b321febc2b4744d1cdeca/jcvi/utils/aws.py#L121-L132
get current ip address
python
def ip(): """Show ip address.""" ok, err = _hack_ip() if not ok: click.secho(click.style(err, fg='red')) sys.exit(1) click.secho(click.style(err, fg='green'))
https://github.com/cls1991/ng/blob/e975fa6c6e39067737ba4e54ee8eec605bb94b86/ng.py#L153-L159
get current ip address
python
def getLocalIPaddress(): """visible to other machines on LAN""" try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('google.com', 0)) my_local_ip = s.getsockname()[0] # takes ~0.005s #from netifaces import interfaces, ifaddresses, AF_INET #full solution in the event of multiple NICs (network interface cards) on the PC #def ip4_addresses(): # ip_list = [] # for interface in interfaces(): # for link in ifaddresses(interface)[AF_INET]: # If IPv6 addresses are needed instead, use AF_INET6 instead of AF_INET # ip_list.append(link['addr']) # return ip_list except Exception: my_local_ip = None return my_local_ip
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/ipAddresses.py#L32-L48
get current ip address
python
def get_ip_addr(self) -> str: '''Show IP Address.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'ip', '-f', 'inet', 'addr', 'show', 'wlan0') ip_addr = re.findall( r"\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b", output) if not ip_addr: raise ConnectionError( 'The device is not connected to WLAN or not connected via USB.') return ip_addr[0]
https://github.com/fjwCode/cerium/blob/f6e06e0dcf83a0bc924828e9d6cb81383ed2364f/cerium/androiddriver.py#L231-L240
get current ip address
python
def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass if isinstance(address, bytes): raise AddressValueError( '%r does not appear to be an IPv4 or IPv6 address. ' 'Did you pass in a bytes (str in Python 2) instead of' ' a unicode object?' % address) raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
https://github.com/pypa/pipenv/blob/cae8d76c210b9777e90aab76e9c4b0e53bb19cde/pipenv/patched/notpip/_vendor/ipaddress.py#L135-L168
get current ip address
python
def ip_address(address): """Take an IP string/int and return an object of the correct type. Args: address: A string or integer, the IP address. Either IPv4 or IPv6 addresses may be supplied; integers less than 2**32 will be considered to be IPv4 by default. Returns: An IPv4Address or IPv6Address object. Raises: ValueError: if the *address* passed isn't either a v4 or a v6 address """ try: return IPv4Address(address) except (AddressValueError, NetmaskValueError): pass try: return IPv6Address(address) except (AddressValueError, NetmaskValueError): pass raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % address)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/ext/ipaddress.py#L93-L120
get current ip address
python
def get_ip_address_info(ip_address, cache=None, nameservers=None, timeout=2.0, parallel=False): """ Returns reverse DNS and country information for the given IP address Args: ip_address (str): The IP address to check cache (ExpiringDict): Cache storage nameservers (list): A list of one or more nameservers to use (Cloudflare's public DNS resolvers by default) timeout (float): Sets the DNS timeout in seconds parallel (bool): parallel processing Returns: OrderedDict: ``ip_address``, ``reverse_dns`` """ ip_address = ip_address.lower() if cache: info = cache.get(ip_address, None) if info: return info info = OrderedDict() info["ip_address"] = ip_address reverse_dns = get_reverse_dns(ip_address, nameservers=nameservers, timeout=timeout) country = get_ip_address_country(ip_address, parallel=parallel) info["country"] = country info["reverse_dns"] = reverse_dns info["base_domain"] = None if reverse_dns is not None: base_domain = get_base_domain(reverse_dns) info["base_domain"] = base_domain return info
https://github.com/domainaware/parsedmarc/blob/ecc9fd434c23d896ccd1f35795ccc047f946ed05/parsedmarc/utils.py#L336-L371
get current ip address
python
def get_ipv4(hostname): """Get list of ipv4 addresses for hostname """ addrinfo = socket.getaddrinfo(hostname, None, socket.AF_INET, socket.SOCK_STREAM) return [addrinfo[x][4][0] for x in range(len(addrinfo))]
https://github.com/openstack/pyghmi/blob/f710b1d30a8eed19a9e86f01f9351c737666f3e5/pyghmi/ipmi/private/util.py#L71-L77
get current ip address
python
def get_ip(self, address): """ Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') """ res = self.get_request('/ip_address/' + address) return IPAddress(cloud_manager=self, **res['ip_address'])
https://github.com/UpCloudLtd/upcloud-python-api/blob/954b0ad7c4b932b2be31a95d88975f6b0eeac8ed/upcloud_api/cloud_manager/ip_address_mixin.py#L16-L23
get current ip address
python
def ip6_address(self): """Returns the IPv6 address of the network interface. If multiple interfaces are provided, the address of the first found is returned. """ if self._ip6_address is None and self.network is not None: self._ip6_address = self._get_ip_address( libvirt.VIR_IP_ADDR_TYPE_IPV6) return self._ip6_address
https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L192-L203
get current ip address
python
def get_ip_address_from_rackspace_server(server_id): """ returns an ipaddress for a rackspace instance """ nova = connect_to_rackspace() server = nova.servers.get(server_id) # the server was assigned IPv4 and IPv6 addresses, locate the IPv4 address ip_address = None for network in server.networks['public']: if re.match('\d+\.\d+\.\d+\.\d+', network): ip_address = network break # find out if we have an ip address if ip_address is None: log_red('No IP address assigned') return False else: return ip_address
https://github.com/pyBookshelf/bookshelf/blob/a6770678e735de95b194f6e6989223970db5f654/bookshelf/api_v1.py#L1073-L1091
get current ip address
python
def ip_address(self, **kwargs): """ Set IP Address on an Interface. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). name (str): Name of interface id. (For interface: 1/0/5, 1/0/10 etc). ip_addr (str): IPv4/IPv6 Virtual IP Address.. Ex: 10.10.10.1/24 or 2001:db8::/48 delete (bool): True is the IP address is added and False if its to be deleted (True, False). Default value will be False if not specified. rbridge_id (str): rbridge-id for device. Only required when type is `ve`. get (bool): Get config instead of editing config. (True, False) callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: Return value of `callback`. Raises: KeyError: if `int_type`, `name`, or `ip_addr` is not passed. ValueError: if `int_type`, `name`, or `ip_addr` are invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... int_type = 'tengigabitethernet' ... name = '225/0/4' ... ip_addr = '20.10.10.1/24' ... output = dev.interface.disable_switchport(inter_type= ... int_type, inter=name) ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr) ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr, delete=True) ... output = dev.interface.add_vlan_int('86') ... output = dev.interface.ip_address(int_type='ve', ... name='86', ip_addr=ip_addr, rbridge_id='225') ... output = dev.interface.ip_address(int_type='ve', ... name='86', ip_addr=ip_addr, delete=True, ... rbridge_id='225') ... output = dev.interface.ip_address(int_type='loopback', ... name='225', ip_addr='10.225.225.225/32', ... rbridge_id='225') ... output = dev.interface.ip_address(int_type='loopback', ... name='225', ip_addr='10.225.225.225/32', delete=True, ... rbridge_id='225') ... ip_addr = 'fc00:1:3:1ad3:0:0:23:a/64' ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr) ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr, delete=True) ... output = dev.interface.ip_address(int_type='ve', ... name='86', ip_addr=ip_addr, rbridge_id='225') ... output = dev.interface.ip_address(int_type='ve', ... name='86', ip_addr=ip_addr, delete=True, ... rbridge_id='225') """ int_type = str(kwargs.pop('int_type').lower()) name = str(kwargs.pop('name')) ip_addr = str(kwargs.pop('ip_addr')) delete = kwargs.pop('delete', False) rbridge_id = kwargs.pop('rbridge_id', '1') callback = kwargs.pop('callback', self._callback) valid_int_types = ['gigabitethernet', 'tengigabitethernet', 've', 'fortygigabitethernet', 'hundredgigabitethernet', 'loopback'] if int_type not in valid_int_types: raise ValueError('int_type must be one of: %s' % repr(valid_int_types)) ipaddress = ip_interface(unicode(ip_addr)) ip_args = dict(name=name, address=ip_addr) method_name = None method_class = self._interface if ipaddress.version == 4: method_name = 'interface_%s_ip_ip_config_address_' \ 'address' % int_type elif ipaddress.version == 6: method_name = 'interface_%s_ipv6_ipv6_config_address_ipv6_' \ 'address_address' % int_type if int_type == 've': method_name = "rbridge_id_%s" % method_name method_class = self._rbridge ip_args['rbridge_id'] = rbridge_id if not pynos.utilities.valid_vlan_id(name): raise InvalidVlanId("`name` must be between `1` and `8191`") elif int_type == 'loopback': method_name = 'rbridge_id_interface_loopback_ip_ip_config_' \ 'address_address' if ipaddress.version == 6: method_name = 'rbridge_id_interface_loopback_ipv6_ipv6_' \ 'config_address_ipv6_address_address' method_class = self._rbridge ip_args['rbridge_id'] = rbridge_id ip_args['id'] = name elif not pynos.utilities.valid_interface(int_type, name): raise ValueError('`name` must be in the format of x/y/z for ' 'physical interfaces.') ip_address_attr = getattr(method_class, method_name) config = ip_address_attr(**ip_args) if delete: config.find('.//*address').set('operation', 'delete') try: if kwargs.pop('get', False): return callback(config, handler='get_config') else: return callback(config) # TODO Setting IP on port channel is not done yet. except AttributeError: return None
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L346-L469
get current ip address
python
def _get_interface_ip(self, interface_name): """Get the ip address for an interface. :param interface_name: interface_name as a string :return: ip address of interface as a string """ 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
https://github.com/openstack/networking-cisco/blob/aa58a30aec25b86f9aa5952b0863045975debfa9/networking_cisco/plugins/cisco/cfg_agent/device_drivers/iosxe/iosxe_routing_driver.py#L307-L322
get current ip address
python
def ip4_address(self): """Returns the IPv4 address of the network interface. If multiple interfaces are provided, the address of the first found is returned. """ if self._ip4_address is None and self.network is not None: self._ip4_address = self._get_ip_address( libvirt.VIR_IP_ADDR_TYPE_IPV4) return self._ip4_address
https://github.com/F-Secure/see/blob/3e053e52a45229f96a12db9e98caf7fb3880e811/see/context/context.py#L178-L189
get current ip address
python
def parse_ip_address(self, ip_address): """Parse an address as returned by the ``connected_users_info`` or ``user_sessions_info`` API calls. Example:: >>> EjabberdBackendBase().parse_ip_address('192.168.0.1') # doctest: +FORCE_TEXT IPv4Address('192.168.0.1') >>> EjabberdBackendBase().parse_ip_address('::FFFF:192.168.0.1') # doctest: +FORCE_TEXT IPv4Address('192.168.0.1') >>> EjabberdBackendBase().parse_ip_address('::1') # doctest: +FORCE_TEXT IPv6Address('::1') :param ip_address: An IP address. :type ip_address: str :return: The parsed IP address. :rtype: `ipaddress.IPv6Address` or `ipaddress.IPv4Address`. """ if ip_address.startswith('::FFFF:'): ip_address = ip_address[7:] if six.PY2 and isinstance(ip_address, str): # ipaddress constructor does not eat str in py2 :-/ ip_address = ip_address.decode('utf-8') return ipaddress.ip_address(ip_address)
https://github.com/mathiasertl/xmpp-backends/blob/214ef0664dbf90fa300c2483b9b3416559e5d171/xmpp_backends/base.py#L592-L615
get current ip address
python
def get_internal_ip(): """Get the local IP addresses.""" nics = {} for interface_name in interfaces(): addresses = ifaddresses(interface_name) try: nics[interface_name] = { 'ipv4': addresses[AF_INET], 'link_layer': addresses[AF_LINK], 'ipv6': addresses[AF_INET6], } except KeyError: pass return nics
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/lib/ip.py#L14-L28
get current ip address
python
def local_ip(): """Get the local network IP of this machine""" try: ip = socket.gethostbyname(socket.gethostname()) except IOError: ip = socket.gethostbyname('localhost') if ip.startswith('127.'): ip = get_local_ip_by_interfaces() if ip is None: ip = get_local_ip_by_socket() return ip
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/utils.py#L60-L70
get current ip address
python
def get_ipv6_addr(iface=None, inc_aliases=False, fatal=True, exc_list=None, dynamic_only=True): """Get assigned IPv6 address for a given interface. Returns list of addresses found. If no address found, returns empty list. If iface is None, we infer the current primary interface by doing a reverse lookup on the unit private-address. We currently only support scope global IPv6 addresses i.e. non-temporary addresses. If no global IPv6 address is found, return the first one found in the ipv6 address list. :param iface: network interface on which ipv6 address(es) are expected to be found. :param inc_aliases: include alias interfaces in search :param fatal: if True, raise exception if address not found :param exc_list: list of addresses to ignore :param dynamic_only: only recognise dynamic addresses :return: list of ipv6 addresses """ addresses = get_iface_addr(iface=iface, inet_type='AF_INET6', inc_aliases=inc_aliases, fatal=fatal, exc_list=exc_list) if addresses: global_addrs = [] for addr in addresses: key_scope_link_local = re.compile("^fe80::..(.+)%(.+)") m = re.match(key_scope_link_local, addr) if m: eui_64_mac = m.group(1) iface = m.group(2) else: global_addrs.append(addr) if global_addrs: # Make sure any found global addresses are not temporary cmd = ['ip', 'addr', 'show', iface] out = subprocess.check_output(cmd).decode('UTF-8') if dynamic_only: key = re.compile("inet6 (.+)/[0-9]+ scope global.* dynamic.*") else: key = re.compile("inet6 (.+)/[0-9]+ scope global.*") addrs = [] for line in out.split('\n'): line = line.strip() m = re.match(key, line) if m and 'temporary' not in line: # Return the first valid address we find for addr in global_addrs: if m.group(1) == addr: if not dynamic_only or \ m.group(1).endswith(eui_64_mac): addrs.append(addr) if addrs: return addrs if fatal: raise Exception("Interface '%s' does not have a scope global " "non-temporary ipv6 address." % iface) return []
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L360-L424
get current ip address
python
def _get_local_ip(self): """Try to determine the local IP address of the machine.""" try: sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Use Google Public DNS server to determine own IP sock.connect(('8.8.8.8', 80)) return sock.getsockname()[0] except socket.error: try: return socket.gethostbyname(socket.gethostname()) except socket.gaierror: return '127.0.0.1' finally: sock.close()
https://github.com/florianholzapfel/panasonic-viera/blob/bf912ff6eb03b59e3dde30b994a0fb1d883eb873/panasonic_viera/__init__.py#L138-L153
get current ip address
python
def get_public_ip(addresses, version=4): """Return either the devices public IPv4 or IPv6 address. """ for addr in addresses: if addr['public'] and addr['address_family'] == version: return addr.get('address') return None
https://github.com/MozillaSecurity/laniakea/blob/7e80adc6ae92c6c1332d4c08473bb271fb3b6833/laniakea/core/providers/packet/manager.py#L192-L198
get current ip address
python
def get_ip6_address(interface_name, expand=False): """ Extracts the IPv6 address for a particular interface from `ifconfig`. :param interface_name: Name of the network interface (e.g. ``eth0``). :type interface_name: unicode :param expand: If set to ``True``, an abbreviated address is expanded to the full address. :type expand: bool :return: IPv6 address; ``None`` if the interface is present but no address could be extracted. :rtype: unicode """ address = _get_address(interface_name, IP6_PATTERN) if address and expand: return ':'.join(_expand_groups(address)) return address
https://github.com/merll/docker-fabric/blob/785d84e40e17265b667d8b11a6e30d8e6b2bf8d4/dockerfabric/utils/net.py#L47-L61
get current ip address
python
def get(self): """Get the first public IP address returned by one of the online services.""" q = queue.Queue() for u, j, k in urls: t = threading.Thread(target=self._get_ip_public, args=(q, u, j, k)) t.daemon = True t.start() timer = Timer(self.timeout) ip = None while not timer.finished() and ip is None: if q.qsize() > 0: ip = q.get() return ', '.join(set([x.strip() for x in ip.split(',')]))
https://github.com/nicolargo/glances/blob/5bd4d587a736e0d2b03170b56926841d2a3eb7ee/glances/plugins/glances_ip.py#L161-L176
get current ip address
python
def get_ips(self, instance_id): """ Retrieves all IP addresses associated to a given instance. :return: tuple (IPs) """ self._init_az_api() cluster_name, node_name = instance_id # XXX: keep in sync with contents of `vm_deployment_template` ip_name = ('{node_name}-public-ip'.format(node_name=node_name)) ip = self._network_client.public_ip_addresses.get(cluster_name, ip_name) if (ip.provisioning_state == 'Succeeded' and ip.ip_address): return [ip.ip_address] else: return []
https://github.com/gc3-uzh-ch/elasticluster/blob/e6345633308c76de13b889417df572815aabe744/elasticluster/providers/azure_provider.py#L412-L426
get current ip address
python
def get_ip(self, use_cached=True): """Get the last known IP of this device""" device_json = self.get_device_json(use_cached) return device_json.get("dpLastKnownIp")
https://github.com/digidotcom/python-devicecloud/blob/32529684a348a7830a269c32601604c78036bcb8/devicecloud/devicecore.py#L443-L446
get current ip address
python
def get_ip_addresses(): """ :return: all knows IP Address """ LOGGER.debug("IPAddressService.get_ip_addresses") args = {'http_operation': 'GET', 'operation_path': ''} response = IPAddressService.requester.call(args) ret = None if response.rc == 0: ret = [] for ipAddress in response.response_content['ipAddresses']: ret.append(IPAddress.json_2_ip_address(ipAddress)) elif response.rc != 404: err_msg = 'IPAddressService.get_ip_addresses - Problem while getting IP Address. ' \ 'Reason: ' + str(response.response_content) + '-' + str(response.error_message) + \ " (" + str(response.rc) + ")" LOGGER.warning(err_msg) return ret
https://github.com/echinopsii/net.echinopsii.ariane.community.cli.python3/blob/0a7feddebf66fee4bef38d64f456d93a7e9fcd68/ariane_clip3/directory.py#L1374-L1391
get current ip address
python
def mac_address(ip): """Get the MAC address""" mac = '' for line in os.popen('/sbin/ifconfig'): s = line.split() if len(s) > 3: if s[3] == 'HWaddr': mac = s[4] elif s[2] == ip: break return {'MAC': mac}
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/utils/syshwinfo.py#L164-L174
get current ip address
python
def _get_ids_from_ip(self, ip_address): # pylint: disable=inconsistent-return-statements """List VS ids which match the given ip address.""" try: # Does it look like an ip address? socket.inet_aton(ip_address) except socket.error: return [] # Find the VS via ip address. First try public ip, then private results = self.list_instances(public_ip=ip_address, mask="id") if results: return [result['id'] for result in results] results = self.list_instances(private_ip=ip_address, mask="id") if results: return [result['id'] for result in results]
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/vs.py#L677-L692
get current ip address
python
def is_ip(address): """ Returns True if address is a valid IP address. """ try: # Test to see if already an IPv4/IPv6 address address = netaddr.IPAddress(address) return True except (netaddr.AddrFormatError, ValueError): return False
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L448-L457
get current ip address
python
def ip_lookup(self, ip_address): """Looks up an IP address and returns network information about it. :param string ip_address: An IP address. Can be IPv4 or IPv6 :returns: A dictionary of information about the IP """ obj = self.client['Network_Subnet_IpAddress'] return obj.getByIpAddress(ip_address, mask='hardware, virtualGuest')
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/network.py#L344-L352
get current ip address
python
def get_real_time_locate(ipAddress): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. :param ipAddress: str value valid IPv4 IP address :return: dictionary containing hostIp, devId, deviceIP, ifDesc, ifIndex """ if auth is None or url is None: # checks to see if the imc credentials are already available set_imc_creds() real_time_locate_url = "/imcrs/res/access/realtimeLocate?type=2&value=" + str(ipAddress) + "&total=false" f_url = url + real_time_locate_url r = requests.get(f_url, auth=auth, headers=headers) # creates the URL using the payload variable as the contents if r.status_code == 200: return json.loads(r.text)['realtimeLocation'] else: print(r.status_code) print("An Error has occured")
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/archived/pyhpimc.py#L441-L458
get current ip address
python
def get_eip_address_info(addresses=None, allocation_ids=None, region=None, key=None, keyid=None, profile=None): ''' Get 'interesting' info about some, or all EIPs associated with the current account. addresses (list) - Optional list of addresses. If provided, only the addresses associated with those in the list will be returned. allocation_ids (list) - Optional list of allocation IDs. If provided, only the addresses associated with the given allocation IDs will be returned. returns (list of dicts) - A list of dicts, each containing the info for one of the requested EIPs. CLI Example: .. code-block:: bash salt-call boto_ec2.get_eip_address_info addresses=52.4.2.15 .. versionadded:: 2016.3.0 ''' if type(addresses) == (type('string')): addresses = [addresses] if type(allocation_ids) == (type('string')): allocation_ids = [allocation_ids] ret = _get_all_eip_addresses(addresses=addresses, allocation_ids=allocation_ids, region=region, key=key, keyid=keyid, profile=profile) interesting = ['allocation_id', 'association_id', 'domain', 'instance_id', 'network_interface_id', 'network_interface_owner_id', 'public_ip', 'private_ip_address'] return [dict([(x, getattr(address, x)) for x in interesting]) for address in ret]
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/boto_ec2.py#L197-L232
get current ip address
python
def get_node_ip_address(address="8.8.8.8:53"): """Determine the IP address of the local node. Args: address (str): The IP address and port of any known live service on the network you care about. Returns: The IP address of the current node. """ ip_address, port = address.split(":") s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # This command will raise an exception if there is no internet # connection. s.connect((ip_address, int(port))) node_ip_address = s.getsockname()[0] except Exception as e: node_ip_address = "127.0.0.1" # [Errno 101] Network is unreachable if e.errno == 101: try: # try get node ip address from host name host_name = socket.getfqdn(socket.gethostname()) node_ip_address = socket.gethostbyname(host_name) except Exception: pass finally: s.close() return node_ip_address
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L196-L226
get current ip address
python
def ip(self): """return the public ip address""" r = '' # this was compiled from here: # https://github.com/un33k/django-ipware # http://www.ietf.org/rfc/rfc3330.txt (IPv4) # http://www.ietf.org/rfc/rfc5156.txt (IPv6) # https://en.wikipedia.org/wiki/Reserved_IP_addresses format_regex = re.compile(r'\s') ip_regex = re.compile(r'^(?:{})'.format(r'|'.join([ r'0\.', # reserved for 'self-identification' r'10\.', # class A r'169\.254', # link local block r'172\.(?:1[6-9]|2[0-9]|3[0-1])\.', # class B r'192\.0\.2\.', # documentation/examples r'192\.168', # class C r'255\.{3}', # broadcast address r'2001\:db8', # documentation/examples r'fc00\:', # private r'fe80\:', # link local unicast r'ff00\:', # multicast r'127\.', # localhost r'\:\:1' # localhost ]))) ips = self.ips for ip in ips: if not format_regex.search(ip) and not ip_regex.match(ip): r = ip break return r
https://github.com/Jaymon/endpoints/blob/2f1c4ae2c69a168e69447d3d8395ada7becaa5fb/endpoints/http.py#L887-L919
get current ip address
python
def getIPaddresses(self): """identify the IP addresses where this process client will launch the SC2 client""" if not self.ipAddress: self.ipAddress = ipAddresses.getAll() # update with IP address return self.ipAddress
https://github.com/ttinies/sc2gameLobby/blob/5352d51d53ddeb4858e92e682da89c4434123e52/sc2gameLobby/gameConfig.py#L470-L474
get current ip address
python
def get_ips(self, instance_id): """Retrieves all IP addresses associated to a given instance. :return: tuple (IPs) """ instance = self._load_instance(instance_id) IPs = sum(instance.networks.values(), []) return IPs
https://github.com/TissueMAPS/TmDeploy/blob/f891b4ffb21431988bc4a063ae871da3bf284a45/elasticluster/elasticluster/providers/openstack.py#L288-L295
get current ip address
python
def get_ip(request): """Return the IP address inside the HTTP_X_FORWARDED_FOR var inside the `request` object. The return of this function can be overrided by the `LOCAL_GEOLOCATION_IP` variable in the `conf` module. This function will skip local IPs (starting with 10. and equals to 127.0.0.1). """ if getsetting('LOCAL_GEOLOCATION_IP'): return getsetting('LOCAL_GEOLOCATION_IP') forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if not forwarded_for: return UNKNOWN_IP for ip in forwarded_for.split(','): ip = ip.strip() if not ip.startswith('10.') and not ip == '127.0.0.1': return ip return UNKNOWN_IP
https://github.com/Yipit/eventlib/blob/0cf29e5251a59fcbfc727af5f5157a3bb03832e2/eventlib/util.py#L23-L46
get current ip address
python
def get_ip_address_list(list_name): ''' Retrieves a specific IP address list. list_name(str): The name of the specific policy IP address list to retrieve. CLI Example: .. code-block:: bash salt '*' bluecoat_sslv.get_ip_address_list MyIPAddressList ''' payload = {"jsonrpc": "2.0", "id": "ID0", "method": "get_policy_ip_addresses", "params": [list_name, 0, 256]} response = __proxy__['bluecoat_sslv.call'](payload, False) return _convert_to_list(response, 'item_name')
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/bluecoat_sslv.py#L308-L328
get current ip address
python
def get_ip_addresses(): """Gets the ip addresses from ifconfig :return: (dict) of devices and aliases with the IPv4 address """ log = logging.getLogger(mod_logger + '.get_ip_addresses') command = ['/sbin/ifconfig'] try: result = run_command(command) except CommandError: raise ifconfig = result['output'].strip() # Scan the ifconfig output for IPv4 addresses devices = {} parts = ifconfig.split() device = None for part in parts: if device is None: if 'eth' in part or 'eno' in part: device = part else: test = part.split(':', 1) if len(test) == 2: if test[0] == 'addr': ip_address = test[1] log.info('Found IP address %s on device %s', ip_address, device) devices[device] = ip_address device = None return devices
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/bash.py#L235-L267
get current ip address
python
def get_own_ip(): """Get the host's ip number. """ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect(("8.8.8.8", 80)) except socket.gaierror: ip_ = "127.0.0.1" else: ip_ = sock.getsockname()[0] finally: sock.close() return ip_
https://github.com/pytroll/posttroll/blob/8e811a0544b5182c4a72aed074b2ff8c4324e94d/posttroll/publisher.py#L41-L53
get current ip address
python
def get_self_ip(): ''' Find out localhost outside IP. :return: ''' sck = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: sck.connect(('1.255.255.255', 1)) # Does not needs to be reachable ip_addr = sck.getsockname()[0] except Exception: ip_addr = socket.gethostbyname(socket.gethostname()) finally: sck.close() return ip_addr
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/utils/ssdp.py#L89-L103
get current ip address
python
def get_ips(host, port): """ lookup all IPs (v4 and v6) """ ips = set() for af_type in (socket.AF_INET, socket.AF_INET6): try: records = socket.getaddrinfo(host, port, af_type, socket.SOCK_STREAM) ips.update(rec[4][0] for rec in records) except socket.gaierror as ex: pass return ips
https://github.com/rgs1/zk_shell/blob/bbf34fdfcf1f81100e2a5816fad8af6afc782a54/zk_shell/util.py#L188-L201
get current ip address
python
def get_host_ipv4addr_info(ipv4addr=None, mac=None, discovered_data=None, return_fields=None, **api_opts): ''' Get host ipv4addr information CLI Examples: .. code-block:: bash salt-call infoblox.get_ipv4addr ipv4addr=123.123.122.12 salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae salt-call infoblox.get_ipv4addr mac=00:50:56:84:6e:ae return_fields=host return_fields='mac,host,configure_for_dhcp,ipv4addr' ''' infoblox = _get_infoblox(**api_opts) return infoblox.get_host_ipv4addr_object(ipv4addr, mac, discovered_data, return_fields)
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L436-L451
get current ip address
python
def address_by_interface(ifname): """Returns the IP address of the given interface name, e.g. 'eth0' Parameters ---------- ifname : str Name of the interface whose address is to be returned. Required. Taken from this Stack Overflow answer: https://stackoverflow.com/questions/24196932/how-can-i-get-the-ip-address-of-eth0-in-python#24196955 """ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) return socket.inet_ntoa(fcntl.ioctl( s.fileno(), 0x8915, # SIOCGIFADDR struct.pack('256s', bytes(ifname[:15], 'utf-8')) )[20:24])
https://github.com/Parsl/parsl/blob/d7afb3bc37f50dcf224ae78637944172edb35dac/parsl/addresses.py#L33-L48
get current ip address
python
def get_ap_info(ipaddress, auth, url): """ function takes input of ipaddress to RESTFUL call to HP IMC :param ipaddress: The current IP address of the Access Point at time of query. :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: Dictionary object with the details of the target access point :rtype: dict >>> from pyhpeimc.auth import * >>> from pyhpeimc.wsm.apinfo import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> ap_info = get_ap_info('10.101.0.170',auth.creds, auth.url) >>> assert type(ap_info) is dict >>> assert len(ap_info) == 20 >>> assert 'acDevId' in ap_info >>> assert 'acIpAddress' in ap_info >>> assert 'acLabel' in ap_info >>> assert 'apAlias' in ap_info >>> assert 'connectType' in ap_info >>> assert 'hardwareVersion' in ap_info >>> assert 'ipAddress' in ap_info >>> assert 'isFit' in ap_info >>> assert 'label' in ap_info >>> assert 'location' in ap_info >>> assert 'locationList' in ap_info >>> assert 'macAddress' in ap_info >>> assert 'onlineClientCount' in ap_info >>> assert 'serialId' in ap_info >>> assert 'softwareVersion' in ap_info >>> assert 'ssids' in ap_info >>> assert 'status' in ap_info >>> assert 'sysName' in ap_info >>> assert 'type' in ap_info """ get_ap_info_url = "/imcrs/wlan/apInfo/queryApBasicInfoByCondition?ipAddress=" + str(ipaddress) f_url = url + get_ap_info_url payload = None r = requests.get(f_url, auth=auth, headers=HEADERS) # creates the URL using the payload variable as the contents # print(r.status_code) try: if r.status_code == 200: if len(r.text) > 0: return json.loads(r.text)['apBasicInfo'] except requests.exceptions.RequestException as e: return "Error:\n" + str(e) + " get_ap_info_all: An Error has occured"
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/build/lib/pyhpeimc/wsm/apinfo.py#L91-L167
get current ip address
python
def getPublicIP(): """Get the IP that this machine uses to contact the internet. If behind a NAT, this will still be this computer's IP, and not the router's.""" try: # Try to get the internet-facing IP by attempting a connection # to a non-existent server and reading what IP was used. with closing(socket.socket(socket.AF_INET, socket.SOCK_DGRAM)) as sock: # 203.0.113.0/24 is reserved as TEST-NET-3 by RFC 5737, so # there is guaranteed to be no one listening on the other # end (and we won't accidentally DOS anyone). sock.connect(('203.0.113.1', 1)) ip = sock.getsockname()[0] return ip except: # Something went terribly wrong. Just give loopback rather # than killing everything, because this is often called just # to provide a default argument return '127.0.0.1'
https://github.com/DataBiosphere/toil/blob/a8252277ff814e7bee0971139c2344f88e44b644/src/toil/batchSystems/options.py#L22-L40
get current ip address
python
def get_by_ip(cls, ip): 'Returns Host instance for the given ip address.' ret = cls.hosts_by_ip.get(ip) if ret is None: ret = cls.hosts_by_ip[ip] = [Host(ip)] return ret
https://github.com/saulpw/visidata/blob/32771e0cea6c24fc7902683d14558391395c591f/visidata/loaders/pcap.py#L150-L155
get current ip address
python
def getaddress(self): """Parse the next address.""" self.commentlist = [] self.gotonext() oldpos = self.pos oldcl = self.commentlist plist = self.getphraselist() self.gotonext() returnlist = [] if self.pos >= len(self.field): # Bad email address technically, no domain. if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in '.@': # email address is just an addrspec # this isn't very efficient since we start over self.pos = oldpos self.commentlist = oldcl addrspec = self.getaddrspec() returnlist = [(SPACE.join(self.commentlist), addrspec)] elif self.field[self.pos] == ':': # address is a group returnlist = [] fieldlen = len(self.field) self.pos += 1 while self.pos < len(self.field): self.gotonext() if self.pos < fieldlen and self.field[self.pos] == ';': self.pos += 1 break returnlist = returnlist + self.getaddress() elif self.field[self.pos] == '<': # Address is a phrase then a route addr routeaddr = self.getrouteaddr() if self.commentlist: returnlist = [(SPACE.join(plist) + ' (' + ' '.join(self.commentlist) + ')', routeaddr)] else: returnlist = [(SPACE.join(plist), routeaddr)] else: if plist: returnlist = [(SPACE.join(self.commentlist), plist[0])] elif self.field[self.pos] in self.specials: self.pos += 1 self.gotonext() if self.pos < len(self.field) and self.field[self.pos] == ',': self.pos += 1 return returnlist
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/_parseaddr.py#L266-L323
get current ip address
python
def update_ipaddress(self): ''' Updates the scheduler so it knows its own ip address ''' # assign local ip in case of exception self.old_ip = self.my_ip self.my_ip = '127.0.0.1' try: obj = urllib.request.urlopen(settings.get('PUBLIC_IP_URL', 'http://ip.42.pl/raw')) results = self.ip_regex.findall(obj.read()) if len(results) > 0: self.my_ip = results[0] else: raise IOError("Could not get valid IP Address") obj.close() self.logger.debug("Current public ip: {ip}".format(ip=self.my_ip)) except IOError: self.logger.error("Could not reach out to get public ip") pass if self.old_ip != self.my_ip: self.logger.info("Changed Public IP: {old} -> {new}".format( old=self.old_ip, new=self.my_ip))
https://github.com/istresearch/scrapy-cluster/blob/13aaed2349af5d792d6bcbfcadc5563158aeb599/crawler/crawling/distributed_scheduler.py#L275-L298
get current ip address
python
def _get_local_ip(): """ Get the local ip of this device :return: Ip of this computer :rtype: str """ return set([x[4][0] for x in socket.getaddrinfo( socket.gethostname(), 80, socket.AF_INET )]).pop()
https://github.com/the01/python-paps/blob/2dde5a71913e4c7b22901cf05c6ecedd890919c4/paps/si/app/sensor.py#L96-L107
get current ip address
python
def cmd_ip_internal(verbose): """Get the local IP address(es) of the local interfaces. Example: \b $ habu.ip.internal { "lo": { "ipv4": [ { "addr": "127.0.0.1", "netmask": "255.0.0.0", "peer": "127.0.0.1" } ], "link_layer": [ { "addr": "00:00:00:00:00:00", "peer": "00:00:00:00:00:00" } ], "ipv6": [ { "addr": "::1", "netmask": "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128" } ] }, ... """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') print("Gathering NIC details...", file=sys.stderr) result = get_internal_ip() if result: print(json.dumps(result, indent=4)) else: print("[X] Unable to get detail about the interfaces") return True
https://github.com/portantier/habu/blob/87091e389dc6332fe1b82830c22b2eefc55816f2/habu/cli/cmd_ip_internal.py#L14-L56
get current ip address
python
def _get_ipv6_network_from_address(address): """Get an netaddr.IPNetwork for the given IPv6 address :param address: a dict as returned by netifaces.ifaddresses :returns netaddr.IPNetwork: None if the address is a link local or loopback address """ if address['addr'].startswith('fe80') or address['addr'] == "::1": return None prefix = address['netmask'].split("/") if len(prefix) > 1: netmask = prefix[1] else: netmask = address['netmask'] return netaddr.IPNetwork("%s/%s" % (address['addr'], netmask))
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/network/ip.py#L72-L87
get current ip address
python
def get_ip_address(request): """ Correct IP address is expected as first element of HTTP_X_FORWARDED_FOR or REMOTE_ADDR """ if 'HTTP_X_FORWARDED_FOR' in request.META: return request.META['HTTP_X_FORWARDED_FOR'].split(',')[0].strip() else: return request.META['REMOTE_ADDR']
https://github.com/opennode/waldur-core/blob/d6c17a9592bb6c49c33567542eef8d099605a46a/waldur_core/logging/middleware.py#L29-L36
get current ip address
python
def get_ip_report(self, this_ip, timeout=None): """ Get IP address reports. :param this_ip: a valid IPv4 address in dotted quad notation, for the time being only IPv4 addresses are supported. :param timeout: The amount of time in seconds the request should wait before timing out. :return: JSON response """ params = {'apikey': self.api_key, 'ip': this_ip} try: response = requests.get(self.base + 'ip-address/report', params=params, proxies=self.proxies, timeout=timeout) except requests.RequestException as e: return dict(error=str(e)) return _return_response_and_status_code(response)
https://github.com/blacktop/virustotal-api/blob/4e01e1c6d87255ec8370ac2a4ee16edce00e1e86/virus_total_apis/api.py#L215-L234
get current ip address
python
def local_ip(): """Get the local network IP of this machine""" ip = socket.gethostbyname(socket.gethostname()) if ip.startswith('127.'): # Check eth0, eth1, eth2, en0, ... interfaces = [ i + str(n) for i in ("eth", "en", "wlan") for n in xrange(3) ] # :( for interface in interfaces: try: ip = interface_ip(interface) break except IOError: pass return ip
https://github.com/uber/tchannel-python/blob/ee08cce6234f24fd2373774988186dd374306c43/tchannel/net.py#L44-L58
get current ip address
python
def ipaddress(): ''' Determine our own IP adress. This seems to be far more complicated than you would think: ''' try: import socket s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(("gmail.com", 80)) result = s.getsockname()[0] s.close() return result except Exception: return ""
https://github.com/troeger/opensubmit/blob/384a95b7c6fa41e3f949a129d25dafd9a1c54859/executor/opensubmitexec/hostinfo.py#L18-L31
get current ip address
python
def get_real_time_locate(host_ipaddress, auth, url): """ function takes the ipAddress of a specific host and issues a RESTFUL call to get the device and interface that the target host is currently connected to. Note: Although intended to return a single location, Multiple locations may be returned for a single host due to a partially discovered network or misconfigured environment. :param host_ipaddress: str value valid IPv4 IP address :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries where each element of the list represents the location of the target host :rtype: list >>> from pyhpeimc.auth import * >>> from pyhpeimc.plat.termaccess import * >>> auth = IMCAuth("http://", "10.101.0.203", "8080", "admin", "admin") >>> found_device = get_real_time_locate('10.101.0.51', auth.creds, auth.url) >>> assert type(found_device) is list >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> assert 'deviceId' in found_device[0] >>> no_device = get_real_time_locate('192.168.254.254', auth.creds, auth.url) >>> assert type(no_device) is dict >>> assert len(no_device) == 0 """ f_url = url + "/imcrs/res/access/realtimeLocate?type=2&value=" + str(host_ipaddress) + \ "&total=false" response = requests.get(f_url, auth=auth, headers=HEADERS) try: if response.status_code == 200: response = json.loads(response.text) if 'realtimeLocation' in response: real_time_locate = response['realtimeLocation'] if isinstance(real_time_locate, dict): real_time_locate = [real_time_locate] return real_time_locate else: return json.loads(response)['realtimeLocation'] else: print("Host not found") return 403 except requests.exceptions.RequestException as error: return "Error:\n" + str(error) + " get_real_time_locate: An Error has occured"
https://github.com/HPENetworking/PYHPEIMC/blob/4fba31827573587e03a6233c7db60f188038c8e5/pyhpeimc/plat/termaccess.py#L23-L83
get current ip address
python
def get_address(self, address_id, **params): """https://developers.coinbase.com/api/v2#show-addresss""" return self.api_client.get_address(self.id, address_id, **params)
https://github.com/coinbase/coinbase-python/blob/497c28158f529e8c7d0228521b4386a890baf088/coinbase/wallet/model.py#L163-L165
get current ip address
python
def determine_ip_address(): """Return the first IP address for an ethernet interface on the system.""" addrs = [ x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e" for x in v if x.family == AddressFamily.AF_INET ] return addrs[0]
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L61-L67
get current ip address
python
def get_ip_on_network(self, network_name): """Given a network name, returns the IP address :param network_name: (str) Name of the network to search for :return: (str) IP address on the specified network or None """ return self.get_scenario_host_ip_on_network( scenario_role_name=self.cons3rt_role_name, network_name=network_name )
https://github.com/cons3rt/pycons3rt/blob/f004ab3a35c5bff2f698131fef3b2a8ed5a7596d/pycons3rt/deployment.py#L627-L636
get current ip address
python
def address(self, ip, owner=None, **kwargs): """ Create the Address TI object. Args: owner: ip: **kwargs: Return: """ return Address(self.tcex, ip, owner=owner, **kwargs)
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti/tcex_ti.py#L52-L64
get current ip address
python
def ip_address(self): """ The IP address of the first interface listed in the droplet's ``networks`` field (ordering IPv4 before IPv6), or `None` if there are no interfaces """ networks = self.get("networks", {}) v4nets = networks.get("v4", []) v6nets = networks.get("v6", []) try: return (v4nets + v6nets)[0].ip_address except IndexError: return None
https://github.com/jwodder/doapi/blob/b1306de86a01d8ae7b9c1fe2699765bb82e4f310/doapi/droplet.py#L141-L153
get current ip address
python
def get_host_ipv4(name=None, mac=None, allow_array=False, **api_opts): ''' Get ipv4 address from host record. Use `allow_array` to return possible multiple values. CLI Examples: .. code-block:: bash salt-call infoblox.get_host_ipv4 host=localhost.domain.com salt-call infoblox.get_host_ipv4 mac=00:50:56:84:6e:ae ''' data = get_host(name=name, mac=mac, **api_opts) if data and 'ipv4addrs' in data: l = [] for a in data['ipv4addrs']: if 'ipv4addr' in a: l.append(a['ipv4addr']) if allow_array: return l if l: return l[0] return None
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/infoblox.py#L410-L433
get current ip address
python
def get_ip(request): """ Retrieves the remote IP address from the request data. If the user is behind a proxy, they may have a comma-separated list of IP addresses, so we need to account for that. In such a case, only the first IP in the list will be retrieved. Also, some hosts that use a proxy will put the REMOTE_ADDR into HTTP_X_FORWARDED_FOR. This will handle pulling back the IP from the proper place. **NOTE** This function was taken from django-tracking (MIT LICENSE) http://code.google.com/p/django-tracking/ """ # if neither header contain a value, just use local loopback ip_address = request.META.get('HTTP_X_FORWARDED_FOR', request.META.get('REMOTE_ADDR', '127.0.0.1')) if ip_address: # make sure we have one and only one IP try: ip_address = IP_RE.match(ip_address) if ip_address: ip_address = ip_address.group(0) else: # no IP, probably from some dirty proxy or other device # throw in some bogus IP ip_address = '10.0.0.1' except IndexError: pass return ip_address
https://github.com/thornomad/django-hitcount/blob/b35d2f9c213f6a2ff0e5d0a746339a5b84b4d416/hitcount/utils.py#L11-L40
get current ip address
python
def _get_ids_from_ip(self, ip): # pylint: disable=inconsistent-return-statements """Returns list of matching hardware IDs for a given ip address.""" try: # Does it look like an ip address? socket.inet_aton(ip) except socket.error: return [] # Find the server via ip address. First try public ip, then private results = self.list_hardware(public_ip=ip, mask="id") if results: return [result['id'] for result in results] results = self.list_hardware(private_ip=ip, mask="id") if results: return [result['id'] for result in results]
https://github.com/softlayer/softlayer-python/blob/9f181be08cc3668353b05a6de0cb324f52cff6fa/SoftLayer/managers/hardware.py#L530-L545
get current ip address
python
def _in6_getifaddr(ifname): """ Returns a list of IPv6 addresses configured on the interface 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
https://github.com/secdev/scapy/blob/3ffe757c184017dd46464593a8f80f85abc1e79a/scapy/arch/unix.py#L149-L181
get current ip address
python
def get_ip_info(ip: str, exceptions: bool=False, timeout: int=10) -> tuple: """ Returns (ip, country_code, host) tuple of the IP address. :param ip: IP address :param exceptions: Raise Exception or not :param timeout: Timeout in seconds. Note that timeout only affects geo IP part, not getting host name. :return: (ip, country_code, host) """ import traceback import socket if not ip: # localhost return None, '', '' host = '' country_code = get_geo_ip(ip, exceptions=exceptions, timeout=timeout).get('country_code', '') try: res = socket.gethostbyaddr(ip) host = res[0][:255] if ip else '' except Exception as e: msg = 'socket.gethostbyaddr({}) failed: {}'.format(ip, traceback.format_exc()) logger.error(msg) if exceptions: raise e return ip, country_code, host
https://github.com/kajala/django-jutil/blob/2abd93ebad51042744eaeb1ee1074ed0eb55ad0c/jutil/request.py#L39-L61
get current ip address
python
def get_ip_address(domain): """ Get IP address for given `domain`. Try to do smart parsing. Args: domain (str): Domain or URL. Returns: str: IP address. Raises: ValueError: If can't parse the domain. """ if "://" not in domain: domain = "http://" + domain hostname = urlparse(domain).netloc if not hostname: raise ValueError("Can't parse hostname!") return socket.gethostbyname(hostname)
https://github.com/WebarchivCZ/WA-KAT/blob/16d064a3a775dc1d2713debda7847ded52dd2a06/src/wa_kat/analyzers/place_detector.py#L22-L43
get current ip address
python
async def get_real_ext_ip(self): """Return real external IP address.""" while self._ip_hosts: try: timeout = aiohttp.ClientTimeout(total=self._timeout) async with aiohttp.ClientSession( timeout=timeout, loop=self._loop ) as session, session.get(self._pop_random_ip_host()) as resp: ip = await resp.text() except asyncio.TimeoutError: pass else: ip = ip.strip() if self.host_is_ip(ip): log.debug('Real external IP: %s', ip) break else: raise RuntimeError('Could not get the external IP') return ip
https://github.com/constverum/ProxyBroker/blob/d21aae8575fc3a95493233ecfd2c7cf47b36b069/proxybroker/resolver.py#L92-L110
get current ip address
python
def address_to_ip(address): """Convert a hostname to a numerical IP addresses in an address. This should be a no-op if address already contains an actual numerical IP address. Args: address: This can be either a string containing a hostname (or an IP address) and a port or it can be just an IP address. Returns: The same address but with the hostname replaced by a numerical IP address. """ address_parts = address.split(":") ip_address = socket.gethostbyname(address_parts[0]) # Make sure localhost isn't resolved to the loopback ip if ip_address == "127.0.0.1": ip_address = get_node_ip_address() return ":".join([ip_address] + address_parts[1:])
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L174-L193
get current ip address
python
def get(self, ip_address): """Return the record for the ip_address in the MaxMind DB Arguments: ip_address -- an IP address in the standard string notation """ address = ipaddress.ip_address(ip_address) if address.version == 6 and self._metadata.ip_version == 4: raise ValueError('Error looking up {0}. You attempted to look up ' 'an IPv6 address in an IPv4-only database.'.format( ip_address)) pointer = self._find_address_in_tree(address) return self._resolve_data_pointer(pointer) if pointer else None
https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/maxminddb/reader.py#L61-L76
get current ip address
python
def is_ip_addr(value): """ Check that the supplied value is an Internet Protocol address, v.4, represented by a dotted-quad string, i.e. '1.2.3.4'. >>> vtor = Validator() >>> vtor.check('ip_addr', '1 ') '1' >>> vtor.check('ip_addr', ' 1.2') '1.2' >>> vtor.check('ip_addr', ' 1.2.3 ') '1.2.3' >>> vtor.check('ip_addr', '1.2.3.4') '1.2.3.4' >>> vtor.check('ip_addr', '0.0.0.0') '0.0.0.0' >>> vtor.check('ip_addr', '255.255.255.255') '255.255.255.255' >>> vtor.check('ip_addr', '255.255.255.256') # doctest: +SKIP Traceback (most recent call last): VdtValueError: the value "255.255.255.256" is unacceptable. >>> vtor.check('ip_addr', '1.2.3.4.5') # doctest: +SKIP Traceback (most recent call last): VdtValueError: the value "1.2.3.4.5" is unacceptable. >>> vtor.check('ip_addr', 0) # doctest: +SKIP Traceback (most recent call last): VdtTypeError: the value "0" is of the wrong type. """ if not isinstance(value, string_types): raise VdtTypeError(value) value = value.strip() try: dottedQuadToNum(value) except ValueError: raise VdtValueError(value) return value
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/validate.py#L954-L989
get current ip address
python
def get_ip_addresses(self, **kwargs): """ Get IP Addresses already set on an Interface. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet etc). name (str): Name of interface id. (For interface: 1/0/5, 1/0/10 etc). version (int): 4 or 6 to represent IPv4 or IPv6 address callback (function): A function executed upon completion of the method. The only parameter passed to `callback` will be the ``ElementTree`` `config`. Returns: List of 0 or more IPs configure on the specified interface. Raises: KeyError: if `int_type` or `name` is not passed. ValueError: if `int_type` or `name` are invalid. Examples: >>> import pynos.device >>> switches = ['10.24.39.211', '10.24.39.203'] >>> auth = ('admin', 'password') >>> for switch in switches: ... conn = (switch, '22') ... with pynos.device.Device(conn=conn, auth=auth) as dev: ... int_type = 'tengigabitethernet' ... name = '225/0/4' ... ip_addr = '20.10.10.1/24' ... version = 4 ... output = dev.interface.disable_switchport(inter_type= ... int_type, inter=name) ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr) ... result = dev.interface.get_ip_addresses( ... int_type=int_type, name=name, version=version) ... assert len(result) >= 1 ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr, delete=True) ... ip_addr = 'fc00:1:3:1ad3:0:0:23:a/64' ... version = 6 ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr) ... result = dev.interface.get_ip_addresses( ... int_type=int_type, name=name, version=version) ... assert len(result) >= 1 ... output = dev.interface.ip_address(int_type=int_type, ... name=name, ip_addr=ip_addr, delete=True) """ int_type = str(kwargs.pop('int_type').lower()) name = str(kwargs.pop('name')) version = int(kwargs.pop('version')) callback = kwargs.pop('callback', self._callback) valid_int_types = ['gigabitethernet', 'tengigabitethernet', 'fortygigabitethernet', 'hundredgigabitethernet'] if int_type not in valid_int_types: raise ValueError('int_type must be one of: %s' % repr(valid_int_types)) method_name = None method_class = self._interface if version == 4: method_name = 'interface_%s_ip_ip_config_address_' \ 'address' % int_type elif version == 6: method_name = 'interface_%s_ipv6_ipv6_config_address_ipv6_' \ 'address_address' % int_type if not pynos.utilities.valid_interface(int_type, name): raise ValueError('`name` must be in the format of x/y/z for ' 'physical interfaces.') ip_args = dict(name=name, address='') ip_address_attr = getattr(method_class, method_name) config = ip_address_attr(**ip_args) output = callback(config, handler='get_config') result = [] if version == 4: for item in output.data.findall( './/{*}address/{*}address'): result.append(item.text) elif version == 6: for item in output.data.findall( './/{*}address/{*}ipv6-address/{' '*}address'): result.append(item.text) return result
https://github.com/brocade/pynos/blob/bd8a34e98f322de3fc06750827d8bbc3a0c00380/pynos/versions/base/interface.py#L471-L560