本文整理汇总了Python中errno.EADDRNOTAVAIL属性的典型用法代码示例。如果您正苦于以下问题:Python errno.EADDRNOTAVAIL属性的具体用法?Python errno.EADDRNOTAVAIL怎么用?Python errno.EADDRNOTAVAIL使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类errno
的用法示例。
在下文中一共展示了errno.EADDRNOTAVAIL属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _bind_by_name
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def _bind_by_name(self, socket, name):
if not service_name_format.match(name):
raise err.Error(errno.EFAULT)
with self.lock:
if self.snl.get(name) is not None:
raise err.Error(errno.EADDRINUSE)
addr = wks_map.get(name)
if addr is None:
try:
addr = 16 + self.sap[16:32].index(None)
except ValueError:
raise err.Error(errno.EADDRNOTAVAIL)
socket.bind(addr)
self.sap[addr] = ServiceAccessPoint(addr, self)
self.sap[addr].insert_socket(socket)
self.snl[name] = addr
示例2: make_output_socket
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def make_output_socket(self, remote_node_id: typing.Optional[int], remote_port: int) -> socket.socket:
if self.local_node_id is None:
raise pyuavcan.transport.OperationNotDefinedForAnonymousNodeError(
f'Anonymous UDP/IP nodes cannot emit transfers, they can only listen. '
f'The local IP address is {self._local}.'
)
bind_to = self._local.host_address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(False)
try:
# Output sockets shall be bound, too, in order to ensure that outgoing packets have the correct
# source IP address specified. This is particularly important for localhost; an unbound socket
# there emits all packets from 127.0.0.1 which is certainly not what we need.
s.bind((str(bind_to), 0)) # Bind to an ephemeral port.
except OSError as ex:
if ex.errno == errno.EADDRNOTAVAIL:
raise pyuavcan.transport.InvalidMediaConfigurationError(
f'Bad IP configuration: cannot bind output socket to {bind_to} [{errno.errorcode[ex.errno]}]'
) from None
raise # pragma: no cover
# Specify the fixed remote end. The port is always fixed; the host is unicast or broadcast.
if remote_node_id is None:
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.connect((str(self._local.broadcast_address), remote_port))
elif 0 <= remote_node_id < self._max_nodes:
ip = IPv4Address(int(self._local.subnet_address) + remote_node_id)
assert ip in self._local
s.connect((str(ip), remote_port))
else:
raise ValueError(f'Cannot map the node-ID value {remote_node_id} to an IP address. '
f'The range of valid node-ID values is [0, {self._max_nodes})')
_logger.debug('%r: New output socket %r connected to remote node %r, remote port %r',
self, s, remote_node_id, remote_port)
return s
示例3: test_create_connection
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def test_create_connection(self):
# Issue #9792: errors raised by create_connection() should have
# a proper errno attribute.
port = test_support.find_unused_port()
with self.assertRaises(socket.error) as cm:
socket.create_connection((HOST, port))
# Issue #16257: create_connection() calls getaddrinfo() against
# 'localhost'. This may result in an IPV6 addr being returned
# as well as an IPV4 one:
# >>> socket.getaddrinfo('localhost', port, 0, SOCK_STREAM)
# >>> [(2, 2, 0, '', ('127.0.0.1', 41230)),
# (26, 2, 0, '', ('::1', 41230, 0, 0))]
#
# create_connection() enumerates through all the addresses returned
# and if it doesn't successfully bind to any of them, it propagates
# the last exception it encountered.
#
# On Solaris, ENETUNREACH is returned in this circumstance instead
# of ECONNREFUSED. So, if that errno exists, add it to our list of
# expected errnos.
expected_errnos = [ errno.ECONNREFUSED, ]
if hasattr(errno, 'ENETUNREACH'):
expected_errnos.append(errno.ENETUNREACH)
if hasattr(errno, 'EADDRNOTAVAIL'):
# bpo-31910: socket.create_connection() fails randomly
# with EADDRNOTAVAIL on Travis CI
expected_errnos.append(errno.EADDRNOTAVAIL)
self.assertIn(cm.exception.errno, expected_errnos)
示例4: checkPortAvailable
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def checkPortAvailable(ha):
"""Checks whether the given port is available"""
# Not sure why OS would allow binding to one type and not other.
# Checking for port available for TCP and UDP.
sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM)
for typ in sockTypes:
sock = socket.socket(socket.AF_INET, typ)
try:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(ha)
if typ == socket.SOCK_STREAM:
l_onoff = 1
l_linger = 0
sock.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
struct.pack('ii', l_onoff, l_linger))
except OSError as exc:
if exc.errno in [
errno.EADDRINUSE, errno.EADDRNOTAVAIL,
WS_SOCKET_BIND_ERROR_ALREADY_IN_USE,
WS_SOCKET_BIND_ERROR_NOT_AVAILABLE
]:
raise PortNotAvailable(ha)
else:
raise exc
finally:
sock.close()
示例5: __init__
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def __init__(self):
ip = config("cuckoo:resultserver:ip")
port = config("cuckoo:resultserver:port")
pool_size = config("cuckoo:resultserver:pool_size")
sock = gevent.socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
try:
sock.bind((ip, port))
except (OSError, socket.error) as e:
if e.errno == errno.EADDRINUSE:
raise CuckooCriticalError(
"Cannot bind ResultServer on port %d "
"because it was in use, bailing." % port
)
elif e.errno == errno.EADDRNOTAVAIL:
raise CuckooCriticalError(
"Unable to bind ResultServer on %s:%s %s. This "
"usually happens when you start Cuckoo without "
"bringing up the virtual interface associated with "
"the ResultServer IP address. Please refer to "
"https://cuckoo.sh/docs/faq/#troubles-problem "
"for more information." % (ip, port, e)
)
else:
raise CuckooCriticalError(
"Unable to bind ResultServer on %s:%s: %s" % (ip, port, e)
)
# We allow user to specify port 0 to get a random port, report it back
# here
_, self.port = sock.getsockname()
sock.listen(128)
self.thread = threading.Thread(
target=self.create_server, args=(sock, pool_size)
)
self.thread.daemon = True
self.thread.start()
示例6: _probe_ipv6_sock
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def _probe_ipv6_sock(interface):
# Alternate way is to check IPs on interfaces using glibc, like:
# github.com/Gautier/minifail/blob/master/minifail/getifaddrs.py
try:
with closing(socket.socket(family=socket.AF_INET6)) as sock:
sock.bind((interface, 0))
except (OSError, socket.error) as sock_err:
# In Python 3 socket.error is an alias for OSError
# In Python 2 socket.error is a subclass of IOError
if sock_err.errno != errno.EADDRNOTAVAIL:
raise
else:
return True
return False
示例7: nl_syserr2nlerr
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def nl_syserr2nlerr(error_):
"""https://github.com/thom311/libnl/blob/libnl3_2_25/lib/error.c#L84."""
error_ = abs(error_)
legend = {
errno.EBADF: libnl.errno_.NLE_BAD_SOCK,
errno.EADDRINUSE: libnl.errno_.NLE_EXIST,
errno.EEXIST: libnl.errno_.NLE_EXIST,
errno.EADDRNOTAVAIL: libnl.errno_.NLE_NOADDR,
errno.ESRCH: libnl.errno_.NLE_OBJ_NOTFOUND,
errno.ENOENT: libnl.errno_.NLE_OBJ_NOTFOUND,
errno.EINTR: libnl.errno_.NLE_INTR,
errno.EAGAIN: libnl.errno_.NLE_AGAIN,
errno.ENOTSOCK: libnl.errno_.NLE_BAD_SOCK,
errno.ENOPROTOOPT: libnl.errno_.NLE_INVAL,
errno.EFAULT: libnl.errno_.NLE_INVAL,
errno.EACCES: libnl.errno_.NLE_NOACCESS,
errno.EINVAL: libnl.errno_.NLE_INVAL,
errno.ENOBUFS: libnl.errno_.NLE_NOMEM,
errno.ENOMEM: libnl.errno_.NLE_NOMEM,
errno.EAFNOSUPPORT: libnl.errno_.NLE_AF_NOSUPPORT,
errno.EPROTONOSUPPORT: libnl.errno_.NLE_PROTO_MISMATCH,
errno.EOPNOTSUPP: libnl.errno_.NLE_OPNOTSUPP,
errno.EPERM: libnl.errno_.NLE_PERM,
errno.EBUSY: libnl.errno_.NLE_BUSY,
errno.ERANGE: libnl.errno_.NLE_RANGE,
errno.ENODEV: libnl.errno_.NLE_NODEV,
}
return int(legend.get(error_, libnl.errno_.NLE_FAILURE))
示例8: _conn_request
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
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 in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient socket errors
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
示例9: get_interface_ip
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def get_interface_ip(sock: socket.socket, ifname: str) -> str:
"""Obtain an IP address for a network interface, as a string."""
ifreq_tuple = (ifname.encode("utf-8")[:15], socket.AF_INET, b"\x00" * 14)
ifreq = struct.pack(b"16sH14s", *ifreq_tuple)
try:
info = fcntl.ioctl(sock, SIOCGIFADDR, ifreq)
except OSError as e:
if e.errno == errno.ENODEV:
raise InterfaceNotFound("Interface not found: '%s'." % ifname)
elif e.errno == errno.EADDRNOTAVAIL:
raise IPAddressNotAvailable(
"No IP address found on interface '%s'." % ifname
)
else:
raise IPAddressNotAvailable(
"Failed to get IP address for '%s': %s."
% (ifname, strerror(e.errno))
)
else:
( # Parse the `struct ifreq` that comes back from the ioctl() call.
# 16x --> char ifr_name[IFNAMSIZ];
# ... next is a union of structures; we're interested in the
# `sockaddr_in` that is returned from this particular ioctl().
# 2x --> short sin_family;
# 2x --> unsigned short sin_port;
# 4s --> struct in_addr sin_addr;
# 8x --> char sin_zero[8];
addr,
) = struct.unpack(b"16x2x2x4s8x", info)
ip = socket.inet_ntoa(addr)
return ip
示例10: test_no_ip_raises_ipaddressnotavailable
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def test_no_ip_raises_ipaddressnotavailable(self):
mock_ioerror = IOError()
mock_ioerror.errno = errno.EADDRNOTAVAIL
self.patch(detect_module.fcntl, "ioctl").side_effect = mock_ioerror
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
with ExpectedException(IPAddressNotAvailable, ".*No IP address.*"):
get_interface_ip(sock, "lo")
示例11: inner_run
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def inner_run(self, *args, **options):
from django.conf import settings
from django.utils import translation
threading = options.get('use_threading')
shutdown_message = options.get('shutdown_message', '')
quit_command = 'CTRL-BREAK' if sys.platform == 'win32' else 'CONTROL-C'
self.stdout.write("Performing system checks...\n\n")
self.validate(display_num_errors=True)
try:
self.check_migrations()
except ImproperlyConfigured:
pass
now = datetime.now().strftime('%B %d, %Y - %X')
if six.PY2:
now = now.decode(get_system_encoding())
self.stdout.write((
"%(started_at)s\n"
"Django version %(version)s, using settings %(settings)r\n"
"Starting development server at http://%(addr)s:%(port)s/\n"
"Quit the server with %(quit_command)s.\n"
) % {
"started_at": now,
"version": self.get_version(),
"settings": settings.SETTINGS_MODULE,
"addr": '[%s]' % self.addr if self._raw_ipv6 else self.addr,
"port": self.port,
"quit_command": quit_command,
})
# django.core.management.base forces the locale to en-us. We should
# set it up correctly for the first request (particularly important
# in the "--noreload" case).
translation.activate(settings.LANGUAGE_CODE)
try:
handler = self.get_handler(*args, **options)
run(self.addr, int(self.port), handler,
ipv6=self.use_ipv6, threading=threading)
except socket.error as e:
# Use helpful error messages instead of ugly tracebacks.
ERRORS = {
errno.EACCES: "You don't have permission to access that port.",
errno.EADDRINUSE: "That port is already in use.",
errno.EADDRNOTAVAIL: "That IP address can't be assigned-to.",
}
try:
error_text = ERRORS[e.errno]
except KeyError:
error_text = force_text(e)
self.stderr.write("Error: %s" % error_text)
# Need to use an OS exit because sys.exit doesn't work in a thread
os._exit(1)
except KeyboardInterrupt:
if shutdown_message:
self.stdout.write(shutdown_message)
sys.exit(0)
示例12: make_input_socket
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def make_input_socket(self, local_port: int, expect_broadcast: bool) -> socket.socket:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setblocking(False)
# Allow other applications and other instances to listen to broadcast traffic.
# This option shall be set before the socket is bound.
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if expect_broadcast or self.local_node_id is None:
# The socket MUST BE BOUND TO INADDR_ANY IN ORDER TO RECEIVE BROADCAST DATAGRAMS.
# The user will have to filter out irrelevant datagrams in user space.
# Please read https://stackoverflow.com/a/58118503/1007777
# We also bind to this address if the local node is anonymous because in that case the local
# IP address may be impossible to bind to.
s.bind(('', local_port))
else:
# We are not interested in broadcast traffic, so it is safe to bind to a specific address.
# On some operating systems this may not reject broadcast traffic, but we don't care.
# The motivation for this is to allow multiple nodes running on localhost to bind to the same
# service port. If they all were binding to that port at INADDR_ANY, on some OS (like GNU/Linux)
# only the last-bound node would receive unicast data, making the service dysfunctional on all
# other (earlier bound) nodes. Jeez, the socket API is kind of a mess.
bind_to = self._local.host_address
try:
s.bind((str(bind_to), local_port))
except OSError as ex:
if ex.errno == errno.EADDRNOTAVAIL:
raise pyuavcan.transport.InvalidMediaConfigurationError(
f'Bad IP configuration: cannot bind input socket to {bind_to} [{errno.errorcode[ex.errno]}]'
) from None
raise # pragma: no cover
# Man 7 IP says that SO_BROADCAST should be set in order to receive broadcast datagrams.
# The behavior I am observing does not match that, but we do it anyway because man says so.
# If the call fails, ignore because it may not be necessary depending on the OS in use.
try:
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
except Exception as ex: # pragma: no cover
_logger.exception('%r: Could not set SO_BROADCAST on %r: %s', self, s, ex)
_logger.debug('%r: New input socket %r, local port %r, supports broadcast: %r',
self, s, local_port, expect_broadcast)
return s
示例13: _conn_request
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
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
if err in (errno.ENETUNREACH, errno.EADDRNOTAVAIL) and i < RETRIES:
continue # retry on potentially transient socket errors
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
示例14: log_server_asyncio
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def log_server_asyncio(log_server_port):
'''
Starts a log server.
'''
async def read_child_processes_log_records(reader, writer):
unpacker = msgpack.Unpacker(raw=False)
while True:
try:
wire_bytes = await reader.read(1024)
if not wire_bytes:
break
try:
unpacker.feed(wire_bytes)
except msgpack.exceptions.BufferFull:
# Start over loosing some data?!
unpacker = msgpack.Unpacker(raw=False)
unpacker.feed(wire_bytes)
for record_dict in unpacker:
record = logging.makeLogRecord(record_dict)
logger = logging.getLogger(record.name)
logger.handle(record)
except (EOFError, KeyboardInterrupt, SystemExit):
break
except Exception as exc: # pylint: disable=broad-except
log.exception(exc)
def process_logs(port):
loop = asyncio.new_event_loop()
try:
coro = asyncio.start_server(read_child_processes_log_records, host='localhost', port=port, loop=loop)
server = loop.run_until_complete(coro)
except OSError as err:
if err.errno != errno.EADDRNOTAVAIL:
# If not address not available, in case localhost cannot be resolved
raise
coro = asyncio.start_server(read_child_processes_log_records, host='127.0.0.1', port=port, loop=loop)
server = loop.run_until_complete(coro)
try:
loop.run_forever()
except KeyboardInterrupt:
pass
server.close()
loop.run_until_complete(server.wait_closed())
loop.close()
process_queue_thread = threading.Thread(target=process_logs, args=(log_server_port,))
process_queue_thread.daemon = True
process_queue_thread.start()
示例15: __init__
# 需要导入模块: import errno [as 别名]
# 或者: from errno import EADDRNOTAVAIL [as 别名]
def __init__(self, wsgi_app, flags):
self._flags = flags
host = flags.host
port = flags.port
self._auto_wildcard = flags.bind_all
if self._auto_wildcard:
# Serve on all interfaces, and attempt to serve both IPv4 and IPv6
# traffic through one socket.
host = self._get_wildcard_address(port)
elif host is None:
host = "localhost"
self._host = host
self._url = None # Will be set by get_url() below
self._fix_werkzeug_logging()
try:
super(WerkzeugServer, self).__init__(host, port, wsgi_app)
except socket.error as e:
if hasattr(errno, "EACCES") and e.errno == errno.EACCES:
raise TensorBoardServerException(
"TensorBoard must be run as superuser to bind to port %d"
% port
)
elif hasattr(errno, "EADDRINUSE") and e.errno == errno.EADDRINUSE:
if port == 0:
raise TensorBoardServerException(
"TensorBoard unable to find any open port"
)
else:
raise TensorBoardPortInUseError(
"TensorBoard could not bind to port %d, it was already in use"
% port
)
elif (
hasattr(errno, "EADDRNOTAVAIL")
and e.errno == errno.EADDRNOTAVAIL
):
raise TensorBoardServerException(
"TensorBoard could not bind to unavailable address %s"
% host
)
elif (
hasattr(errno, "EAFNOSUPPORT") and e.errno == errno.EAFNOSUPPORT
):
raise TensorBoardServerException(
"Tensorboard could not bind to unsupported address family %s"
% host
)
# Raise the raw exception if it wasn't identifiable as a user error.
raise