Python socket.gethostbyname() Examples

The following are 30 code examples of socket.gethostbyname(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module socket , or try the search function .
Example #1
Source File: tracker.py    From sagemaker-xgboost-container with Apache License 2.0 9 votes vote down vote up
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 
Example #2
Source File: diagnose.py    From dynamic-training-with-apache-mxnet-on-aws with Apache License 2.0 7 votes vote down vote up
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)) 
Example #3
Source File: ssh.py    From b1tifi with MIT License 7 votes vote down vote up
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 
Example #4
Source File: connectionpool.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #5
Source File: client.py    From tandem with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()
    self_address = (socket.gethostbyname(socket.gethostname()), args.self_port)
    server_address = (args.target_host, args.target_port)

    print("Listening on {}".format(self_address))
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(self_address)

    print("Connecting to rendezvous server")
    send_data(sock, self_address, server_address)

    while(True):
        data, address = recv_data(sock)

        if (type(data) is list and type(data[0]) is list):
            connect_to(sock, data)
        else:
            if data['type'] == 'ping':
                time.sleep(1)
                send_data(sock, create_pingback(data), address) 
Example #6
Source File: test_tls.py    From oscrypto with MIT License 6 votes vote down vote up
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() 
Example #7
Source File: test_tls.py    From oscrypto with MIT License 6 votes vote down vote up
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() 
Example #8
Source File: client.py    From The-chat-room with MIT License 6 votes vote down vote up
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 
Example #9
Source File: connectionpool.py    From core with MIT License 6 votes vote down vote up
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).lower()

        # 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) 
Example #10
Source File: client-test.py    From The-chat-room with MIT License 6 votes vote down vote up
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 
Example #11
Source File: test_tls.py    From oscrypto with MIT License 6 votes vote down vote up
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() 
Example #12
Source File: server.py    From tandem with Apache License 2.0 6 votes vote down vote up
def main():
    args = get_args()
    self_address = (socket.gethostbyname(socket.gethostname()), args.self_port)
    connected_clients = []

    print("Listening on {}".format(self_address))
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.bind(self_address)

    while(True):
        new_data, new_address = recv_data(sock)

        # Send new client information about the connected_clients
        for connected_data, connected_address in connected_clients:
            send_data(sock, (connected_data, connected_address), new_address)
            time.sleep(3)

        time.sleep(3)

        # Send connected_clients information about the new client
        for connected_data, connected_address in connected_clients:
            send_data(sock, (new_data, new_address), connected_address)

        connected_clients.append((new_data, new_address)) 
Example #13
Source File: connectionpool.py    From jawfish with MIT License 6 votes vote down vote up
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) 
Example #14
Source File: connectionpool.py    From gist-alfred with MIT License 6 votes vote down vote up
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) 
Example #15
Source File: linux_mips32_connectback.py    From rex with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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() 
Example #16
Source File: auth.py    From LGWebOSRemote with MIT License 6 votes vote down vote up
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 
Example #17
Source File: remote.py    From LGWebOSRemote with MIT License 6 votes vote down vote up
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"]) 
Example #18
Source File: urllib2.py    From jawfish with MIT License 6 votes vote down vote up
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') 
Example #19
Source File: test_fetcher.py    From pyspider with Apache License 2.0 6 votes vote down vote up
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' 
Example #20
Source File: connectionpool.py    From misp42splunk with GNU Lesser General Public License v3.0 6 votes vote down vote up
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) 
Example #21
Source File: client-test2.py    From The-chat-room with MIT License 6 votes vote down vote up
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 
Example #22
Source File: request.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def localhost():
    """Return the IP address of the magic hostname 'localhost'."""
    global _localhost
    if _localhost is None:
        _localhost = socket.gethostbyname('localhost')
    return _localhost 
Example #23
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Returns an open connection (socket) to the Splunk instance.

        This method is used for writing bulk events to an index or similar tasks
        where the overhead of opening a connection multiple times would be
        prohibitive.

        :returns: A socket.

        **Example**::

            import splunklib.binding as binding
            c = binding.connect(...)
            socket = c.connect()
            socket.write("POST %s HTTP/1.1\\r\\n" % "some/path/to/post/to")
            socket.write("Host: %s:%s\\r\\n" % (c.host, c.port))
            socket.write("Accept-Encoding: identity\\r\\n")
            socket.write("Authorization: %s\\r\\n" % c.token)
            socket.write("X-Splunk-Input-Mode: Streaming\\r\\n")
            socket.write("\\r\\n")
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if self.scheme == "https":
            sock = ssl.wrap_socket(sock)
        sock.connect((socket.gethostbyname(self.host), self.port))
        return sock 
