Python socket.herror() Examples

The following are 30 code examples of socket.herror(). 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: common.py    From Yuki-Chan-The-Auto-Pentest with MIT License 7 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example #2
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #3
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #4
Source File: console_proxy_thread.py    From openmano with Apache License 2.0 6 votes vote down vote up
def on_close(self, sock, cause):
        if sock not in self.channel:
            return  #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
        info = self.channel[sock]
        #debug info
        sockname = "client" if sock is info["clientsock"] else "server"
        print self.name, ": del connection %s %s at %s side" % (info["name"], cause, sockname)
        #close sockets
        try:
            # close the connection with client
            info["clientsock"].close()  # equivalent to do self.s.close()
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_close client socket %s: %s" % (type(e).__name__, str(e) )
        try:
            # close the connection with remote server
            info["serversock"].close()
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            print self.name, ": Exception on_close server socket %s: %s" % (type(e).__name__, str(e) )
        
        #remove objects from input_list
        self.input_list.remove(info["clientsock"])
        self.input_list.remove(info["serversock"])
        # delete both objects from channel dict
        del self.channel[info["clientsock"]]
        del self.channel[info["serversock"]] 
Example #5
Source File: common.py    From ITWSV with MIT License 6 votes vote down vote up
def ip2name(addr):
    if not ip2name.resolve:
        return addr
    try:
        if addr in ip2name.cache:
            return ip2name.cache[addr]
        # FIXME: Workaround Python bug
        # Need double try/except to catch the bug
        try:
            name = gethostbyaddr(addr)[0]
        except KeyboardInterrupt:
            raise
    except (socket_host_error, ValueError):
        name = addr
    except (socket_host_error, KeyboardInterrupt, ValueError):
        ip2name.resolve = False
        name = addr
    ip2name.cache[addr] = name
    return name 
Example #6
Source File: FICSConnection.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def start(self):
        try:
            if not self.isConnected():
                await self._connect()
            while self.isConnected():
                await self.client.parse()
        except CancelledError:
            pass
        except Exception as err:
            exc_type, exc_value, exc_traceback = sys.exc_info()
            traceback.print_exception(exc_type, exc_value, exc_traceback)
            log.info("FICSConnection.run: %s" % repr(err),
                     extra={"task": (self.host, "raw")})
            self.close()
            if isinstance(err,
                          (IOError, LogOnException, EOFError, socket.error,
                           socket.gaierror, socket.herror)):
                self.emit("error", err)
            else:
                raise
        finally:
            if isinstance(self, FICSMainConnection):
                self.emit("disconnected") 
Example #7
Source File: console_proxy_thread.py    From openmano with Apache License 2.0 6 votes vote down vote up
def on_recv(self, sock):
        if sock not in self.channel:
            return  #can happen if there is data ready to received at both sides and the channel has been deleted. QUITE IMPROBABLE but just in case
        info = self.channel[sock]
        peersock = info["serversock"] if sock is info["clientsock"] else info["clientsock"]
        try:
            data = sock.recv(self.buffer_size)
            if len(data) == 0:
                self.on_close(sock, "peer closed")
            else:
                #print self.data
                sock = peersock
                peersock.send(data)
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            #print self.name, ": Exception %s: %s" % (type(e).__name__, str(e) )
            self.on_close(sock, "Exception %s: %s" % (type(e).__name__, str(e) ))

        

    #def start_timeout(self):
    #    self.timeout = time.time() + 120 
Example #8
Source File: FICSConnection.py    From pychess with GNU General Public License v3.0 6 votes vote down vote up
def close(self):
        if isinstance(self.client, PredictionsTelnet) and self.set_user_vars:
            self.client.run_command("set open 0")
            self.client.run_command("set gin 0")
            self.client.run_command("set availinfo 0")
        try:
            self.lvm.stop()
        except AttributeError:
            pass
        except Exception as err:
            if not isinstance(err,
                              (IOError, LogOnException, EOFError, socket.error,
                               socket.gaierror, socket.herror)):
                raise
        finally:
            FICSConnection.close(self) 
Example #9
Source File: console_proxy_thread.py    From openmano with Apache License 2.0 6 votes vote down vote up
def __init__(self, host, port, console_host, console_port):
        try:
            threading.Thread.__init__(self)
            self.console_host = console_host
            self.console_port = console_port
            self.host = host
            self.port = port
            self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.server.bind((host, port))
            self.server.listen(200)
            #TODO timeout in a lock section can be used to autoterminate the thread
            #when inactivity and timeout<time : set timeout=0 and terminate
            #from outside, close class when timeout==0; set timeout=time+120 when adding a new console on this thread
            #set self.timeout = time.time() + 120 at init
            self.name = "ConsoleProxy " + console_host + ":" + str(console_port)
            self.input_list = [self.server]
            self.channel = {}
            self.terminate = False #put at True from outside to force termination
        except (socket.error, socket.herror, socket.gaierror, socket.timeout) as e:
            if e is socket.error and e.errno==98:
                raise ConsoleProxyExceptionPortUsed("socket.error " + str(e))
            raise ConsoleProxyException(type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0])) ) 
