Python socket.gethostbyname() Examples

The following are code examples for showing how to use socket.gethostbyname(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: ssrspeed_backup   Author: mazhenting   File: mujson_mgr.py    GNU General Public License v3.0 7 votes vote down vote up
def getipaddr(self, ifname='eth0'):
		import socket
		import struct
		ret = '127.0.0.1'
		try:
			ret = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
		except:
			pass
		if ret == '127.0.0.1':
			try:
				import fcntl
				s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
				ret = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', ifname[:15]))[20:24])
			except:
				pass
		return ret 
Example 2
Project: pyblish-win   Author: pyblish   File: test_socket.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def testHostnameRes(self):
        # Testing hostname resolution mechanisms
        hostname = socket.gethostname()
        try:
            ip = socket.gethostbyname(hostname)
        except socket.error:
            # Probably name lookup wasn't set up right; skip this test
            self.skipTest('name lookup failure')
        self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
        try:
            hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
        except socket.error:
            # Probably a similar problem as above; skip this test
            self.skipTest('address lookup failure')
        all_host_names = [hostname, hname] + aliases
        fqhn = socket.getfqdn(ip)
        if not fqhn in all_host_names:
            self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names))) 
Example 3
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: connectionpool.py    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 4
Project: flasky   Author: RoseOu   File: connectionpool.py    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 5
Project: flasky   Author: RoseOu   File: connectionpool.py    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)

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

        return (scheme, host, port) == (self.scheme, self.host, self.port) 
Example 6
Project: dynamic-training-with-apache-mxnet-on-aws   Author: awslabs   File: diagnose.py    Apache License 2.0 6 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 7
Project: sic   Author: Yanixos   File: connectionpool.py    GNU 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)

        # 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 8
Project: bigquerylayers   Author: smandaric   File: connectionpool.py    GNU 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 9
Project: AshsSDK   Author: thehappydinoa   File: connectionpool.py    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 10
Project: AshsSDK   Author: thehappydinoa   File: connectionpool.py    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 11
Project: Kitsu.Bundle   Author: AeonLucid   File: connectionpool.py    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 12
Project: steamlink   Author: steamlink   File: steamlink.py    MIT License 6 votes vote down vote up
def __init__(self, conf=None):
		self.steam_id = 0
		self.autocreate = False
		if conf:
			self.desc = conf['description']
			self.autocreate = conf['autocreate']
			self.name = conf['name']
			self.steam_id = int(conf['id'])
		super().__init__(self.steam_id)
		self.cpubusy = 0
		self.my_ip_address = socket.gethostbyname(socket.gethostname())
		self.identity = "%s %s (%s)" % (PROJECT_PACKAGE_NAME, __version__, self.my_ip_address)
		self._public_topic_control_re = None

		_MQTT.set_msg_callback(self.on_data_msg)

		self._public_topic_control = _MQTT.get_public_control_topic()
		if self._public_topic_control is not None:
			_MQTT.set_public_control_callback(self.on_public_control_msg)
			self._public_topic_control_re = self._public_topic_control % "(.*)"

		self._mqtt_test_succeeded = False

		mq_cmd_msg = {"cmd": "selfcheck", "identity": self.identity}
		_MQTT.publish("store", json.dumps(mq_cmd_msg), sub="data") 
Example 13
Project: oscrypto   Author: wbond   File: test_tls.py    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 14
Project: oscrypto   Author: wbond   File: test_tls.py    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 15
Project: oscrypto   Author: wbond   File: test_tls.py    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 16
Project: jawfish   Author: war-and-code   File: urllib2.py    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 17
Project: jawfish   Author: war-and-code   File: connectionpool.py    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 18
Project: Repobot   Author: Desgard   File: connectionpool.py    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 19
Project: Repobot   Author: Desgard   File: connectionpool.py    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 20
Project: jupyter_drill   Author: JohnOmernik   File: drill_base.py    Apache License 2.0 6 votes vote down vote up
def getipurl(self, url):
        ts1 = url.split("://")
        scheme = ts1[0]
        t1 = ts1[1]
        ts2 = t1.split(":")
        host = ts2[0]
        port = ts2[1]
        try:
            ip = socket.gethostbyname(host)
        except:
            print("Failure on IP Lookup - URL: %s Host: %s Port: %s" % (url, host, port))
        return ip



    #Display Only functions 