Example #24
Source File: binding.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self):
        """Returns an open connection (socket) to the Splunk instance.

        This method is used for writing bulk events to an index or similar tasks
        where the overhead of opening a connection multiple times would be
        prohibitive.

        :returns: A socket.

        **Example**::

            import splunklib.binding as binding
            c = binding.connect(...)
            socket = c.connect()
            socket.write("POST %s HTTP/1.1\\r\\n" % "some/path/to/post/to")
            socket.write("Host: %s:%s\\r\\n" % (c.host, c.port))
            socket.write("Accept-Encoding: identity\\r\\n")
            socket.write("Authorization: %s\\r\\n" % c.token)
            socket.write("X-Splunk-Input-Mode: Streaming\\r\\n")
            socket.write("\\r\\n")
        """
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        if self.scheme == "https":
            sock = ssl.wrap_socket(sock)
        sock.connect((socket.gethostbyname(self.host), self.port))
        return sock 
Example #25
Source File: request.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            try:
                FileHandler.names = tuple(
                    socket.gethostbyname_ex('localhost')[2] +
                    socket.gethostbyname_ex(socket.gethostname())[2])
            except socket.gaierror:
                FileHandler.names = (socket.gethostbyname('localhost'),)
        return FileHandler.names

    # not entirely sure what the rules are here 
Example #26
Source File: socks.py    From plugin.video.kmediatorrent with GNU General Public License v3.0 5 votes vote down vote up
def _write_SOCKS5_address(self, addr, file):
        """
        Return the host and port packed for the SOCKS5 protocol,
        and the resolved address as a tuple object.
        """
        host, port = addr
        proxy_type, _, _, rdns, username, password = self.proxy
        
        # If the given destination address is an IP address, we'll
        # use the IPv4 address request even if remote resolving was specified.
        try:
            addr_bytes = socket.inet_aton(host)
            file.write(b"\x01" + addr_bytes)
            host = socket.inet_ntoa(addr_bytes)
        except socket.error:
            # Well it's not an IP number, so it's probably a DNS name.
            if rdns:
                # Resolve remotely
                file.write(b"\x03" + chr(len(host)).encode() + host.encode())
            else:
                # Resolve locally
                addr_bytes = socket.inet_aton(socket.gethostbyname(host))
                file.write(b"\x01" + addr_bytes)
                host = socket.inet_ntoa(addr_bytes)

        file.write(struct.pack(">H", port))
        return host, port 
Example #27
Source File: ip_gather.py    From pysploit-framework with GNU General Public License v2.0 5 votes vote down vote up
def exploit():
    """ main exploit function """
    try:
        var = socket.gethostbyname(obtainer.options['target'][2])
        print(var)
    except socket.gaierror:
        print(Red + "Error:" + White + "You should enter right url.")
        return False 
Example #28
Source File: updateHosts.py    From updateHosts with MIT License 5 votes vote down vote up
def check_connection():
    sleep_seconds = 1200
    i = 0
    for i in range(sleep_seconds):
        try:
            socket.gethostbyname("www.baidu.com")
            break
        except socket.gaierror:
            time.sleep(1)
    if i == sleep_seconds - 1:
        exit_this() 
Example #29
Source File: portscan.py    From pynmap with GNU General Public License v3.0 5 votes vote down vote up
def resolve(self, host):
        # Get website and translate it to IP address
        # Using very low level socket module
        print("[+] Target argument received website address")
        print("[+] Resolving website address to ip address")
        try:
            ip = socket.gethostbyname(host)
        except socket.gaierror:
            print(bcolors.WARNING+"[!] Error resolving website to ip, please get ip address manually"+bcolors.ENDC)
            exit()
        else:
            #print((bcolors.OKBLUE+"[+] %s = %s"+bcolors.ENDC) % (host, ip))
            print("{}[+] {} = {}".format(bcolors.OKBLUE,host,ip,bcolors.ENDC))
            return ip 
Example #30
Source File: gateway.py    From Jtyoui with MIT License 5 votes vote down vote up
def window_name_get_ip(window_name):
    """根据window的名字来获取ip地址

    :param window_name: window的名字
    :return: 返回当前计算机的ip地址
    """
    return socket.gethostbyname(window_name)