本文整理汇总了Python中socket.inet_pton函数的典型用法代码示例。如果您正苦于以下问题:Python inet_pton函数的具体用法?Python inet_pton怎么用?Python inet_pton使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了inet_pton函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: validip6addr
def validip6addr(addr):
try:
socket.inet_pton(socket.AF_INET6, addr)
except (socket.error, AttributeError):
return False
print "Invalid Ipv6 Address"
return True
示例2: __init__
def __init__(self, market_id, my_ip, my_port, my_guid, nickname=None):
self.peers = {}
self.callbacks = defaultdict(list)
self.timeouts = []
self.port = my_port
self.ip = my_ip
self.guid = my_guid
self.market_id = market_id
self.nickname = nickname
self.handler = None
# Create one ZeroMQ context to be reused and reduce overhead
self.ctx = zmq.Context()
try:
socket.inet_pton(socket.AF_INET6, my_ip)
my_uri = 'tcp://[%s]:%s' % (self.ip, self.port)
except (socket.error, ValueError):
my_uri = 'tcp://%s:%s' % (self.ip, self.port)
self.uri = my_uri
self.log = logging.getLogger(
'[%s] %s' % (market_id, self.__class__.__name__)
)
示例3: prepareBaseReply
def prepareBaseReply(self, request):
request.setETag("RTSP/1.0")
request.setResponseCode(200)
request.setHeader("cseq", request.received_headers["cseq"])
request.setHeader("audio-jack-status", "connected; type=analog")
if "apple-challenge" in request.received_headers:
challenge = request.received_headers["apple-challenge"]
if challenge[-2:] != "==":
challenge += "=="
data = base64.b64decode(challenge)
host = request.getHost().host
if (host.split(".")) == 4: # ipv4
data += socket.inet_pton(socket.AF_INET, host)
elif host[:7] == "::ffff:":
data += socket.inet_pton(socket.AF_INET, host[7:])
else:
data += socket.inet_pton(socket.AF_INET6, host.split("%")[0])
hwaddr = self.info.deviceid
for i in range (0, 12, 2):
data += chr(int(hwaddr[i:i+2], 16))
data = data.ljust(32, '\0')
#self.dump(data)
key = RSA.load_key_string(AIRPORT_PRIVATE_KEY)
signature = base64.b64encode(key.private_encrypt(data, RSA.pkcs1_padding))
if signature[-2:] == "==":
signature = signature[:-2]
request.setHeader("apple-response", signature)
示例4: join_network
def join_network(self, seed_peers=[], callback=lambda msg: None):
self.log.info('Joining network')
known_peers = []
# Connect up through seed servers
for idx, seed in enumerate(seed_peers):
try:
socket.inet_pton(socket.AF_INET6, seed)
seed_peers[idx] = "tcp://[%s]:12345" % seed
except socket.error:
seed_peers[idx] = "tcp://%s:12345" % seed
# Connect to persisted peers
db_peers = self.get_past_peers()
known_peers = list(set(seed_peers)) + list(set(db_peers))
print 'known_peers', known_peers
self.connect_to_peers(known_peers)
# Populate routing table by searching for self
if len(known_peers) > 0:
self.search_for_my_node()
if callback is not None:
callback('Joined')
示例5: is_ipv6
def is_ipv6(addr):
"""Checks if a given address is an IPv6 address."""
try:
socket.inet_pton(socket.AF_INET6, addr)
return True
except socket.error:
return False
示例6: query_nat
def query_nat(self, family, proto, src_ip, src_port, dst_ip, dst_port):
[proto, family, src_port, dst_port] = [
int(v) for v in [proto, family, src_port, dst_port]]
packed_src_ip = socket.inet_pton(family, src_ip)
packed_dst_ip = socket.inet_pton(family, dst_ip)
assert len(packed_src_ip) == len(packed_dst_ip)
length = len(packed_src_ip)
pnl = self.pfioc_natlook()
pnl.proto = proto
pnl.direction = self.PF_OUT
pnl.af = family
memmove(addressof(pnl.saddr), packed_src_ip, length)
memmove(addressof(pnl.daddr), packed_dst_ip, length)
self._add_natlook_ports(pnl, src_port, dst_port)
ioctl(pf_get_dev(), self.DIOCNATLOOK,
(c_char * sizeof(pnl)).from_address(addressof(pnl)))
ip = socket.inet_ntop(
pnl.af, (c_char * length).from_address(addressof(pnl.rdaddr)).raw)
port = socket.ntohs(self._get_natlook_port(pnl.rdxport))
return (ip, port)
示例7: is_ip
def is_ip(value):
"""Determine if the given string is an IP address.
Python 2 on Windows doesn't provide ``inet_pton``, so this only
checks IPv4 addresses in that environment.
:param value: value to check
:type value: str
:return: True if string is an IP address
:rtype: bool
"""
if PY2 and os.name == 'nt':
try:
socket.inet_aton(value)
return True
except socket.error:
return False
for family in (socket.AF_INET, socket.AF_INET6):
try:
socket.inet_pton(family, value)
except socket.error:
pass
else:
return True
return False
示例8: setup
def setup(hass, config):
"""Set up Zeroconf and make Home Assistant discoverable."""
from zeroconf import Zeroconf, ServiceInfo
zeroconf = Zeroconf()
zeroconf_name = '{}.{}'.format(hass.config.location_name, ZEROCONF_TYPE)
requires_api_password = hass.config.api.api_password is not None
params = {
'version': __version__,
'base_url': hass.config.api.base_url,
'requires_api_password': requires_api_password,
}
host_ip = util.get_local_ip()
try:
host_ip_pton = socket.inet_pton(socket.AF_INET, host_ip)
except socket.error:
host_ip_pton = socket.inet_pton(socket.AF_INET6, host_ip)
info = ServiceInfo(ZEROCONF_TYPE, zeroconf_name, host_ip_pton,
hass.http.server_port, 0, 0, params)
zeroconf.register_service(info)
def stop_zeroconf(event):
"""Stop Zeroconf."""
zeroconf.unregister_service(info)
zeroconf.close()
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_zeroconf)
return True
示例9: is_local_interface
def is_local_interface(host):
is_ipv6 = False
if ':' in host:
try:
if host.find('[', 0, 2) != -1:
last_bracket_position = host.rfind(']')
last_colon_position = host.rfind(':')
if last_colon_position > last_bracket_position:
host = host.rsplit(':', 1)[0]
host = host.strip('[]')
socket.inet_pton(socket.AF_INET6, host)
is_ipv6 = True
except socket.error:
host = host.split(':',1)[0]
try:
if is_ipv6:
sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect( (host, 4242) )
local_ip = sock.getsockname()[0]
sock.close()
except:
log.exception("Failed to open socket with %s" % host)
raise
if local_ip == host:
return True
return False
示例10: convdata
def convdata(self, dtype, data):
if dtype == "4":
if type(data) != str:
raise error("IPv4 address must be a string")
if len(data) == 4:
d = data
else:
d = socket.inet_pton(socket.AF_INET, data)
if dtype == "6":
if type(data) != str:
raise error("IPv6 address must be a string")
if len(data) == 16 and data.find(":") == -1:
d = data
else:
d = socket.inet_pton(socket.AF_INET6, data)
if dtype == "d":
if type(data) == str:
d = dn.fromstring(data)
elif isinstance(data, dn.domainname):
d = data
else:
raise error("Domain name must be either proper or string")
if dtype == "s":
d = str(data)
if dtype == "i":
d = int(data)
return d
示例11: validate
def validate(self, value):
valid = True
try:
socket.inet_pton(self.family, value)
except:
valid = False
return valid
示例12: __new__
def __new__(cls, addr, s=None):
if s is None:
host, port = addr
for af_type, cls in connector_registry.iteritems():
try :
socket.inet_pton(af_type, host)
break
except socket.error:
pass
else:
raise ValueError("Unknown type of host", host)
self = object.__new__(cls)
self.addr = cls._normAddress(addr)
if s is None:
s = socket.socket(af_type, socket.SOCK_STREAM)
else:
self.is_server = True
self.is_closed = False
self.socket = s
self.socket_fd = s.fileno()
# always use non-blocking sockets
s.setblocking(0)
# disable Nagle algorithm to reduce latency
s.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.queued = []
return self
示例13: is_ip6
def is_ip6(self):
from socket import inet_pton, AF_INET6, error
try:
inet_pton(AF_INET6, self.host)
return True
except error:
return False
示例14: cidr_to_list
def cidr_to_list(self, string):
# references:
# http://boubakr92.wordpress.com/2012/12/20/convert-cidr-into-ip-range-with-python/
# http://stackoverflow.com/questions/8338655/how-to-get-list-of-ip-addresses
# parse address and cidr
(addrString, cidrString) = string.split('/')
# split address into octets and convert cidr to int
addr = addrString.split('.')
cidr = int(cidrString)
# initialize the netmask and calculate based on cidr mask
mask = [0, 0, 0, 0]
for i in range(cidr):
mask[i/8] = mask[i/8] + (1 << (7 - i % 8))
# initialize net and binary and netmask with addr to get network
net = []
for i in range(4):
net.append(int(addr[i]) & mask[i])
# duplicate net into broad array, gather host bits, and generate broadcast
broad = list(net)
brange = 32 - cidr
for i in range(brange):
broad[3 - i/8] = broad[3 - i/8] + (1 << (i % 8))
# print information, mapping integer lists to strings for easy printing
#mask = '.'.join(map(str, mask))
net = '.'.join(map(str, net))
broad = '.'.join(map(str, broad))
ips = []
f = struct.unpack('!I',socket.inet_pton(socket.AF_INET,net))[0]
l = struct.unpack('!I',socket.inet_pton(socket.AF_INET,broad))[0]
while f <= l:
ips.append(socket.inet_ntop(socket.AF_INET,struct.pack('!I',f)))
f = f + 1
return ips
示例15: add_addr
def add_addr(cmd, _type, addr):
if addr is None:
return
host = None
from socket import inet_pton,AF_INET,AF_INET6
try:
inet_pton(AF_INET, addr['uri']['host'])
host = addr['uri']['host']
except:
pass
try:
inet_pton(AF_INET6, addr['uri']['host'])
host = addr['uri']['host']
except:
pass
cursor.execute("""INSERT INTO dionaea.sip_addrs
(sip_command, sip_addr_type, sip_addr_display_name,
sip_addr_uri_scheme, sip_addr_uri_user, sip_addr_uri_password,
sip_addr_uri_hostname, sip_addr_uri_host, sip_addr_uri_port) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s)""",
(
cmd, _type, addr['display_name'],
addr['uri']['scheme'], addr['uri']['user'], addr['uri']['password'],
addr['uri']['host'], host, addr['uri']['port']
))