Example 21
Project: lena   Author: coingraham   File: connectionpool.py    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 22
Project: vscode-mayapy   Author: FXTD-ODYSSEY   File: _pydev_uuid_old.py    MIT License 6 votes vote down vote up
def _ifconfig_getnode():
    """Get the hardware address on Unix by running ifconfig."""

    # This works on Linux ('' or '-a'), Tru64 ('-av'), but not all Unixes.
    for args in ('', '-a', '-av'):
        mac = _find_mac('ifconfig', args, ['hwaddr', 'ether'], lambda i: i+1)
        if mac:
            return mac

    import socket
    ip_addr = socket.gethostbyname(socket.gethostname())

    # Try getting the MAC addr from arp based on our IP address (Solaris).
    mac = _find_mac('arp', '-an', [ip_addr], lambda i: -1)
    if mac:
        return mac

    # This might work on HP-UX.
    mac = _find_mac('lanscan', '-ai', ['lan0'], lambda i: 0)
    if mac:
        return mac

    return None 
Example 23
Project: gist-alfred   Author: danielecook   File: connectionpool.py    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 24
Project: rebel-framework   Author: reb311ion   File: connectionpool.py    GNU 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)

        # 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 25
Project: LGWebOSRemote   Author: klattimer   File: auth.py    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 26
Project: LGWebOSRemote   Author: klattimer   File: remote.py    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 27
Project: pyblish-win   Author: pyblish   File: mimetools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def choose_boundary():
    """Return a string usable as a multipart boundary.

    The string chosen is unique within a single program run, and
    incorporates the user id (if available), process id (if available),
    and current time.  So it's very unlikely the returned string appears
    in message text, but there's no guarantee.

    The boundary contains dots so you have to quote it in the header."""

    global _prefix
    import time
    if _prefix is None:
        import socket
        try:
            hostid = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            hostid = '127.0.0.1'
        try:
            uid = repr(os.getuid())
        except AttributeError:
            uid = '1'
        try:
            pid = repr(os.getpid())
        except AttributeError:
            pid = '1'
        _prefix = hostid + '.' + uid + '.' + pid
    return "%s.%.3f.%d" % (_prefix, time.time(), _get_next_counter())


# Subroutines for decoding some common content-transfer-types 
Example 28
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _safe_gethostbyname(host):
    try:
        return socket.gethostbyname(host)
    except socket.gaierror:
        return None 
Example 29
Project: pyblish-win   Author: pyblish   File: urllib2.py    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 30
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def ftp_open(self, req):
        import ftplib
        import mimetypes
        host = req.get_host()
        if not host:
            raise URLError('ftp error: no host given')
        host, port = splitport(host)
        if port is None:
            port = ftplib.FTP_PORT
        else:
            port = int(port)

        # username/password handling
        user, host = splituser(host)
        if user:
            user, passwd = splitpasswd(user)
        else:
            passwd = None
        host = unquote(host)
        user = user or ''
        passwd = passwd or ''

        try:
            host = socket.gethostbyname(host)
        except socket.error, msg:
            raise URLError(msg) 
Example 31
Project: pyblish-win   Author: pyblish   File: urllib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def thishost():
    """Return the IP address of the current host."""
    global _thishost
    if _thishost is None:
        try:
            _thishost = socket.gethostbyname(socket.gethostname())
        except socket.gaierror:
            _thishost = socket.gethostbyname('localhost')
    return _thishost 
