Python socket.AF_UNSPEC Examples
The following are 30
code examples of socket.AF_UNSPEC().
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: 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 #2
Source File: tcpclient.py From tornado-zh with MIT License | 7 votes |
def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None, max_buffer_size=None): """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). """ addrinfo = yield self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, self.io_loop, functools.partial(self._create_stream, max_buffer_size)) af, addr, stream = yield connector.start() # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: stream = yield stream.start_tls(False, ssl_options=ssl_options, server_hostname=host) raise gen.Return(stream)
Example #3
Source File: wsgi_server_test.py From browserscope with Apache License 2.0 | 6 votes |
def test_basic_behavior(self): inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer') self.mox.StubOutWithMock(socket, 'getaddrinfo') socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE).AndReturn( [(None, None, None, None, ('127.0.0.1', 0, 'baz')), (None, None, None, None, ('::1', 0, 'baz'))]) wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn( inet4_server) inet4_server.start() inet4_server.port = 123 wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn( inet6_server) inet6_server.start() self.mox.ReplayAll() self.server.start() self.mox.VerifyAll() self.assertItemsEqual([inet4_server, inet6_server], self.server._servers)
Example #4
Source File: TSocket.py From galaxy-sdk-python with Apache License 2.0 | 6 votes |
def listen(self): res0 = self._resolveAddr() socket_family = self._socket_family == socket.AF_UNSPEC and socket.AF_INET6 or self._socket_family for res in res0: if res[0] is socket_family or res is res0[-1]: break # We need remove the old unix socket if the file exists and # nobody is listening on it. if self._unix_socket: tmp = socket.socket(res[0], res[1]) try: tmp.connect(res[4]) except socket.error, err: eno, message = err.args if eno == errno.ECONNREFUSED: os.unlink(res[4])
Example #5
Source File: tcpclient.py From tornado-zh with MIT License | 6 votes |
def connect(self, host, port, af=socket.AF_UNSPEC, ssl_options=None, max_buffer_size=None): """Connect to the given host and port. Asynchronously returns an `.IOStream` (or `.SSLIOStream` if ``ssl_options`` is not None). """ addrinfo = yield self.resolver.resolve(host, port, af) connector = _Connector( addrinfo, self.io_loop, functools.partial(self._create_stream, max_buffer_size)) af, addr, stream = yield connector.start() # TODO: For better performance we could cache the (af, addr) # information here and re-use it on subsequent connections to # the same host. (http://tools.ietf.org/html/rfc6555#section-4.2) if ssl_options is not None: stream = yield stream.start_tls(False, ssl_options=ssl_options, server_hostname=host) raise gen.Return(stream)
Example #6
Source File: tcpserver.py From tornado-zh with MIT License | 6 votes |
def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128): u"""绑定该服务到指定的地址的指定端口上. 要启动该服务, 调用 `start`. 如果你想要在一个单进程上运行该服务, 你可以调用 `listen` 作为顺序调用 `bind` 和 `start` 的一个快捷方式. address 参数可以是 IP 地址或者主机名. 如果它是主机名, 该服务将监听在和该名称有关的所有 IP 地址上. 地址也可以是空字符串或者 None, 服务将监听所有可用的接口. family 可以被设置为 `socket.AF_INET` 或 `socket.AF_INET6` 用来限定是 IPv4 或 IPv6 地址, 否则如果可用的话, 两者 都将被使用. ``backlog`` 参数和 `socket.listen <socket.socket.listen>` 是相同含义. 这个方法可能在 `start` 之前被调用多次来监听在多个端口或接口上. """ sockets = bind_sockets(port, address=address, family=family, backlog=backlog) if self._started: self.add_sockets(sockets) else: self._pending_sockets.extend(sockets)
Example #7
Source File: netutil.py From opendevops with GNU General Public License v3.0 | 6 votes |
def is_valid_ip(ip: str) -> bool: """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 #8
Source File: netutil.py From opendevops with GNU General Public License v3.0 | 6 votes |
def resolve( self, host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC ) -> Awaitable[List[Tuple[int, Any]]]: """Resolves an address. The ``host`` argument is a string which may be a hostname or a literal IP address. Returns a `.Future` whose result is a list of (family, address) pairs, where address is a tuple suitable to pass to `socket.connect <socket.socket.connect>` (i.e. a ``(host, port)`` pair for IPv4; additional fields may be present for IPv6). If a ``callback`` is passed, it will be run with the result as an argument when it is complete. :raises IOError: if the address cannot be resolved. .. versionchanged:: 4.4 Standardized all implementations to raise `IOError`. .. versionchanged:: 6.0 The ``callback`` argument was removed. Use the returned awaitable object instead. """ raise NotImplementedError()
Example #9
Source File: util.py From pyvpn with The Unlicense | 6 votes |
def is_valid_ip(ip): """Returns true if the given string is a well-formed IP address. Supports IPv4 and IPv6. //取自 tornado """ 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: 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 #11
Source File: tcpserver.py From tornado-zh with MIT License | 6 votes |
def bind(self, port, address=None, family=socket.AF_UNSPEC, backlog=128): u"""绑定该服务到指定的地址的指定端口上. 要启动该服务, 调用 `start`. 如果你想要在一个单进程上运行该服务, 你可以调用 `listen` 作为顺序调用 `bind` 和 `start` 的一个快捷方式. address 参数可以是 IP 地址或者主机名. 如果它是主机名, 该服务将监听在和该名称有关的所有 IP 地址上. 地址也可以是空字符串或者 None, 服务将监听所有可用的接口. family 可以被设置为 `socket.AF_INET` 或 `socket.AF_INET6` 用来限定是 IPv4 或 IPv6 地址, 否则如果可用的话, 两者 都将被使用. ``backlog`` 参数和 `socket.listen <socket.socket.listen>` 是相同含义. 这个方法可能在 `start` 之前被调用多次来监听在多个端口或接口上. """ sockets = bind_sockets(port, address=address, family=family, backlog=backlog) if self._started: self.add_sockets(sockets) else: self._pending_sockets.extend(sockets)
Example #12
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 #13
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 #14
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 #15
Source File: wsgi_server_test.py From browserscope with Apache License 2.0 | 6 votes |
def test_ignore_other_errors(self): inet4_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) inet6_server = self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer') self.mox.StubOutWithMock(socket, 'getaddrinfo') socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE).AndReturn( [(None, None, None, None, ('127.0.0.1', 0, 'baz')), (None, None, None, None, ('::1', 0, 'baz'))]) wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn( inet4_server) inet4_server.start() inet4_server.port = 123 wsgi_server._SingleAddressWsgiServer(('::1', 123), None).AndReturn( inet6_server) inet6_server.start().AndRaise( wsgi_server.BindError('message', (errno.ENOPROTOOPT, 'no protocol'))) self.mox.ReplayAll() self.server.start() self.mox.VerifyAll() self.assertItemsEqual([inet4_server], self.server._servers)
Example #16
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 #17
Source File: wsgi_server_test.py From browserscope with Apache License 2.0 | 5 votes |
def test_retry_limited(self): inet4_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) for _ in range(wsgi_server._PORT_0_RETRIES)] inet6_servers = [self.mox.CreateMock(wsgi_server._SingleAddressWsgiServer) for _ in range(wsgi_server._PORT_0_RETRIES)] self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer') self.mox.StubOutWithMock(socket, 'getaddrinfo') socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE).AndReturn( [(None, None, None, None, ('127.0.0.1', 0, 'baz')), (None, None, None, None, ('::1', 0, 'baz'))]) for offset, (inet4_server, inet6_server) in enumerate(zip( inet4_servers, inet6_servers)): wsgi_server._SingleAddressWsgiServer(('127.0.0.1', 0), None).AndReturn( inet4_server) inet4_server.start() inet4_server.port = offset + 1 wsgi_server._SingleAddressWsgiServer(('::1', offset + 1), None).AndReturn( inet6_server) inet6_server.start().AndRaise( wsgi_server.BindError('message', (errno.EADDRINUSE, 'in use'))) inet4_server.quit() self.mox.ReplayAll() self.assertRaises(wsgi_server.BindError, self.server.start) self.mox.VerifyAll()
Example #18
Source File: netutil_test.py From opendevops with GNU General Public License v3.0 | 5 votes |
def test_bad_host(self): with self.assertRaises(IOError): yield self.resolver.resolve("an invalid domain", 80, socket.AF_UNSPEC)
Example #19
Source File: tcpclient_test.py From opendevops with GNU General Public License v3.0 | 5 votes |
def test_connect_unspec_dual(self): self.do_test_connect(socket.AF_UNSPEC, "localhost")
Example #20
Source File: tcpclient_test.py From opendevops with GNU General Public License v3.0 | 5 votes |
def test_connect_unspec_ipv6(self): self.skipIfLocalhostV4() self.do_test_connect(socket.AF_UNSPEC, "::1")
Example #21
Source File: tcpclient_test.py From opendevops with GNU General Public License v3.0 | 5 votes |
def start_server(self, family): if family == socket.AF_UNSPEC and "TRAVIS" in os.environ: self.skipTest("dual-stack servers often have port conflicts on travis") self.server = TestTCPServer(family) return self.server.port
Example #22
Source File: TSocket.py From galaxy-sdk-python with Apache License 2.0 | 5 votes |
def __init__(self, host='localhost', port=9090, unix_socket=None, socket_family=socket.AF_UNSPEC): """Initialize a TSocket @param host(str) The host to connect to. @param port(int) The (TCP) port to connect to. @param unix_socket(str) The filename of a unix socket to connect to. (host and port will be ignored.) @param socket_family(int) The socket family to use with this socket. """ self.host = host self.port = port self.handle = None self._unix_socket = unix_socket self._timeout = None self._socket_family = socket_family
Example #23
Source File: status.py From koku with GNU Affero General Public License v3.0 | 5 votes |
def check_kafka_connection(): """Check connectability of Kafka Broker.""" conn = BrokerConnection(SourcesConfig.SOURCES_KAFKA_HOST, int(SourcesConfig.SOURCES_KAFKA_PORT), socket.AF_UNSPEC) connected = conn.connect_blocking(timeout=1) if connected: conn.close() return connected
Example #24
Source File: socks.py From CloudFail with MIT License | 5 votes |
def _write_SOCKS5_address(self, addr, file): """ Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object. """ host, port = addr proxy_type, _, _, rdns, username, password = self.proxy family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"} # If the given destination address is an IP address, we'll # use the IP address request even if remote resolving was specified. # Detect whether the address is IPv4/6 directly. for family in (socket.AF_INET, socket.AF_INET6): try: addr_bytes = socket.inet_pton(family, host) file.write(family_to_byte[family] + addr_bytes) host = socket.inet_ntop(family, addr_bytes) file.write(struct.pack(">H", port)) return host, port except socket.error: continue # Well it's not an IP number, so it's probably a DNS name. if rdns: # Resolve remotely host_bytes = host.encode('idna') file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) else: # Resolve locally addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG) # We can't really work out what IP is reachable, so just pick the # first. target_addr = addresses[0] family = target_addr[0] host = target_addr[4][0] addr_bytes = socket.inet_pton(family, host) file.write(family_to_byte[family] + addr_bytes) host = socket.inet_ntop(family, addr_bytes) file.write(struct.pack(">H", port)) return host, port
Example #25
Source File: assocket.py From aerospike-admin with Apache License 2.0 | 5 votes |
def _create_socket(self): sock = None for addrinfo in socket.getaddrinfo(self.ip, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM): # for DNS it will try all possible addresses try: sock = self._create_socket_for_addrinfo(addrinfo) if sock: break except Exception: pass return sock
Example #26
Source File: wsgi_server_test.py From browserscope with Apache License 2.0 | 5 votes |
def test_start_port_in_use(self): self.mox.StubOutWithMock(socket, 'getaddrinfo') self.mox.StubOutWithMock(self.server, 'bind') af = object() socktype = object() proto = object() socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_PASSIVE).AndReturn( [(af, socktype, proto, None, None)]) self.server.bind(af, socktype, proto).AndRaise(socket.error) self.mox.ReplayAll() self.assertRaises(wsgi_server.BindError, self.server.start) self.mox.VerifyAll()
Example #27
Source File: socketutil.py From Pyro5 with MIT License | 5 votes |
def get_ip_address(hostname: str, workaround127: bool = False, version: int = None) \ -> Union[ipaddress.IPv4Address, ipaddress.IPv6Address]: """ Returns the IP address for the given host. If you enable the workaround, it will use a little hack if the ip address is found to be the loopback address. The hack tries to discover an externally visible ip address instead (this only works for ipv4 addresses). Set ipVersion=6 to return ipv6 addresses, 4 to return ipv4, 0 to let OS choose the best one or None to use config.PREFER_IP_VERSION. """ if not workaround127: with contextlib.suppress(ValueError): addr = ipaddress.ip_address(hostname) return addr def getaddr(ip_version): if ip_version == 6: family = socket.AF_INET6 elif ip_version == 4: family = socket.AF_INET elif ip_version == 0: family = socket.AF_UNSPEC else: raise ValueError("unknown value for argument ipVersion.") ip = socket.getaddrinfo(hostname or socket.gethostname(), 80, family, socket.SOCK_STREAM, socket.SOL_TCP)[0][4][0] if workaround127 and (ip.startswith("127.") or ip == "0.0.0.0"): return get_interface("4.2.2.2").ip return ipaddress.ip_address(ip) try: if hostname and ':' in hostname and version is None: version = 0 return getaddr(config.PREFER_IP_VERSION) if version is None else getaddr(version) except socket.gaierror: if version == 6 or (version is None and config.PREFER_IP_VERSION == 6): raise socket.error("unable to determine IPV6 address") return getaddr(0)
Example #28
Source File: connection.py From NEIE-Assistant with GNU General Public License v3.0 | 5 votes |
def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family
Example #29
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 #30
Source File: node.py From aerospike-admin with Apache License 2.0 | 5 votes |
def _update_IP(self, address, port): if address not in self.dns_cache: self.dns_cache[address] = ( socket.getaddrinfo(address, port, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][4][0], getfqdn(address)) self.ip, self.fqdn = self.dns_cache[address]