Example #10
Source File: monitors.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def send(self, metric_pb):
    body = self.encode_to_json(metric_pb)

    try:
      resp, content = self._http.request(self._endpoint,
          method='POST',
          body=body,
          headers={'Content-Type': 'application/json'})
      if resp.status == 200:
        self._failed = False
      else:
        logging.warning('HttpsMonitor.send received status %d: %s', resp.status,
                        content)
        self._failed = True
    except (ValueError, errors.Error,
            socket.timeout, socket.error, socket.herror, socket.gaierror,
            httplib2.HttpLib2Error):
      logging.exception('HttpsMonitor.send failed')
      self._failed = True 
Example #11
Source File: checkdmarc.py    From checkdmarc with Apache License 2.0 6 votes vote down vote up
def _get_reverse_dns(ip_address):
    """
    Queries for an IP addresses reverse DNS hostname(s)

    Args:
        ip_address (str): An IPv4 or IPv6 address

    Returns:
        list: A list of reverse DNS hostnames

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        results = socket.gethostbyaddr(ip_address)
        hostnames = [results[0]] + results[1]
    except socket.herror:
        return []
    except Exception as error:
        raise DNSException(error)

    return hostnames 
Example #12
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #13
Source File: utils.py    From lbry-sdk with MIT License 6 votes vote down vote up
def check_connection(server="lbry.com", port=80, timeout=5) -> bool:
    """Attempts to open a socket to server:port and returns True if successful."""
    log.debug('Checking connection to %s:%s', server, port)
    try:
        server = socket.gethostbyname(server)
        socket.create_connection((server, port), timeout).close()
        return True
    except (socket.gaierror, socket.herror):
        log.debug("Failed to connect to %s:%s. Unable to resolve domain. Trying to bypass DNS",
                  server, port)
        try:
            server = "8.8.8.8"
            port = 53
            socket.create_connection((server, port), timeout).close()
            return True
        except OSError:
            return False
    except OSError:
        return False 
Example #14
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #15
Source File: checkdmarc.py    From Scrummage with GNU General Public License v3.0 6 votes vote down vote up
def _get_reverse_dns(ip_address):
    """
    Queries for an IP addresses reverse DNS hostname(s)

    Args:
        ip_address (str): An IPv4 or IPv6 address

    Returns:
        list: A list of reverse DNS hostnames

    Raises:
        :exc:`checkdmarc.DNSException`

    """
    try:
        results = socket.gethostbyaddr(ip_address)
        hostnames = [results[0]] + results[1]
    except socket.herror:
        return []
    except Exception as error:
        raise DNSException(error)

    return hostnames 
Example #16
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #17
Source File: network.py    From network_tech with Apache License 2.0 6 votes vote down vote up
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 #18
Source File: __init__.py    From whois with MIT License 6 votes vote down vote up
def whois(url, command=False, flags=0):
    # clean domain to expose netloc
    ip_match = IPV4_OR_V6.match(url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = extract_domain(result[0])
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read().decode()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain.encode('idna'), flags)
    return WhoisEntry.load(domain, text) 
Example #19
Source File: __init__.py    From webdigger with GNU General Public License v3.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example #20
Source File: __init__.py    From Belati with GNU General Public License v2.0 6 votes vote down vote up
def whois(url, command=False):
    # clean domain to expose netloc
    ip_match = re.match(r"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$", url)
    if ip_match:
        domain = url
        try:
            result = socket.gethostbyaddr(url)
        except socket.herror as e:
            pass
        else:
            domain = result[0]
    else:
        domain = extract_domain(url)
    if command:
        # try native whois command
        r = subprocess.Popen(['whois', domain], stdout=subprocess.PIPE)
        text = r.stdout.read()
    else:
        # try builtin client
        nic_client = NICClient()
        text = nic_client.whois_lookup(None, domain, 0)
    return WhoisEntry.load(domain, text) 
Example #21
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #22
Source File: monitors.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def send(self, metric_pb):
    body = self.encode_to_json(metric_pb)

    try:
      resp, content = self._http.request(self._endpoint,
          method='POST',
          body=body,
          headers={'Content-Type': 'application/json'})
      if resp.status == 200:
        self._failed = False
      else:
        logging.warning('HttpsMonitor.send received status %d: %s', resp.status,
                        content)
        self._failed = True
    except (ValueError, errors.Error,
            socket.timeout, socket.error, socket.herror, socket.gaierror,
            httplib2.HttpLib2Error):
      logging.exception('HttpsMonitor.send failed')
      self._failed = True 
Example #23
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #24
Source File: __init__.py    From smarthome with GNU General Public License v3.0 6 votes vote down vote up
def get_local_hostname(self):
        """
        Returns the local hostname under which the webinterface can be reached

        :return: fully qualified hostname
        :rtype: str
        """
        import socket
        try:
            return socket.gethostbyaddr(self.get_local_ip_address())[0] # can fail with default /etc/hosts
        except socket.herror:
            try:
                return socket.gethostbyaddr("127.0.1.1")[0]	# in debian based systems hostname is assigned to "127.0.1.1" by default
            except socket.herror:
                try:
                    return socket.gethostbyaddr("127.0.0.1")[0]	# 'localhost' in most cases
                except socket.herror:
                    return "localhost"	# should not happen 
Example #25
Source File: httplib2_utils.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def request(self, uri, method='GET', body=None, *args, **kwargs):
    for i in range(1, self._max_tries + 1):
      try:
        response, content = self._http.request(uri, method, body, *args,
                                               **kwargs)

        if self._retrying_statuses_fn(response.status):
          logging.info('RetriableHttp: attempt %d receiving status %d, %s',
                       i, response.status,
                       'final attempt' if i == self._max_tries else \
                       'will retry')
        else:
          break
      except (ValueError, errors.Error,
              socket.timeout, socket.error, socket.herror, socket.gaierror,
              httplib2.HttpLib2Error) as error:
        logging.info('RetriableHttp: attempt %d received exception: %s, %s',
                     i, error, 'final attempt' if i == self._max_tries else \
                     'will retry')
        if i == self._max_tries:
          raise
      time.sleep(self._backoff_time)

    return response, content 
Example #26
Source File: monitors.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def send(self, metric_pb):
    body = self.encode_to_json(metric_pb)

    try:
      resp, content = self._http.request(self._endpoint,
          method='POST',
          body=body,
          headers={'Content-Type': 'application/json'})
      if resp.status == 200:
        self._failed = False
      else:
        logging.warning('HttpsMonitor.send received status %d: %s', resp.status,
                        content)
        self._failed = True
    except (ValueError, errors.Error,
            socket.timeout, socket.error, socket.herror, socket.gaierror,
            httplib2.HttpLib2Error):
      logging.exception('HttpsMonitor.send failed')
      self._failed = True 
Example #27
Source File: ip_generator.py    From AutoSploit with GNU General Public License v3.0 6 votes vote down vote up
def check_ip_alive(ip):
    """
    efficiently check if an IP address is alive or not
    by using the socket.gethostbyaddr function
    """
    def is_valid_ip(ip):
        try:
            socket.inet_aton(ip)
            return True
        except:
            return False

    try:
        if not is_valid_ip(ip):
            return False
        else:
            return socket.gethostbyaddr(ip)
    except socket.herror:
        return False 
Example #28
Source File: monitors.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def send(self, metric_pb):
    body = self.encode_to_json(metric_pb)

    try:
      resp, content = self._http.request(self._endpoint,
          method='POST',
          body=body,
          headers={'Content-Type': 'application/json'})
      if resp.status == 200:
        self._failed = False
      else:
        logging.warning('HttpsMonitor.send received status %d: %s', resp.status,
                        content)
        self._failed = True
    except (ValueError, errors.Error,
            socket.timeout, socket.error, socket.herror, socket.gaierror,
            httplib2.HttpLib2Error):
      logging.exception('HttpsMonitor.send failed')
      self._failed = True 
Example #29
Source File: blacklist.py    From ip-reputation-monitoring with GNU General Public License v3.0 5 votes vote down vote up
def _is_blacklisted(dnsbl_uri, addr):
    try:
        reversed_ip = '.'.join(addr.split('.')[::-1])
        addr = '.'.join([reversed_ip, dnsbl_uri])

        # For a given ip such 1.2.3.4, addr should look like:
        # 4.3.2.1.dnsbl_uri
        socket.gethostbyname_ex(addr)
        return True
    except (IndexError, socket.error, socket.gaierror, socket.herror, socket.timeout):
        # Not blacklisted
        return False 
Example #30
Source File: route_cache.py    From vortessence with GNU General Public License v2.0 5 votes vote down vote up
def render_text(self, outfd, data):
        if self._config.RESOLVE:
            self.table_header(outfd, [("Interface", "16"),
                                  ("Destination", "20"),
                                  ("Dest Name", "30"), 
                                  ("Gateway", "")])
        else:
            self.table_header(outfd, [("Interface", "16"),
                                  ("Destination", "20"),
                                  ("Gateway", "")])
   
        for (name, dest, gw) in data:
            if self._config.RESOLVE:
                
                host = str(dest.cast("IpAddress"))
                try:
                    host = socket.gethostbyaddr(host)
                    host = host[0]
                except socket.herror:
                    host = ""
                except socket.gaierror:
                    host = ""
                
                self.table_row(outfd, name, dest.cast("IpAddress"), host, gw.cast("IpAddress"))
            else:        
                self.table_row(outfd, name, dest.cast("IpAddress"), gw.cast("IpAddress"))