当前位置: 首页>>代码示例>>Python>>正文


Python socket.gethostbyname方法代码示例

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


在下文中一共展示了socket.gethostbyname方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: video_invite

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def video_invite():
    global IsOpen, Version, AudioOpen
    if Version == 4:
        host_name = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
    else:
        host_name = [i['addr'] for i in ifaddresses(interfaces()[-2]).setdefault(AF_INET6, [{'addr': 'No IP addr'}])][
            -1]

    invite = 'INVITE' + host_name + ':;' + user + ':;' + chat
    s.send(invite.encode())
    if not IsOpen:
        vserver = vachat.Video_Server(10087, Version)
        if AudioOpen:
            aserver = vachat.Audio_Server(10088, Version)
            aserver.start()
        vserver.start()
        IsOpen = True 
开发者ID:11ze,项目名称:The-chat-room,代码行数:19,代码来源:client-test2.py

示例2: test_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def test_connection(name, url, timeout=10):
    """Simple connection test"""
    urlinfo = urlparse(url)
    start = time.time()
    try:
        ip = socket.gethostbyname(urlinfo.netloc)
    except Exception as e:
        print('Error resolving DNS for {}: {}, {}'.format(name, url, e))
        return
    dns_elapsed = time.time() - start
    start = time.time()
    try:
        _ = urlopen(url, timeout=timeout)
    except Exception as e:
        print("Error open {}: {}, {}, DNS finished in {} sec.".format(name, url, e, dns_elapsed))
        return
    load_elapsed = time.time() - start
    print("Timing for {}: {}, DNS: {:.4f} sec, LOAD: {:.4f} sec.".format(name, url, dns_elapsed, load_elapsed)) 
开发者ID:awslabs,项目名称:dynamic-training-with-apache-mxnet-on-aws,代码行数:20,代码来源:diagnose.py

示例3: ThreadSSH

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def ThreadSSH(self):
        try:
            self.session = pxssh.pxssh(encoding='utf-8')
            if (not path.isfile(self.settings['Password'])):
                self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
                self.settings['Password'],port=self.settings['Port'])
            else:
                self.session.login(gethostbyname(self.settings['Host']), self.settings['User'],
                ssh_key=self.settings['Password'],port=self.settings['Port'])

            if self.connection:
                self.status = '[{}]'.format(setcolor('ON',color='green'))
            self.activated = True
        except Exception, e:
            self.status = '[{}]'.format(setcolor('OFF',color='red'))
            self.activated = False 
开发者ID:mh4x0f,项目名称:b1tifi,代码行数:18,代码来源:ssh.py

示例4: test_tls_closed_connection_read_handshake

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def test_tls_closed_connection_read_handshake(self):
        ip = socket.gethostbyname('badtls.io')

        # Break the connection after the ServerHello is received
        def recv_callback(src, dest):
            data = src.recv(8192)
            for record_type, tls_version, message in parse_tls_records(data):
                if record_type == b'\x16':
                    for message_type, payload in parse_handshake_messages(message):
                        if message_type == b'\x02':
                            dest.close()
                            return
            dest.send(data)

        with assert_exception(self, (errors.TLSDisconnectError, errors.TLSError),
                              'The remote end closed the connection|TLS handshake failed'):
            try:
                sock, send_sock, recv_sock, server = make_socket_proxy(ip, 443, None, recv_callback)
                tls.TLSSocket.wrap(sock, 'badtls.io')
            finally:
                recv_sock.close()
                send_sock.close()
                server.close() 
开发者ID:wbond,项目名称:oscrypto,代码行数:25,代码来源:test_tls.py

示例5: test_tls_closed_connection_write_handshake

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def test_tls_closed_connection_write_handshake(self):
        ip = socket.gethostbyname('badtls.io')

        # Break the connection after the ClientHello is sent
        def send_callback(src, dest):
            data = src.recv(8192)
            for record_type, tls_version, message in parse_tls_records(data):
                if record_type == b'\x16':
                    for message_type, payload in parse_handshake_messages(message):
                        if message_type == b'\x01':
                            src.close()
                            return
            dest.send(data)

        with assert_exception(self, (errors.TLSDisconnectError, errors.TLSError),
                              'The remote end closed the connection|TLS handshake failed'):
            try:
                sock, send_sock, recv_sock, server = make_socket_proxy(ip, 443, send_callback)
                tls.TLSSocket.wrap(sock, 'badtls.io')
            finally:
                recv_sock.close()
                send_sock.close()
                server.close() 
开发者ID:wbond,项目名称:oscrypto,代码行数:25,代码来源:test_tls.py

示例6: test_tls_closed_connection_read_shutdown

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def test_tls_closed_connection_read_shutdown(self):
        ip = socket.gethostbyname('badtls.io')
        try:
            sock, send_sock, recv_sock, server = make_socket_proxy(ip, 443)
            tsock = None
            try:
                tsock = tls.TLSSocket.wrap(sock, 'badtls.io')
                send_sock.close()
                tsock.read(8192)
                shutdown = False
            except (errors.TLSError):
                if tsock:
                    tsock.shutdown()
                shutdown = True
            self.assertEqual(True, shutdown)
        finally:
            recv_sock.close()
            server.close() 
开发者ID:wbond,项目名称:oscrypto,代码行数:20,代码来源:test_tls.py

