本文整理汇总了Python中ipaddress.ip_address方法的典型用法代码示例。如果您正苦于以下问题:Python ipaddress.ip_address方法的具体用法?Python ipaddress.ip_address怎么用?Python ipaddress.ip_address使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ipaddress
的用法示例。
在下文中一共展示了ipaddress.ip_address方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: waf_update_ip_set
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def waf_update_ip_set(ip_set_id, source_ip):
logging.getLogger().debug('[waf_update_ip_set] Start')
ip_type = "IPV%s"%ip_address(source_ip).version
ip_class = "32" if ip_type == "IPV4" else "128"
waf.update_ip_set(IPSetId=ip_set_id,
ChangeToken=waf.get_change_token()['ChangeToken'],
Updates=[{
'Action': 'INSERT',
'IPSetDescriptor': {
'Type': ip_type,
'Value': "%s/%s"%(source_ip, ip_class)
}
}]
)
logging.getLogger().debug('[waf_update_ip_set] End')
示例2: is_payfast_ip_address
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def is_payfast_ip_address(ip_address_str):
"""
Return True if ip_address_str matches one of PayFast's server IP addresses.
Setting: `PAYFAST_IP_ADDRESSES`
:type ip_address_str: str
:rtype: bool
"""
# TODO: Django system check for validity?
payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
conf.DEFAULT_PAYFAST_IP_ADDRESSES)
if sys.version_info < (3,):
# Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
# (On Python 3, this should generally not happen:
# let unexpected bytes values fail as expected.)
ip_address_str = unicode(ip_address_str) # noqa: F821
payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses] # noqa: F821
return any(ip_address(ip_address_str) in ip_network(payfast_address)
for payfast_address in payfast_ip_addresses)
示例3: checkIP
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def checkIP(self, directive, directiveValues, findings):
csp = self.csp
for value in directiveValues:
url = '//' + Util.getSchemeFreeUrl(value)
host = urlparse(url).netloc
ip = None
validip = True
try:
ip = ipaddress.ip_address(u''+host)
except ValueError:
validip = False
if validip:
ipString = str(ip) + ''
if '127.0.0.1' in ipString:
findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive allows localhost as source. Please make sure to remove this in production environments.',FindingSeverity.INFO, directive, value))
else:
findings.append(Finding(csp.headerkey,FindingType.IP_SOURCE, directive.value + ' directive has an IP-Address as source: ' + ipString + ' (will be ignored by browsers!). ', FindingSeverity.INFO, directive, value))
示例4: bind_socket
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
"""Create TCP server socket.
:param host: IPv4, IPv6 or hostname may be specified
:param port: TCP port number
:param backlog: Maximum number of connections to queue
:return: socket.socket object
"""
try: # IP address: family must be specified for IPv6 at least
ip = ip_address(host)
host = str(ip)
sock = socket.socket(
socket.AF_INET6 if ip.version == 6 else socket.AF_INET
)
except ValueError: # Hostname, may become AF_INET or AF_INET6
sock = socket.socket()
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((host, port))
sock.listen(backlog)
return sock
示例5: get_cidr
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def get_cidr(iplist):
cidrs = []
for ip in iplist:
cidr = re.sub(r'\d+$', '0/24', ip)
cidrs.append(ipaddress.ip_network(cidr))
result = []
for cidr in cidrs:
for i in iplist:
ip = ipaddress.ip_address(i)
if ip in cidr:
result.append(str(cidr))
break
out = get_top(result)
for i in out:
cidr, num = i.split('|')
print(cidr, num)
示例6: iscdn
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def iscdn(host):
result = True
# noinspection PyBroadException
try:
if not re.search(r'\d+\.\d+\.\d+\.\d+', host):
host = parse_ip(host)
for cdn in cdns:
if ipaddress.ip_address(host) in ipaddress.ip_network(cdn):
result = False
except Exception:
pass
# noinspection PyBroadException
try:
with geoip2.database.Reader('data/GeoLite2-ASN.mmdb') as reader:
response = reader.asn(host)
for i in ASNS:
if response.autonomous_system_number == int(i):
result = False
except Exception:
pass
return result
示例7: raw
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def raw(self, arch=None):
if not arch:
raise ValueError("Architecture must be specified.")
the_arch = convert_arch(arch)
if the_arch.name != "MIPS32":
raise TypeError("%s only supports MIPS32." % str(self.__class__))
packed_port = struct.pack('>H', (~self.port) & 0xffff)
target_ip = socket.gethostbyname(self.host)
ip = ipaddress.ip_address(target_ip)
ip_for_shellcode = (~int(ip)) & 0xffffffff
ip_to_send = struct.pack('>I', ip_for_shellcode)
lower_ip = ip_to_send[:2]
higher_ip = ip_to_send[2:]
if the_arch.memory_endness == Endness.LE:
return self.code_le % (packed_port, higher_ip, lower_ip)
else:
raise NOTIMPLEMENTEDYET()
示例8: _is_url_naive
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def _is_url_naive(urlstr: str) -> bool:
"""Naive check if given URL is really a URL.
Args:
urlstr: The URL to check for, as string.
Return:
True if the URL really is a URL, False otherwise.
"""
url = qurl_from_user_input(urlstr)
assert url.isValid()
host = url.host()
# Valid IPv4/IPv6 address. Qt converts things like "23.42" or "1337" or
# "0xDEAD" to IP addresses, which we don't like, so we check if the host
# from Qt is part of the input.
if (not utils.raises(ValueError, ipaddress.ip_address, host) and
host in urlstr):
return True
tld = r'\.([^.0-9_-]+|xn--[a-z0-9-]+)$'
forbidden = r'[\u0000-\u002c\u002f\u003a-\u0060\u007b-\u00b6]'
return bool(re.search(tld, host) and not re.search(forbidden, host))
示例9: get_request_ip
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def get_request_ip(request: Any, context: Optional[Dict] = None) -> Optional[str]:
if request._cache.get('request_ip'):
return str(request._cache.get('request_ip', ''))
if request.transport:
if not context:
context = {}
real_ip_header = context.get('options', {}).get('http', {}).get('real_ip_header', 'X-Forwarded-For')
real_ip_from = context.get('options', {}).get('http', {}).get('real_ip_from', [])
if isinstance(real_ip_from, str):
real_ip_from = [real_ip_from]
peername = request.transport.get_extra_info('peername')
request_ip = None
if peername:
request_ip, _ = peername
if real_ip_header and real_ip_from and request.headers.get(real_ip_header) and request_ip and len(real_ip_from):
if any([ipaddress.ip_address(request_ip) in ipaddress.ip_network(cidr) for cidr in real_ip_from]):
request_ip = request.headers.get(real_ip_header).split(',')[0].strip().split(' ')[0].strip()
request._cache['request_ip'] = request_ip
return request_ip
return None
示例10: setup_kubernetes_client
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def setup_kubernetes_client():
if config.CONF.kubernetes.api_root:
api_root = config.CONF.kubernetes.api_root
else:
# NOTE(dulek): This is for containerized deployments, i.e. running in
# K8s Pods.
host = os.environ['KUBERNETES_SERVICE_HOST']
port = os.environ['KUBERNETES_SERVICE_PORT_HTTPS']
try:
addr = ipaddress.ip_address(host)
if addr.version == 6:
host = '[%s]' % host
except ValueError:
# It's not an IP addres but a hostname, it's fine, move along.
pass
api_root = "https://%s:%s" % (host, port)
_clients[_KUBERNETES_CLIENT] = k8s_client.K8sClient(api_root)
示例11: _match_whitelist
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def _match_whitelist(self, address: str, whitelist: str) -> bool:
trimmed_address = re.sub(r"/32$", "", address)
if address in whitelist:
raise PluginException(
cause=f"Address Object not created because the host {address} was found in the whitelist as {address}.",
assistance=f"If you would like to block this host, remove {address} from the whitelist and try again.")
elif '/' not in trimmed_address:
pass
for address_object in whitelist:
if self._determine_address_type(address_object) == "cidr":
net = ip_network(address_object, False)
ip = ip_address(trimmed_address)
if ip in net:
raise PluginException(
cause=f"Address Object not created because the host {address}"
f" was found in the whitelist as {address_object}.",
assistance="If you would like to block this host,"
f" remove {address_object} from the whitelist and try again.")
return False
示例12: find_internal_ip_on_device_network
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def find_internal_ip_on_device_network(upnp_dev: upnpclient.upnp.Device) -> str:
"""
For a given UPnP device, return the internal IP address of this host machine that can
be used for a NAT mapping.
"""
parsed_url = urlparse(upnp_dev.location)
# Get an ipaddress.IPv4Network instance for the upnp device's network.
upnp_dev_net = ipaddress.ip_network(parsed_url.hostname + "/24", strict=False)
for iface in netifaces.interfaces():
for family, addresses in netifaces.ifaddresses(iface).items():
# TODO: Support IPv6 addresses as well.
if family != netifaces.AF_INET:
continue
for item in addresses:
if ipaddress.ip_address(item["addr"]) in upnp_dev_net:
return item["addr"]
raise NoInternalAddressMatchesDevice(device_hostname=parsed_url.hostname)
示例13: fetch_peers_async
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def fetch_peers_async(node):
"""
:param node: tuple(ip, p2p_port, jrpc_port)
:return: list of tuple(ip, p2p_port, jrpc_port)
"""
json_rpc_url = "http://{}:{}".format(node[0], node[2])
server = Server(json_rpc_url)
try:
peers = await asyncio.wait_for(server.get_peers(), 5)
except Exception:
print("Failed to get peers from {}".format(json_rpc_url))
peers = {"peers": []}
await server.session.close()
return [
(
str(ipaddress.ip_address(int(p["ip"], 16))),
int(p["port"], 16),
int(p["port"], 16) + node[2] - node[1],
)
for p in peers["peers"]
]
示例14: transform_index_ipv6_address
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def transform_index_ipv6_address(ipv6_str):
"""
Converts a substring of an SNMP index that contains an IPv6 address into a human readable format.
Example:
254.128.0.0.0.0.0.0.14.134.16.255.254.243.135.30 => fe80::e86:10ff:fef3:871e
Args:
ipv6_str (str): SNMP index substring containing an IPv6 address.
Returns:
str: human readable IPv6 address
"""
parts = [u"{0:02x}".format(int(x)) for x in ipv6_str.split(u'.')]
byte_string = u""
for p, i in enumerate(parts):
if p % 2 != 0:
byte_string += u'{}{}:'.format(parts[p - 1].lstrip(u'0'), parts[p])
result = str(byte_string[:-1])
if isinstance(result, bytes):
result = result.decode('utf-8')
return str(ipaddress.ip_address(result))
示例15: transform_ip_octstr
# 需要导入模块: import ipaddress [as 别名]
# 或者: from ipaddress import ip_address [as 别名]
def transform_ip_octstr(ip_octstr):
"""
Converts octet strings containing IPv4 or IPv6 addresses into a human readable format.
Args:
ip_octstr (str): The octet string returned via SNMP
Returns:
str: human readable IPv4 or IPv6 IP address:
2001:dea:0:10::82, 1.2.3.4
"""
if isinstance(ip_octstr, bytes) and not is_python_2():
byte_arr = [u'{:02x}'.format(_) for _ in ip_octstr]
else:
byte_arr = ['%0.2x' % ord(_) for _ in ip_octstr]
if len(byte_arr) == 4:
return '.'.join([str(int(x, 16)) for x in byte_arr])
else:
byte_string = ""
for p, i in enumerate(byte_arr):
if p % 2 != 0:
byte_string += '{}{}:'.format(byte_arr[p - 1].lstrip('0'), byte_arr[p])
# ipaddress formats the string nicely -- collapses blocks of zero
return str(ipaddress.ip_address(byte_string[:-1].encode('ascii').decode('ascii')))