当前位置: 首页>>代码示例>>Python>>正文


Python socket.herror方法代码示例

本文整理汇总了Python中socket.herror方法的典型用法代码示例。如果您正苦于以下问题:Python socket.herror方法的具体用法?Python socket.herror怎么用?Python socket.herror使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在socket的用法示例。


在下文中一共展示了socket.herror方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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])) ) 
开发者ID:nfvlabs,项目名称:openmano,代码行数:25,代码来源:console_proxy_thread.py

示例2: on_close

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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"]] 
开发者ID:nfvlabs,项目名称:openmano,代码行数:27,代码来源:console_proxy_thread.py

示例3: on_recv

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:nfvlabs,项目名称:openmano,代码行数:23,代码来源:console_proxy_thread.py

示例4: ip2name

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:Yukinoshita47,项目名称:Yuki-Chan-The-Auto-Pentest,代码行数:21,代码来源:common.py

示例5: ptr_lookup

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:heyglen,项目名称:network_tech,代码行数:23,代码来源:network.py

示例6: whois

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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) 
开发者ID:rajeshmajumdar,项目名称:webdigger,代码行数:24,代码来源:__init__.py

示例7: get_local_hostname

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:smarthomeNG,项目名称:smarthome,代码行数:20,代码来源:__init__.py

示例8: whois

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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) 
开发者ID:richardpenman,项目名称:whois,代码行数:24,代码来源:__init__.py

示例9: _get_reverse_dns

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:matamorphosis,项目名称:Scrummage,代码行数:25,代码来源:checkdmarc.py

示例10: start

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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") 
开发者ID:pychess,项目名称:pychess,代码行数:25,代码来源:FICSConnection.py

示例11: close

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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) 
开发者ID:pychess,项目名称:pychess,代码行数:18,代码来源:FICSConnection.py

示例12: check_connection

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:lbryio,项目名称:lbry-sdk,代码行数:21,代码来源:utils.py

示例13: check_ip_alive

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:NullArray,项目名称:AutoSploit,代码行数:21,代码来源:ip_generator.py

示例14: request

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:luci,项目名称:luci-py,代码行数:26,代码来源:httplib2_utils.py

示例15: send

# 需要导入模块: import socket [as 别名]
# 或者: from socket import herror [as 别名]
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 
开发者ID:luci,项目名称:luci-py,代码行数:21,代码来源:monitors.py


注:本文中的socket.herror方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。