示例7: open_local_file

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def open_local_file(self, req):
        host = req.get_host()
        file = req.get_selector()
        localfile = url2pathname(file)
        stats = os.stat(localfile)
        size = stats[stat.ST_SIZE]
        modified = rfc822.formatdate(stats[stat.ST_MTIME])
        mtype = mimetypes.guess_type(file)[0]
        stats = os.stat(localfile)
        headers = mimetools.Message(StringIO(
            'Content-Type: %s\nContent-Length: %d\nLast-modified: %s\n' %
            (mtype or 'text/plain', size, modified)))
        if host:
            host, port = splitport(host)
        if not host or \
           (not port and socket.gethostbyname(host) in self.get_names()):
            return addinfourl(open(localfile, 'rb'),
                              headers, 'file:'+file)
        raise URLError('file not on local host') 
开发者ID:war-and-code,项目名称:jawfish,代码行数:21,代码来源:urllib2.py

示例8: is_same_host

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
开发者ID:war-and-code,项目名称:jawfish,代码行数:20,代码来源:connectionpool.py

示例9: is_same_host

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith('/'):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)

        host = _ipv6_host(host, self.scheme)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
开发者ID:danielecook,项目名称:gist-alfred,代码行数:22,代码来源:connectionpool.py

示例10: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def __init__(self, name, host):
        self.__clientKey = None
        self.__macAddress = None
        self.__name = name
        self.__handshake_done = False

        # Check if host is an IP address or hostname
        # Try to resolve the hostname
        try:
            socket.inet_aton(host)
            self.__ip = host
            self.__hostname = socket.gethostbyaddr(host)[0]
        except:
            self.__hostname = host
            self.__ip = socket.gethostbyname(host)

        if self.__macAddress is None and self.__ip is not None:
            self.__macAddress = self.__get_mac_address(self.__ip)

        super(LGTVAuth, self).__init__('ws://' + self.__ip + ':3000/', exclude_headers=["Origin"])
        self.__waiting_callback = self.__prompt 
开发者ID:klattimer,项目名称:LGWebOSRemote,代码行数:23,代码来源:auth.py

示例11: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def __init__(self, name, ip=None, mac=None, key=None, hostname=None):
        self.__command_count = 0
        self.__waiting_callback = None
        self.__commands = []
        self.__handshake_done = False

        self.__hostname = hostname
        self.__clientKey = key
        self.__macAddress = mac
        self.__ip = ip
        self.__name = name

        if self.__hostname is not None:
            # Over ride IP address when we know the hostname
            self.__ip = socket.gethostbyname(self.__hostname)

        super(LGTVRemote, self).__init__('ws://' + self.__ip + ':3000/', exclude_headers=["Origin"]) 
开发者ID:klattimer,项目名称:LGWebOSRemote,代码行数:19,代码来源:remote.py

示例12: setUpClass

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def setUpClass(self):
        import tests.data_test_webpage
        import httpbin

        self.httpbin_thread = utils.run_in_subprocess(httpbin.app.run, host='0.0.0.0', port=14887, passthrough_errors=False)
        self.httpbin = 'http://' + socket.gethostbyname(socket.gethostname()) + ':14887'

        self.inqueue = Queue(10)
        self.outqueue = Queue(10)
        self.fetcher = Fetcher(self.inqueue, self.outqueue)
        self.fetcher.splash_endpoint = 'http://127.0.0.1:8050/execute'
        self.rpc = xmlrpc_client.ServerProxy('http://localhost:%d' % 24444)
        self.xmlrpc_thread = utils.run_in_thread(self.fetcher.xmlrpc_run, port=24444)
        self.thread = utils.run_in_thread(self.fetcher.run)
        self.proxy_thread = subprocess.Popen(['pyproxy', '--username=binux', '--bind=0.0.0.0',
                                              '--password=123456', '--port=14830',
                                              '--debug'], close_fds=True)
        self.proxy = socket.gethostbyname(socket.gethostname()) + ':14830' 
开发者ID:binux,项目名称:pyspider,代码行数:20,代码来源:test_fetcher.py

示例13: is_same_host

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def is_same_host(self, url):
        """
        Check if the given ``url`` is a member of the same host as this
        connection pool.
        """
        if url.startswith("/"):
            return True

        # TODO: Add optional support for socket.gethostbyname checking.
        scheme, host, port = get_host(url)
        if host is not None:
            host = _normalize_host(host, scheme=scheme)

        # Use explicit default port for comparison when none is given
        if self.port and not port:
            port = port_by_scheme.get(scheme)
        elif not self.port and port == port_by_scheme.get(scheme):
            port = None

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:22,代码来源:connectionpool.py

示例14: raw

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [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() 
开发者ID:angr,项目名称:rex,代码行数:25,代码来源:linux_mips32_connectback.py

示例15: get_host_ip

# 需要导入模块: import socket [as 别名]
# 或者: from socket import gethostbyname [as 别名]
def get_host_ip(hostIP=None):
    if hostIP is None or hostIP == 'auto':
        hostIP = 'ip'

    if hostIP == 'dns':
        hostIP = socket.getfqdn()
    elif hostIP == 'ip':
        from socket import gaierror
        try:
            hostIP = socket.gethostbyname(socket.getfqdn())
        except gaierror:
            logger.warn('gethostbyname(socket.getfqdn()) failed... trying on hostname()')
            hostIP = socket.gethostbyname(socket.gethostname())
        if hostIP.startswith("127."):
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            # doesn't have to be reachable
            s.connect(('10.255.255.255', 1))
            hostIP = s.getsockname()[0]
    return hostIP 
开发者ID:aws,项目名称:sagemaker-xgboost-container,代码行数:21,代码来源:tracker.py


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