Python socket.gaierror() Examples
The following are 30
code examples of socket.gaierror().
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: simple_httpclient_test.py From tornado-zh with MIT License | 7 votes |
def test_ipv6(self): try: [sock] = bind_sockets(None, '::1', family=socket.AF_INET6) port = sock.getsockname()[1] self.http_server.add_socket(sock) except socket.gaierror as e: if e.args[0] == socket.EAI_ADDRFAMILY: # python supports ipv6, but it's not configured on the network # interface, so skip this test. return raise url = '%s://[::1]:%d/hello' % (self.get_protocol(), port) # ipv6 is currently enabled by default but can be disabled self.http_client.fetch(url, self.stop, allow_ipv6=False) response = self.wait() self.assertEqual(response.code, 599) self.http_client.fetch(url, self.stop) response = self.wait() self.assertEqual(response.body, b"Hello world!")
Example #3
Source File: simple_httpclient_test.py From tornado-zh with MIT License | 7 votes |
def test_ipv6(self): try: [sock] = bind_sockets(None, '::1', family=socket.AF_INET6) port = sock.getsockname()[1] self.http_server.add_socket(sock) except socket.gaierror as e: if e.args[0] == socket.EAI_ADDRFAMILY: # python supports ipv6, but it's not configured on the network # interface, so skip this test. return raise url = '%s://[::1]:%d/hello' % (self.get_protocol(), port) # ipv6 is currently enabled by default but can be disabled self.http_client.fetch(url, self.stop, allow_ipv6=False) response = self.wait() self.assertEqual(response.code, 599) self.http_client.fetch(url, self.stop) response = self.wait() self.assertEqual(response.body, b"Hello world!")
Example #4
Source File: serving.py From recruit with Apache License 2.0 | 7 votes |
def select_address_family(host, port): """Return ``AF_INET4``, ``AF_INET6``, or ``AF_UNIX`` depending on the host and port.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. # try: # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, # socket.SOCK_STREAM, 0, # socket.AI_PASSIVE) # if info: # return info[0][0] # except socket.gaierror: # pass if host.startswith("unix://"): return socket.AF_UNIX elif ":" in host and hasattr(socket, "AF_INET6"): return socket.AF_INET6 return socket.AF_INET
Example #5
Source File: serving.py From lambda-packs with MIT License | 6 votes |
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. # try: # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, # socket.SOCK_STREAM, 0, # socket.AI_PASSIVE) # if info: # return info[0][0] # except socket.gaierror: # pass if ':' in host and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
Example #6
Source File: serving.py From jbox with MIT License | 6 votes |
def select_ip_version(host, port): """Returns AF_INET4 or AF_INET6 depending on where to connect to.""" # disabled due to problems with current ipv6 implementations # and various operating systems. Probably this code also is # not supposed to work, but I can't come up with any other # ways to implement this. # try: # info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, # socket.SOCK_STREAM, 0, # socket.AI_PASSIVE) # if info: # return info[0][0] # except socket.gaierror: # pass if ':' in host and hasattr(socket, 'AF_INET6'): return socket.AF_INET6 return socket.AF_INET
Example #7
Source File: transport.py From smbprotocol with MIT License | 6 votes |
def socket_connect(func): def wrapped(self, *args, **kwargs): if not self._connected: log.info("Connecting to DirectTcp socket") try: self._sock = socket.create_connection((self.server, self.port), timeout=self.timeout) except (OSError, socket.gaierror) as err: raise ValueError("Failed to connect to '%s:%s': %s" % (self.server, self.port, str(err))) self._sock.settimeout(None) # Make sure the socket is in blocking mode. self._t_recv = threading.Thread(target=self.recv_thread, name="recv-%s:%s" % (self.server, self.port)) self._t_recv.daemon = True self._t_recv.start() self._connected = True func(self, *args, **kwargs) return wrapped
Example #8
Source File: server_setting.py From sslyze with GNU Affero General Public License v3.0 | 6 votes |
def _do_dns_lookup(hostname: str, port: int) -> str: try: addr_infos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.IPPROTO_IP) except (socket.gaierror, IndexError, ConnectionError): raise ServerHostnameCouldNotBeResolved(f"Could not resolve {hostname}") family, socktype, proto, canonname, sockaddr = addr_infos[0] # By default use the first DNS entry, IPv4 or IPv6 tentative_ip_addr = sockaddr[0] # But try to use IPv4 if we have both IPv4 and IPv6 addresses, to work around buggy networks for family, socktype, proto, canonname, sockaddr in addr_infos: if family == socket.AF_INET: tentative_ip_addr = sockaddr[0] return tentative_ip_addr
Example #9
Source File: netutil.py From tornado-zh with MIT License | 6 votes |
def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ if not ip or '\x00' in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True
Example #10
Source File: serving.py From recruit with Apache License 2.0 | 6 votes |
def get_sockaddr(host, port, family): """Return a fully qualified socket address that can be passed to :func:`socket.bind`.""" if family == af_unix: return host.split("://", 1)[1] try: res = socket.getaddrinfo( host, port, family, socket.SOCK_STREAM, socket.IPPROTO_TCP ) except socket.gaierror: return host, port return res[0][4]
Example #11
Source File: netutil.py From tornado-zh with MIT License | 6 votes |
def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. """ if not ip or '\x00' in ip: # getaddrinfo resolves empty strings to localhost, and truncates # on zero bytes. return False try: res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST) return bool(res) except socket.gaierror as e: if e.args[0] == socket.EAI_NONAME: return False raise return True
Example #12
Source File: ProxyTool.py From ProxHTTPSProxyMII with MIT License | 6 votes |
def tunnel_traffic(self): "Tunnel traffic to remote host:port" logger.info("%03d " % self.reqNum + Fore.CYAN + '[D] SSL Pass-Thru: https://%s/' % self.path) server_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: server_conn.connect((self.host, int(self.port))) self.wfile.write(("HTTP/1.1 200 Connection established\r\n" + "Proxy-agent: %s\r\n" % self.version_string() + "\r\n").encode('ascii')) read_write(self.connection, server_conn) except TimeoutError: self.wfile.write(b"HTTP/1.1 504 Gateway Timeout\r\n\r\n") logger.warning("%03d " % self.reqNum + Fore.YELLOW + 'Timed Out: https://%s:%s/' % (self.host, self.port)) except socket.gaierror as e: self.wfile.write(b"HTTP/1.1 503 Service Unavailable\r\n\r\n") logger.warning("%03d " % self.reqNum + Fore.YELLOW + '%s: https://%s:%s/' % (e, self.host, self.port)) finally: # We don't maintain a connection reuse pool, so close the connection anyway server_conn.close()
Example #13
Source File: wsgi_server.py From browserscope with Apache License 2.0 | 5 votes |
def start(self): """Starts the WsgiServer. This starts multiple _SingleAddressWsgiServers to bind the address in all address families. Raises: BindError: The address could not be bound. """ host, port = self.bind_addr try: info = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE) except socket.gaierror: if ':' in host: info = [(socket.AF_INET6, socket.SOCK_STREAM, 0, '', self.bind_addr)] else: info = [(socket.AF_INET, socket.SOCK_STREAM, 0, '', self.bind_addr)] if port != 0: self._start_all_fixed_port(info) else: for _ in range(_PORT_0_RETRIES): if self._start_all_dynamic_port(info): break else: raise BindError('Unable to find a consistent port %s' % host)
Example #14
Source File: network_udp.py From BiblioPixel with MIT License | 5 votes |
def _connect(self): try: self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if self._broadcast: self._sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) return self._sock except socket.gaierror: error = "Unable to connect to or resolve host: {}".format( self._host) log.error(error) raise IOError(error)
Example #15
Source File: __init__.py From earthengine with MIT License | 5 votes |
def _conn_request(self, conn, request_uri, method, body, headers): i = 0 seen_bad_status_line = False while i < RETRIES: i += 1 try: if hasattr(conn, 'sock') and conn.sock is None: conn.connect() conn.request(method, request_uri, body, headers) except socket.timeout: raise except socket.gaierror: conn.close() raise ServerNotFoundError("Unable to find the server at %s" % conn.host) except ssl_SSLError: conn.close() raise except socket.error, e: err = 0 if hasattr(e, 'args'): err = getattr(e, 'args')[0] else: err = e.errno if err == errno.ECONNREFUSED: # Connection refused raise except httplib.HTTPException: # Just because the server closed the connection doesn't apparently mean # that the server didn't send a response. if hasattr(conn, 'sock') and conn.sock is None: if i < RETRIES-1: conn.close() conn.connect() continue else: conn.close() raise if i < RETRIES-1: conn.close() conn.connect() continue
Example #16
Source File: mimetools.py From meddle with MIT License | 5 votes |
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 #17
Source File: interconnect.py From sawtooth-core with Apache License 2.0 | 5 votes |
def _need_enable_ipv6(self, socket_type): # Parse the URL parsed_url = urlparse(self._address) # Get the hostname portion hostname = parsed_url.hostname # See if the hostname is actually an interface name. # In this case, return False. if hostname in netifaces.interfaces(): return False # Next, try to directly parse the hostname to determine if we have a # literal IPv6 address. try: IPv6Address(hostname) return True except AddressValueError: pass # Finally, if we are setting up a zmq.DEALER docker (client), see if # the hostname resolves to an IPv6 address. if socket_type == zmq.DEALER: try: socket.getaddrinfo(parsed_url.hostname, 0, socket.AddressFamily.AF_INET6, socket.SocketKind.SOCK_STREAM) return True except socket.gaierror: pass # If none of the previous cases returns true, return false. return False
Example #18
Source File: io.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _get_socket_addresses(self): """Get Socket address information. :rtype: list """ family = socket.AF_UNSPEC if not socket.has_ipv6: family = socket.AF_INET try: addresses = socket.getaddrinfo(self._parameters['hostname'], self._parameters['port'], family) except socket.gaierror as why: raise AMQPConnectionError(why) return addresses
Example #19
Source File: impacketconnection.py From lsassy with MIT License | 5 votes |
def login(self): try: ip = list({addr[-1][0] for addr in getaddrinfo(self.hostname, 0, 0, 0, 0)})[0] if ip != self.hostname: self._log.debug("Host {} resolved to {}".format(self.hostname, ip)) except gaierror as e: return RetCode(ERROR_DNS_ERROR, e) try: self._conn = SMBConnection(self.hostname, ip, timeout=self.timeout) except Exception as e: return RetCode(ERROR_CONNECTION_ERROR, e) username = '' if not self.kerberos: username = self.username.split("@")[0] self._log.debug("Authenticating against {}".format(ip)) else: self._log.debug("Authenticating against {}".format(self.hostname)) try: if not self.kerberos: self._conn.login(username, self.password, domain=self.domain_name, lmhash=self.lmhash, nthash=self.nthash, ntlmFallback=True) else: self._conn.kerberosLogin(username, self.password, domain=self.domain_name, lmhash=self.lmhash, nthash=self.nthash, aesKey=self.aesKey, kdcHost=self.dc_ip) except SessionError as e: self._log.debug("Provided credentials : {}\\{}:{}".format(self.domain_name, username, self.password)) return RetCode(ERROR_LOGIN_FAILURE, e) except KerberosException as e: self._log.debug("Kerberos error") return RetCode(ERROR_LOGIN_FAILURE, e) except Exception as e: return RetCode(ERROR_UNDEFINED, e) return RetCode(ERROR_SUCCESS)
Example #20
Source File: replica_sorter.py From rucio with Apache License 2.0 | 5 votes |
def __get_lat_long(se, gi): """ Get the latitude and longitude on one host using the GeoLite DB :param se : A hostname or IP. :param gi : A Reader object (geoip2 API). """ try: ip = socket.getaddrinfo(se, None)[0][4][0] response = gi.city(ip) return response.location.latitude, response.location.longitude except socket.gaierror as error: # Host definitively unknown print(error) return None, None
Example #21
Source File: urllib2.py From meddle with MIT License | 5 votes |
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 #22
Source File: masterkey.py From geofront with GNU Affero General Public License v3.0 | 5 votes |
def __enter__(self) -> AbstractSet[Remote]: assert self.sftp_clients is None, 'the context is already started' sftp_clients = {} # type: Dict[Remote, Tuple[Transport, SFTPClient, AuthorizedKeyList]] # noqa: E501 for server in self.servers: try: transport = Transport((server.host, server.port)) transport.connect(username=server.user, pkey=self.old_key) except (OSError, SSHException) as e: for t, _, __ in sftp_clients.values(): t.close() lg = logging.getLogger(__name__ + '.TwoPhaseRenewal.__enter__') lg.exception( 'An exception rise during master key renewal ' '(%s -> %s, server: %s@%s:%d): %s', get_key_fingerprint(self.old_key), get_key_fingerprint(self.new_key), server.user, server.host, server.port, str(e) ) raise except socket.gaierror as e: raise ConnectionError( 'failed to connect: {0!s}\n{1!s}'.format(server, e) ) from e sftp_client = SFTPClient.from_transport(transport) authorized_keys = AuthorizedKeyList(sftp_client) sftp_clients[server] = transport, sftp_client, authorized_keys authorized_keys.append(self.new_key) self.sftp_clients = sftp_clients return self.servers
Example #23
Source File: smtplib.py From meddle with MIT License | 5 votes |
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. An SMTPConnectError is raised if the specified `host' doesn't respond correctly. If specified, `local_hostname` is used as the FQDN of the local host. By default, 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 #24
Source File: BotDigger.py From BotDigger with GNU General Public License v3.0 | 5 votes |
def domainExistenceCheck(domain): try: host = socket.gethostbyname(domain) #sys.stdout.write("IP: %s\n" % host) return 1 except socket.gaierror, err: #print "cannot resolve hostname: ", domain, err #sys.stdout.write("IP not found\n") return 0 # this function is currently NOT used
Example #25
Source File: ModuleDnsSpoof.py From 3vilTwinAttacker with MIT License | 5 votes |
def listItemclicked(self,pos): item = self.myListDns.selectedItems() self.listMenu= QMenu() menu = QMenu() additem = menu.addAction('Add Host') removeitem = menu.addAction('Remove Host') clearitem = menu.addAction('clear all') action = menu.exec_(self.myListDns.viewport().mapToGlobal(pos)) if action == removeitem: if item != []: self.myListDns.takeItem(self.myListDns.currentRow()) elif action == additem: text, resp = QInputDialog.getText(self, 'Add DNS', 'Enter the DNS for spoof hosts: ex: facebook.com') if resp: try: getip = str(Popen(['/bin/ping','-c1', '-w100', text], stdout=PIPE).stdout.read()).replace(')','') itemsexits = [] for index in xrange(self.myListDns.count()): itemsexits.append(str(self.myListDns.item(index).text())) for i in itemsexits: if search(str(text+':'+str(getip.split()[2]).replace('(','')),i): QMessageBox.information(self,'Dns Rsolver','this DNS already exist on List Attack') return item = QListWidgetItem() item.setText(text+':'+str(getip.split()[2]).replace('(','')) item.setSizeHint(QSize(30,30)) self.myListDns.addItem(item) except gaierror,e: QMessageBox.information(self,'error',str(e)) return
Example #26
Source File: mailer.py From king-phisher with BSD 3-Clause "New" or "Revised" License | 5 votes |
def guess_smtp_server_address(host, forward_host=None): """ Guess the IP address of the SMTP server that will be connected to given the SMTP host information and an optional SSH forwarding host. If a hostname is in use it will be resolved to an IP address, either IPv4 or IPv6 and in that order. If a hostname resolves to multiple IP addresses, None will be returned. This function is intended to guess the SMTP servers IP address given the client configuration so it can be used for SPF record checks. :param str host: The SMTP server that is being connected to. :param str forward_host: An optional host that is being used to tunnel the connection. :return: The IP address of the SMTP server. :rtype: None, :py:class:`ipaddress.IPv4Address`, :py:class:`ipaddress.IPv6Address` """ host = host.rsplit(':', 1)[0] if ipaddress.is_valid(host): ip = ipaddress.ip_address(host) if not ip.is_loopback: return ip else: info = None for family in (socket.AF_INET, socket.AF_INET6): try: info = socket.getaddrinfo(host, 1, family) except socket.gaierror: continue info = set(list([r[4][0] for r in info])) if len(info) != 1: return break if info: ip = ipaddress.ip_address(info.pop()) if not ip.is_loopback: return ip if forward_host: return guess_smtp_server_address(forward_host) return
Example #27
Source File: portscan.py From pynmap with GNU General Public License v3.0 | 5 votes |
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 #28
Source File: serving.py From lambda-packs with MIT License | 5 votes |
def get_sockaddr(host, port, family): """Returns a fully qualified socket address, that can properly used by socket.bind""" try: res = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM, socket.SOL_TCP) except socket.gaierror: return (host, port) return res[0][4]
Example #29
Source File: ipTools.py From quack with MIT License | 5 votes |
def isCloudFlare(link): parsed_uri = urlparse(link) domain = '{uri.netloc}'.format(uri = parsed_uri) try: origin = socket.gethostbyname(domain) iprange = requests.get('https://www.cloudflare.com/ips-v4').text ipv4 = [row.rstrip() for row in iprange.splitlines()] for i in range(len(ipv4)): if ipaddress.ip_address(origin) in ipaddress.ip_network(ipv4[i]): return True except socket.gaierror: print("\033[1;31m"+"[-]"+"\033[0m"+"Unable to verify if victim's IP address belong to a CloudFlare\'s subnet!") return False
Example #30
Source File: urllib2.py From meddle with MIT License | 5 votes |
def _safe_gethostbyname(host): try: return socket.gethostbyname(host) except socket.gaierror: return None