Example 32
Project: pyblish-win   Author: pyblish   File: smtplib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, host='', port=0, local_hostname=None,
                 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
        """Initialize a new instance.

        If specified, `host' is the name of the remote host to which to
        connect.  If specified, `port' specifies the port to which to connect.
        By default, smtplib.SMTP_PORT is used.  If a host is specified the
        connect method is called, and if it returns anything other than a
        success code an SMTPConnectError is raised.  If specified,
        `local_hostname` is used as the FQDN of the local host for the
        HELO/EHLO command.  Otherwise, the local hostname is found using
        socket.getfqdn().

        """
        self.timeout = timeout
        self.esmtp_features = {}
        if host:
            (code, msg) = self.connect(host, port)
            if code != 220:
                raise SMTPConnectError(code, msg)
        if local_hostname is not None:
            self.local_hostname = local_hostname
        else:
            # RFC 2821 says we should use the fqdn in the EHLO/HELO verb, and
            # if that can't be calculated, that we should use a domain literal
            # instead (essentially an encoded IP address like [A.B.C.D]).
            fqdn = socket.getfqdn()
            if '.' in fqdn:
                self.local_hostname = fqdn
            else:
                # We can't find an fqdn hostname, so use a domain literal
                addr = '127.0.0.1'
                try:
                    addr = socket.gethostbyname(socket.gethostname())
                except socket.gaierror:
                    pass
                self.local_hostname = '[%s]' % addr 
Example 33
Project: pyblish-win   Author: pyblish   File: test_urllibnet.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bad_address(self):
        # Make sure proper exception is raised when connecting to a bogus
        # address.
        bogus_domain = "sadflkjsasf.i.nvali.d"
        try:
            socket.gethostbyname(bogus_domain)
        except socket.gaierror:
            pass
        else:
            # This happens with some overzealous DNS providers such as OpenDNS
            self.skipTest("%r should not resolve for test to work" % bogus_domain)
        self.assertRaises(IOError,
                          # SF patch 809915:  In Sep 2003, VeriSign started
                          # highjacking invalid .com and .net addresses to
                          # boost traffic to their own site.  This test
                          # started failing then.  One hopes the .invalid
                          # domain will be spared to serve its defined
                          # purpose.
                          # urllib.urlopen, "http://www.sadflkjsasadf.com/")
                          urllib.urlopen, "http://sadflkjsasf.i.nvali.d/") 
Example 34
Project: pyblish-win   Author: pyblish   File: uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _arp_getnode():
    """Get the hardware address on Unix by running arp."""
    import os, socket
    try:
        ip_addr = socket.gethostbyname(socket.gethostname())
    except EnvironmentError:
        return None

    # Try getting the MAC addr from arp based on our IP address (Solaris).
    return _find_mac('arp', '-an', [ip_addr], lambda i: -1) 
Example 35
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: logentries_msg.py    MIT License 5 votes vote down vote up
def send_msg(module, token, msg, api, port):

    message = "{} {}\n".format(token, msg)

    api_ip = socket.gethostbyname(api)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((api_ip, port))
    try:
        if not module.check_mode:
            s.send(message)
    except Exception as e:
        module.fail_json(msg="failed to send message, msg=%s" % e)
    s.close() 
Example 36
Project: Splunk_CBER_App   Author: MHaggis   File: binding.py    MIT License 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 37
Project: plugin.program.steam.streaming   Author: Drakulix   File: service.py    MIT License 5 votes vote down vote up
def is_connected():
  try:
    # see if we can resolve the host name -- tells us if there is
    # a DNS listening
    host = socket.gethostbyname(REMOTE_SERVER)
    # connect to the host -- tells us if the host is actually
    # reachable
    s = socket.create_connection((host, 80), 2)
    return True
  except:
     pass
  return False 
Example 38
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def connect(self):
		try:
			common.internal_print("Starting client: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if self.os_type == common.OS_WINDOWS:
				# this should give back the default route interface IP
				default_host_ip = socket.gethostbyname(socket.gethostname())
				server_socket.bind((default_host_ip, 0))

			self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False

			self.communication_initialization()
			self.do_hello()
			self.communication(False)

		except KeyboardInterrupt:
			self.do_logoff()
			self.cleanup()
			raise

		self.cleanup()

		return 
Example 39
Project: XFLTReaT   Author: earthquake   File: ICMP.py    MIT License 5 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
			if self.os_type == common.OS_WINDOWS:
				# this should give back the default route interface IP
				default_host_ip = socket.gethostbyname(socket.gethostname())
				server_socket.bind((default_host_ip, 0))

			self.server_tuple = (self.config.get("Global", "remoteserverip"), self.ICMP_fake_serverport)
			self.comms_socket = server_socket
			self.serverorclient = 0
			self.authenticated = False
			self.communication_initialization()
			self.do_check()
			self.communication(True)

		except KeyboardInterrupt:
			self.cleanup()
			raise
		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)

		self.cleanup()

		return 
Example 40
Project: neos-classic-electrum-server   Author: neoscoin   File: ircthread.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def on_who(self, connection, event):
        line = str(event.arguments[6]).split()
        try:
            ip = socket.gethostbyname(line[1])
        except:
            logger.error("gethostbyname error " + line[1])
            return
        nick = event.arguments[4]
        host = line[1]
        ports = line[2:]
        self.queue.put(('join', [nick, ip, host, ports])) 
Example 41
Project: MetrixReloaded   Author: Scrounger   File: MetrixReloadedHelper.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def isconnected(logger, logPrefix="", host='8.8.8.8', port=53, timeout=1):
    try:
        socket.setdefaulttimeout(timeout)
        host = socket.gethostbyname('www.google.com')
        socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
        return True
    except Exception:
        logger.warn("%s no internet connection!", logPrefix)
        return False 
Example 42
Project: steamlink   Author: steamlink   File: web.py    MIT License 5 votes vote down vote up
def start(self):
		logger.info("%s starting, server %s port %s", self.name, self.host, self.port)
		self.sio.register_namespace(WebNamespace(self))
		#		self.runner = web.AppRunner(self.app)
		#		await self.runner.setup()
		#		self.site = web.TCPSite(self.runner, 'localhost', self.port)
		#		await self.site.start()

		logger.debug("%s: app started", self.name)

		scheme = 'https' if self.ssl_context else 'http'

		my_ip_address = socket.gethostbyname(socket.gethostname())
		desc = {'version': __version__}
		self.zeroconf_info = ServiceInfo("_http._tcp.local.",
										 "SteamLink Store._http._tcp.local.",
										 socket.inet_aton(my_ip_address), self.port, 0, 0,
										 desc, "steamlink.local.")
		self.zeroconf = Zeroconf()
		self.zeroconf.register_service(self.zeroconf_info)

		make_handler_kwargs = dict()
		make_handler_kwargs['access_log_format'] = self.access_log_format
		make_handler_kwargs['access_log'] = self.access_log

		self.handler = self.app.make_handler(loop=self.loop, **make_handler_kwargs)

		self.server = await self.loop.create_server(
			self.handler, self.host, self.port,
			ssl=self.ssl_context,
			backlog=self.backlog) 
Example 43
Project: dvrip   Author: alexshpilkin   File: discover.py    Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def run(args: List[str]) -> None:
	try:
		opts, args = getopt(args, 'i:t:')
	except GetoptError:
		usage()
	if args:
		usage()

	interface = ''
	timeout   = 1.0
	for opt, arg in opts:
		if opt == '-i':
			try:
				interface = gethostbyname(arg)
			except OSError as e:
				osexit(e, EX_NOHOST)
		if opt == '-t':
			try:
				timeout = float(arg)
			except ValueError:
				usage()

	for result in DVRIPClient.discover(interface, timeout):
		print('{} {} {} {}/{} via {} port {} channels {}'
		      .format(result.serial, result.mac, result.name,
		              result.host, result.mask, result.router,
		              result.tcpport, result.channels)) 
Example 44
Project: rtp_cluster   Author: sippy   File: SipConf.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __str__(self):
        try:
            return gethostbyname(gethostname())
        except:
            return '127.0.0.1' 
Example 45
Project: gamblerscan   Author: mthbernardes   File: gamblerscan.py    GNU General Public License v2.0 5 votes vote down vote up
def resolve(host):
	try:
		address = socket.gethostbyname(host)
		return address
	except:
		print '[+] - Address resolve isn\'t possible'
		exit()
