• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python socket.inet_pton函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中socket.inet_pton函数的典型用法代码示例。如果您正苦于以下问题:Python inet_pton函数的具体用法?Python inet_pton怎么用?Python inet_pton使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了inet_pton函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:wind3110991,项目名称:dolphin,代码行数:7,代码来源:network.py


示例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__)
        )
开发者ID:BombazineDoll,项目名称:OpenBazaar,代码行数:25,代码来源:transport.py


示例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)
开发者ID:Callez,项目名称:e2openplugin-OpenAirPlay,代码行数:34,代码来源:airplayserver.py


示例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')
开发者ID:alejochang,项目名称:OpenBazaar,代码行数:29,代码来源:crypto2crypto.py


示例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
开发者ID:liminw,项目名称:python-docs-samples,代码行数:7,代码来源:main.py


示例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)
开发者ID:luserx0,项目名称:sshuttle,代码行数:25,代码来源:pf.py


示例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
开发者ID:ThiefMaster,项目名称:flask,代码行数:28,代码来源:helpers.py


示例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
开发者ID:azogue,项目名称:home-assistant,代码行数:35,代码来源:zeroconf.py


示例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
开发者ID:BruceZu,项目名称:graphite-web,代码行数:31,代码来源:util.py


示例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
开发者ID:dolda2000,项目名称:ldd,代码行数:27,代码来源:rec.py


示例11: validate

 def validate(self, value):
     valid = True
     try:
         socket.inet_pton(self.family, value)
     except:
         valid = False
     return valid
开发者ID:oVirt,项目名称:ovirt-node,代码行数:7,代码来源:valid.py


示例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
开发者ID:Nexedi,项目名称:neoppod,代码行数:26,代码来源:connector.py


示例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
开发者ID:pombredanne,项目名称:httoop,代码行数:7,代码来源:messaging.py


示例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
开发者ID:13108989848,项目名称:pydra,代码行数:33,代码来源:module.py


示例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']
					))
开发者ID:ManiacTwister,项目名称:dionaea,代码行数:25,代码来源:pg_backend.py


示例16: valid_ipv6

def valid_ipv6(ip):
    """Returns True if the given string is a valid IPv6 address."""
    try:
        socket.inet_pton(socket.AF_INET6, ip)
    except socket.error:  # not a valid ip
        return False
    return True
开发者ID:bookchin,项目名称:storjnode,代码行数:7,代码来源:util.py


示例17: get_packed_host

 def get_packed_host(self):
   """Returns a BEP_0005 'packed' representation of the addr."""
   try:
     result = socket.inet_pton(socket.AF_INET, self.host)
   except (ValueError, socket.error):
     result = socket.inet_pton(socket.AF_INET6, self.host)
   return buffer(result)
开发者ID:allanlw,项目名称:dhtplay,代码行数:7,代码来源:contactinfo.py


示例18: check_ipv6

def check_ipv6(n):
    """ Returns true if n is IPv6 address, false otherwise. """
    try:
        socket.inet_pton(socket.AF_INET6, n)
        return True
    except:
        return False
开发者ID:flavio,项目名称:spacewalk,代码行数:7,代码来源:rpclib.py


示例19: isIPV6

 def isIPV6(self, string_ip):
     ipv6 = True
     try:
         socket.inet_pton(socket.AF_INET6, string_ip)
     except:
         ipv6 = False
     return ipv6
开发者ID:AntBean,项目名称:alienvault-ossim,代码行数:7,代码来源:Detector.py


示例20: ipv6

def ipv6(value):
    '''Validate an IPv6 address'''
    try:
        socket.inet_pton(socket.AF_INET6, value)
        return value
    except socket.error:
        raise ValueError('{0} is not a valid ipv4 address'.format(value))
开发者ID:bedge,项目名称:flask-restplus,代码行数:7,代码来源:inputs.py



注:本文中的socket.inet_pton函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python socket.listen函数代码示例发布时间:2022-05-27
下一篇:
Python socket.inet_ntop函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap