Python socket.getfqdn() Examples
The following are 30
code examples of socket.getfqdn().
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 |
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: node.py From aerospike-admin with Apache License 2.0 | 6 votes |
def getfqdn(address, timeout=0.5): # note: cannot use timeout lib because signal must be run from the # main thread result = [address] def helper(): result[0] = socket.getfqdn(address) t = threading.Thread(target=helper) t.daemon = True t.start() t.join(timeout) return result[0]
Example #3
Source File: network.py From network_tech with Apache License 2.0 | 6 votes |
def ptr_lookup(cls, network): ip = str(ipaddress.ip_interface(network).ip) try: primary_hostname, alias_hostnames, other_ips = socket.gethostbyaddr(ip) except socket.herror as e: logger.debug('DNS Reverse Lookup Error {}'.format(e)) return Html.div('DNS: n/a') content = Html.div( 'DNS: {}'.format( socket.getfqdn(primary_hostname) ) ) if alias_hostnames: content += Html.div('DNS Aliases:') for hostname in alias_hostnames: fqdn_hostname = socket.getfqdn(hostname) logger.debug('Alias {} FQDN {}'.format(hostname, fqdn_hostname)) content += Html.div(fqdn_hostname) return content
Example #4
Source File: smtpd.py From ironpython2 with Apache License 2.0 | 6 votes |
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return
Example #5
Source File: utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def make_msgid(idstring=None, domain=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring if domain is None: domain = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain) return msgid
Example #6
Source File: test_socket.py From oss-ftp with MIT License | 6 votes |
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 #7
Source File: test_socket.py From ironpython2 with Apache License 2.0 | 6 votes |
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 #8
Source File: utils.py From verge3d-blender-addon with GNU General Public License v3.0 | 6 votes |
def make_msgid(idstring=None, domain=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring if domain is None: domain = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain) return msgid
Example #9
Source File: distributed.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def host_is_local(hostname, port=22): # no port specified, just use the ssh port """ Returns True if the hostname points to the localhost, otherwise False. """ hostname = socket.getfqdn(hostname) if hostname in ("localhost", "0.0.0.0", "127.0.0.1", "1.0.0.127.in-addr.arpa", "1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa"): return True localhost = socket.gethostname() if hostname == localhost: return True localaddrs = socket.getaddrinfo(localhost, port) targetaddrs = socket.getaddrinfo(hostname, port) for (ignored_family, ignored_socktype, ignored_proto, ignored_canonname, sockaddr) in localaddrs: for (ignored_rfamily, ignored_rsocktype, ignored_rproto, ignored_rcanonname, rsockaddr) in targetaddrs: if rsockaddr[0] == sockaddr[0]: return True return False
Example #10
Source File: test_distributed.py From neat-python with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_host_is_local(): """test for neat.distributed.host_is_local""" tests = ( # (hostname or ip, expected value) ("localhost", True), ("0.0.0.0", True), ("127.0.0.1", True), # ("::1", True), # depends on IP, etc setup on host to work right (socket.gethostname(), True), (socket.getfqdn(), True), ("github.com", False), ("google.de", False), ) for hostname, islocal in tests: try: result = neat.host_is_local(hostname) except EnvironmentError: # give more feedback print("test_host_is_local: Error with hostname {0!r} (expected {1!r})".format(hostname, islocal)) raise else: # if do not want to do 'raise' above for some cases assert result == islocal, "Hostname/IP: {h}; Expected: {e}; Got: {r!r}".format( h=hostname, e=islocal, r=result)
Example #11
Source File: utils.py From misp42splunk with GNU Lesser General Public License v3.0 | 6 votes |
def make_msgid(idstring=None, domain=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. Optional domain if given provides the portion of the message id after the '@'. It defaults to the locally defined hostname. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring if domain is None: domain = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain) return msgid
Example #12
Source File: smtpd.py From oss-ftp with MIT License | 6 votes |
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return
Example #13
Source File: connection.py From python-mysql-pool with MIT License | 6 votes |
def report_failure(self, server_uuid, errno): """Report failure to Fabric This method sets the status of a MySQL server identified by server_uuid. """ if not self._report_errors: return errno = int(errno) current_host = socket.getfqdn() if errno in REPORT_ERRORS or errno in REPORT_ERRORS_EXTRA: _LOGGER.debug("Reporting error %d of server %s", errno, server_uuid) inst = self.get_instance() try: data = inst.execute('threat', 'report_failure', server_uuid, current_host, errno) FabricResponse(data) except (Fault, socket.error) as exc: _LOGGER.debug("Failed reporting server to Fabric (%s)", str(exc)) # Not requiring further action
Example #14
Source File: utils.py From oss-ftp with MIT License | 6 votes |
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons.
Example #15
Source File: utils.py From ironpython2 with Apache License 2.0 | 6 votes |
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <142480216486.20800.16526388040877946887@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = int(time.time()*100) pid = os.getpid() randint = random.getrandbits(64) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%d.%d.%d%s@%s>' % (timeval, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons.
Example #16
Source File: smtpd.py From meddle with MIT License | 6 votes |
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return
Example #17
Source File: utils.py From BinderFilter with MIT License | 6 votes |
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons.
Example #18
Source File: utils.py From meddle with MIT License | 6 votes |
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons.
Example #19
Source File: smtpd.py From BinderFilter with MIT License | 6 votes |
def __init__(self, server, conn, addr): asynchat.async_chat.__init__(self, conn) self.__server = server self.__conn = conn self.__addr = addr self.__line = [] self.__state = self.COMMAND self.__greeting = 0 self.__mailfrom = None self.__rcpttos = [] self.__data = '' self.__fqdn = socket.getfqdn() try: self.__peer = conn.getpeername() except socket.error, err: # a race condition may occur if the other end is closing # before we can get the peername self.close() if err[0] != errno.ENOTCONN: raise return
Example #20
Source File: _internal.py From tf-yarn with Apache License 2.0 | 6 votes |
def reserve_sock_addr() -> Iterator[Tuple[str, int]]: """Reserve an available TCP port to listen on. The reservation is done by binding a TCP socket to port 0 with ``SO_REUSEPORT`` flag set (requires Linux >=3.9). The socket is then kept open until the generator is closed. To reduce probability of 'hijacking' port, socket should stay open and should be closed _just before_ starting of ``tf.train.Server`` """ so_reuseport = get_so_reuseport() if so_reuseport is None: raise RuntimeError( "SO_REUSEPORT is not supported by the operating system") from None with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: sock.setsockopt(socket.SOL_SOCKET, so_reuseport, 1) sock.bind(("", 0)) _ipaddr, port = sock.getsockname() yield (socket.getfqdn(), port)
Example #21
Source File: test_socket.py From BinderFilter with MIT License | 6 votes |
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 return 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 return 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 #22
Source File: utils.py From Computable with MIT License | 6 votes |
def make_msgid(idstring=None): """Returns a string suitable for RFC 2822 compliant Message-ID, e.g: <20020201195627.33539.96671@nightshade.la.mastaler.com> Optional idstring if given is a string used to strengthen the uniqueness of the message id. """ timeval = time.time() utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval)) pid = os.getpid() randint = random.randrange(100000) if idstring is None: idstring = '' else: idstring = '.' + idstring idhost = socket.getfqdn() msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, idhost) return msgid # These functions are in the standalone mimelib version only because they've # subsequently been fixed in the latest Python versions. We use this to worm # around broken older Pythons.
Example #23
Source File: test_result.py From tox with MIT License | 6 votes |
def test_set_header(pkg): replog = ResultLog() d = replog.dict assert replog.dict == d assert replog.dict["reportversion"] == "1" assert replog.dict["toxversion"] == tox.__version__ assert replog.dict["platform"] == sys.platform assert replog.dict["host"] == socket.getfqdn() expected = {"basename": "hello-1.0.tar.gz", "sha256": pkg.computehash("sha256")} env_log = replog.get_envlog("a") env_log.set_header(installpkg=pkg) assert env_log.dict["installpkg"] == expected data = replog.dumps_json() replog2 = ResultLog.from_json(data) assert replog2.dict == replog.dict
Example #24
Source File: px.py From px with MIT License | 5 votes |
def address_string(self): host, port = self.client_address[:2] #return socket.getfqdn(host) return host
Example #25
Source File: system.py From privacyidea with GNU Affero General Public License v3.0 | 5 votes |
def get_config_documentation(): """ returns an restructured text document, that describes the complete configuration. """ P = PolicyClass() config = get_from_config() resolvers = get_resolver_list() realms = get_realms() policies = P.list_policies() admins = get_db_admins() context = {"system": socket.getfqdn(socket.gethostname()), "date": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"), "systemconfig": config, "appconfig": current_app.config, "resolverconfig": resolvers, "realmconfig": realms, "policyconfig": policies, "admins": admins} g.audit_object.log({"success": True}) # Three or more line breaks will be changed to two. return send_file(re.sub("\n{3,}", "\n\n", render_template("documentation.rst", context=context)), 'documentation.rst', content_type='text/plain')
Example #26
Source File: client.py From ParadoxIP150v2 with Eclipse Public License 1.0 | 5 votes |
def connect_srv(self, domain=None, keepalive=60, bind_address=""): """Connect to a remote broker. domain is the DNS domain to search for SRV records; if None, try to determine local domain name. keepalive and bind_address are as for connect() """ if HAVE_DNS is False: raise ValueError('No DNS resolver library found.') if domain is None: domain = socket.getfqdn() domain = domain[domain.find('.') + 1:] try: rr = '_mqtt._tcp.%s' % domain if self._ssl is not None: # IANA specifies secure-mqtt (not mqtts) for port 8883 rr = '_secure-mqtt._tcp.%s' % domain answers = [] for answer in dns.resolver.query(rr, dns.rdatatype.SRV): addr = answer.target.to_text()[:-1] answers.append((addr, answer.port, answer.priority, answer.weight)) except (dns.resolver.NXDOMAIN, dns.resolver.NoAnswer, dns.resolver.NoNameservers): raise ValueError("No answer/NXDOMAIN for SRV in %s" % (domain)) # FXME: doesn't account for weight for answer in answers: host, port, prio, weight = answer try: return self.connect(host, port, keepalive, bind_address) except: pass raise ValueError("No SRV hosts responded")
Example #27
Source File: smtp.py From heralding with GNU General Public License v3.0 | 5 votes |
def setfqdn(self): if 'fqdn' in self._options['protocol_specific_data'] and self._options[ 'protocol_specific_data']['fqdn']: SMTPHandler.fqdn = self._options['protocol_specific_data']['fqdn'] else: while True: fqdn = await self.loop.run_in_executor(None, socket.getfqdn) SMTPHandler.fqdn = fqdn await asyncio.sleep(1800, loop=self.loop)
Example #28
Source File: test_kerberos_endpoints.py From airflow with Apache License 2.0 | 5 votes |
def test_trigger_dag(self): with self.app.test_client() as client: url_template = '/api/experimental/dags/{}/dag_runs' response = client.post( url_template.format('example_bash_operator'), data=json.dumps(dict(run_id='my_run' + datetime.now().isoformat())), content_type="application/json" ) self.assertEqual(401, response.status_code) response.url = 'http://{}'.format(socket.getfqdn()) class Request: headers = {} response.request = Request() response.content = '' response.raw = mock.MagicMock() response.connection = mock.MagicMock() response.connection.send = mock.MagicMock() # disable mutual authentication for testing CLIENT_AUTH.mutual_authentication = 3 # case can influence the results CLIENT_AUTH.hostname_override = socket.getfqdn() CLIENT_AUTH.handle_response(response) self.assertIn('Authorization', response.request.headers) response2 = client.post( url_template.format('example_bash_operator'), data=json.dumps(dict(run_id='my_run' + datetime.now().isoformat())), content_type="application/json", headers=response.request.headers ) self.assertEqual(200, response2.status_code)
Example #29
Source File: http.py From ACE with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): super().__init__(workload_type='http', delete_files=True, *args, **kwargs) # the location of the incoming http streams self.bro_http_dir = os.path.join(saq.DATA_DIR, saq.CONFIG['bro']['http_dir']) # the list of streams (connection ids) that we need to process self.stream_list = collections.deque() # for tool_instance self.hostname = socket.getfqdn()
Example #30
Source File: ace_api.py From ACE with Apache License 2.0 | 5 votes |
def __init__(self, *args, **kwargs): # these just get passed to ace_api.submit function self.submit_args = args self.submit_kwargs = kwargs self.remote_host = default_remote_host self.ssl_verification = default_ssl_verification # default submission self.submit_kwargs = { 'description': '', 'analysis_mode': 'analysis', 'tool': 'ace_api', 'tool_instance': 'ace_api:{}'.format(socket.getfqdn()), 'type': 'generic', 'event_time': None, 'details': {}, 'observables': [], 'tags': [], 'files': [], } for key, value in kwargs.items(): if key in self.submit_kwargs: self.submit_kwargs[key] = value elif key == 'desc': self.submit_kwargs['description'] = value elif key == 'alert_type': self.submit_kwargs['type'] = value else: logging.debug("ignoring parameter {}".format(key)) # this gets set after a successful call to submit self.uuid = None