本文整理汇总了Python中socket.AddressFamily方法的典型用法代码示例。如果您正苦于以下问题:Python socket.AddressFamily方法的具体用法?Python socket.AddressFamily怎么用?Python socket.AddressFamily使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类socket
的用法示例。
在下文中一共展示了socket.AddressFamily方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resolve
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
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()
示例2: split
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def split(
addrinfo: List[Tuple]
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
"""Partition the ``addrinfo`` list by address family.
Returns two lists. The first list contains the first entry from
``addrinfo`` and all others with the same family, and the
second list contains all other addresses (normally one list will
be AF_INET and the other AF_INET6, although non-standard resolvers
may return additional families).
"""
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr in addrinfo:
if af == primary_af:
primary.append((af, addr))
else:
secondary.append((af, addr))
return primary, secondary
示例3: try_connect
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def try_connect(self, addrs: Iterator[Tuple[socket.AddressFamily, Tuple]]) -> None:
try:
af, addr = next(addrs)
except StopIteration:
# We've reached the end of our queue, but the other queue
# might still be working. Send a final error on the future
# only when both queues are finished.
if self.remaining == 0 and not self.future.done():
self.future.set_exception(
self.last_error or IOError("connection failed")
)
return
stream, future = self.connect(af, addr)
self.streams.add(stream)
future_add_done_callback(
future, functools.partial(self.on_connect_done, addrs, af, addr)
)
示例4: __init__
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def __init__(
self,
addrinfo: List[Tuple],
connect: Callable[
[socket.AddressFamily, Tuple], Tuple[IOStream, "Future[IOStream]"]
],
) -> None:
self.io_loop = IOLoop.current()
self.connect = connect
self.future = (
Future()
) # type: Future[Tuple[socket.AddressFamily, Any, IOStream]]
self.timeout = None # type: Optional[object]
self.connect_timeout = None # type: Optional[object]
self.last_error = None # type: Optional[Exception]
self.remaining = len(addrinfo)
self.primary_addrs, self.secondary_addrs = self.split(addrinfo)
self.streams = set() # type: Set[IOStream]
示例5: split
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def split(
addrinfo: List[Tuple],
) -> Tuple[
List[Tuple[socket.AddressFamily, Tuple]],
List[Tuple[socket.AddressFamily, Tuple]],
]:
"""Partition the ``addrinfo`` list by address family.
Returns two lists. The first list contains the first entry from
``addrinfo`` and all others with the same family, and the
second list contains all other addresses (normally one list will
be AF_INET and the other AF_INET6, although non-standard resolvers
may return additional families).
"""
primary = []
secondary = []
primary_af = addrinfo[0][0]
for af, addr in addrinfo:
if af == primary_af:
primary.append((af, addr))
else:
secondary.append((af, addr))
return primary, secondary
示例6: test_create_sockets_ip
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def test_create_sockets_ip(
bind: str,
expected_family: socket.AddressFamily,
expected_binding: Tuple[str, int],
monkeypatch: MonkeyPatch,
) -> None:
mock_socket = Mock()
monkeypatch.setattr(socket, "socket", mock_socket)
config = Config()
config.bind = [bind]
sockets = config.create_sockets()
sock = sockets.insecure_sockets[0]
mock_socket.assert_called_with(expected_family, socket.SOCK_STREAM)
sock.setsockopt.assert_called_with(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # type: ignore
sock.bind.assert_called_with(expected_binding) # type: ignore
sock.setblocking.assert_called_with(False) # type: ignore
sock.set_inheritable.assert_called_with(True) # type: ignore
示例7: get_ip_address_type
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def get_ip_address_type(addr: str) -> socket.AddressFamily:
"""Return socket.AF_INET6 or socket.AF_INET4 for the provided address."""
import socket
socket_type = None
# First try it as an ipv4 address.
try:
socket.inet_pton(socket.AF_INET, addr)
socket_type = socket.AF_INET
except OSError:
pass
# Hmm apparently not ipv4; try ipv6.
if socket_type is None:
try:
socket.inet_pton(socket.AF_INET6, addr)
socket_type = socket.AF_INET6
except OSError:
pass
if socket_type is None:
raise ValueError('addr seems to be neither v4 or v6: ' + str(addr))
return socket_type
示例8: _resolve_addr
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def _resolve_addr(
host: str, port: int, family: socket.AddressFamily = socket.AF_UNSPEC
) -> List[Tuple[int, Any]]:
# On Solaris, getaddrinfo fails if the given port is not found
# in /etc/services and no socket type is given, so we must pass
# one here. The socket type used here doesn't seem to actually
# matter (we discard the one we get back in the results),
# so the addresses we return should still be usable with SOCK_DGRAM.
addrinfo = socket.getaddrinfo(host, port, family, socket.SOCK_STREAM)
results = []
for fam, socktype, proto, canonname, address in addrinfo:
results.append((fam, address))
return results
示例9: start
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def start(
self,
timeout: float = _INITIAL_CONNECT_TIMEOUT,
connect_timeout: Union[float, datetime.timedelta] = None,
) -> "Future[Tuple[socket.AddressFamily, Any, IOStream]]":
self.try_connect(iter(self.primary_addrs))
self.set_timeout(timeout)
if connect_timeout is not None:
self.set_connect_timeout(connect_timeout)
return self.future
示例10: on_connect_done
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def on_connect_done(
self,
addrs: Iterator[Tuple[socket.AddressFamily, Tuple]],
af: socket.AddressFamily,
addr: Tuple,
future: "Future[IOStream]",
) -> None:
self.remaining -= 1
try:
stream = future.result()
except Exception as e:
if self.future.done():
return
# Error: try again (but remember what happened so we have an
# error to raise in the end)
self.last_error = e
self.try_connect(addrs)
if self.timeout is not None:
# If the first attempt failed, don't wait for the
# timeout to try an address from the secondary queue.
self.io_loop.remove_timeout(self.timeout)
self.on_timeout()
return
self.clear_timeouts()
if self.future.done():
# This is a late arrival; just drop it.
stream.close()
else:
self.streams.discard(stream)
self.future.set_result((af, addr, stream))
self.close_streams()
示例11: _create_stream
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def _create_stream(
self,
max_buffer_size: int,
af: socket.AddressFamily,
addr: Tuple,
source_ip: str = None,
source_port: int = None,
) -> Tuple[IOStream, "Future[IOStream]"]:
# Always connect in plaintext; we'll convert to ssl if necessary
# after one connection has completed.
source_port_bind = source_port if isinstance(source_port, int) else 0
source_ip_bind = source_ip
if source_port_bind and not source_ip:
# User required a specific port, but did not specify
# a certain source IP, will bind to the default loopback.
source_ip_bind = "::1" if af == socket.AF_INET6 else "127.0.0.1"
# Trying to use the same address family as the requested af socket:
# - 127.0.0.1 for IPv4
# - ::1 for IPv6
socket_obj = socket.socket(af)
set_close_exec(socket_obj.fileno())
if source_port_bind or source_ip_bind:
# If the user requires binding also to a specific IP/port.
try:
socket_obj.bind((source_ip_bind, source_port_bind))
except socket.error:
socket_obj.close()
# Fail loudly if unable to use the IP/port.
raise
try:
stream = IOStream(socket_obj, max_buffer_size=max_buffer_size)
except socket.error as e:
fu = Future() # type: Future[IOStream]
fu.set_exception(e)
return stream, fu
else:
return stream, stream.connect(addr)
示例12: _init
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def _init(self, addr: addr_t, base: str, *,
auth: auth_t,
cookies: cookies_t,
headers: headers_t,
params: params_t,
timeout: timeout_t):
base_url: str
family: socket.AddressFamily
host_numeric: bool
base_url, family, host_numeric = multiaddr_to_url_data(addr, base)
#FIXME once https://github.com/encode/httpcore/pull/100 is released
if family != socket.AF_UNSPEC and not host_numeric:
warnings.warn(
"Restricting the address family on name lookups is not yet supported by HTTPx",
UserWarning
)
self._session_kwargs = map_args_to_httpx(
auth=auth,
cookies=cookies,
headers=headers,
params=params,
timeout=timeout,
)
self._session_kwargs["base_url"] = base_url
示例13: sockfam_to_enum
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def sockfam_to_enum(num):
"""Convert a numeric socket family value to an IntEnum member.
If it's not a known member, return the numeric value itself.
"""
if enum is None:
return num
else: # pragma: no cover
try:
return socket.AddressFamily(num)
except (ValueError, AttributeError):
return num
示例14: sockfam_to_enum
# 需要导入模块: import socket [as 别名]
# 或者: from socket import AddressFamily [as 别名]
def sockfam_to_enum(num):
"""Convert a numeric socket family value to an IntEnum member.
If it's not a known member, return the numeric value itself.
"""
if enum is None:
return num
else: # pragma: no cover
try:
return socket.AddressFamily(num)
except ValueError:
return num