#Port scan function 
Example 46
Project: oscrypto   Author: wbond   File: test_tls.py    MIT License 5 votes vote down vote up
def test_tls_closed_connection_read(self):
        ip = socket.gethostbyname('badtls.io')

        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)
                tsock = tls.TLSSocket.wrap(sock, 'badtls.io')
                send_sock.close()
                tsock.read(8192)
            finally:
                recv_sock.close()
                server.close() 
Example 47
Project: oscrypto   Author: wbond   File: test_tls.py    MIT License 5 votes vote down vote up
def test_tls_closed_connection_write(self):
        ip = socket.gethostbyname('badtls.io')

        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)
                tsock = tls.TLSSocket.wrap(sock, 'badtls.io')
                send_sock.close()
                tsock.write(b'GET / HTTP/1.1\r\n')
                tsock.write(b'\r\n')
                tsock.write(b'\r\n')
            finally:
                recv_sock.close()
                server.close() 
Example 48
Project: telegram-icecast2-bot   Author: hmsuorg   File: __init__.py    MIT License 5 votes vote down vote up
def get_stats(self):

        """get_stats"""

        for srv in ICECAST2_SERVERS:

            try:
                srv_request = request.urlopen('{}/{}'.format(srv, ICECAST2_STATS_FILE), None, 3)

            except URLError:
                # no stream or server is down
                pass

            else:

                if srv_request.getcode() == 200:

                    stats_data = json.loads(srv_request.read().decode('utf-8'))

                    if 'icestats' in stats_data and 'source' in stats_data['icestats']:

                        # if the server limit reach SERVERS_LIMIT - 5, will not be listen as available
                        if stats_data['icestats']['source']['listeners'] >= SERVERS_LIMIT - 5:
                            continue

                        radio = RadioStream()

                        radio.stream = stats_data['icestats']['source']['listenurl']

                        if SSL is True and radio.stream.startswith('http:'):
                            radio.stream = radio.stream.replace('http', 'https')

                        radio.server = socket.gethostbyname(stats_data['icestats']['host'])
                        radio.online = stats_data['icestats']['source']['listeners']
                        self.servers.append(radio)

        return self.servers 
Example 49
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 5 votes vote down vote up
def get_names(self):
        if FileHandler.names is None:
            FileHandler.names = (socket.gethostbyname('localhost'),
                                 socket.gethostbyname(socket.gethostname()))
        return FileHandler.names

    # not entirely sure what the rules are here 
Example 50
Project: jawfish   Author: war-and-code   File: urllib2.py    MIT License 5 votes vote down vote up
def ftp_open(self, req):
        host = req.get_host()
        if not host:
            raise IOError('ftp error', 'no host given')
        # XXX handle custom username & password
        try:
            host = socket.gethostbyname(host)
        except socket.error(msg):
            raise URLError(msg)
        host, port = splitport(host)
        if port is None:
            port = ftplib.FTP_PORT
        path, attrs = splitattr(req.get_selector())
        path = unquote(path)
        dirs = path.split('/')
        dirs, file = dirs[:-1], dirs[-1]
        if dirs and not dirs[0]:
            dirs = dirs[1:]
        user = passwd = '' # XXX
        try:
            fw = self.connect_ftp(user, passwd, host, port, dirs)
            type = file and 'I' or 'D'
            for attr in attrs:
                attr, value = splitattr(attr)
                if attr.lower() == 'type' and \
                   value in ('a', 'A', 'i', 'I', 'd', 'D'):
                    type = value.upper()
            fp, retrlen = fw.retrfile(file, type)
            headers = ""
            mtype = mimetypes.guess_type(req.get_full_url())[0]
            if mtype:
                headers += "Content-Type: %s\n" % mtype
            if retrlen is not None and retrlen >= 0:
                headers += "Content-Length: %d\n" % retrlen
            sf = StringIO(headers)
            headers = mimetools.Message(sf)
            return addinfourl(fp, headers, req.get_full_url())
        except ftplib.all_errors(msg):
            raise IOError(('ftp error', msg), sys.exc_info()[2])