Python errno.EADDRNOTAVAIL Examples

The following are 23 code examples of errno.EADDRNOTAVAIL(). 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 errno , or try the search function .
Example #1
Source File: llc.py    From nfcpy with European Union Public License 1.1 6 votes vote down vote up
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 
Example #2
Source File: _ipv4.py    From pyuavcan with MIT License 5 votes vote down vote up
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 
Example #3
Source File: __init__.py    From Sepia with GNU General Public License v2.0 5 votes vote down vote up
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 
Example #4
Source File: test_detect.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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") 
Example #5
Source File: detect.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
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 
Example #6
Source File: testing.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #7
Source File: __init__.py    From data with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #8
Source File: __init__.py    From data with GNU General Public License v3.0 5 votes vote down vote up
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 
Example #9
Source File: __init__.py    From SA-ctf_scoreboard with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
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 
Example #10
Source File: error.py    From libnl with GNU Lesser General Public License v2.1 5 votes vote down vote up
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)) 
Example #11
Source File: testing.py    From cheroot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 
Example #12
Source File: ResultManager.py    From Panda-Sandbox with MIT License 5 votes vote down vote up
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() 
Example #13
Source File: util.py    From indy-plenum with Apache License 2.0 5 votes vote down vote up
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() 
Example #14
Source File: test_socket.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
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) 
Example #15
Source File: program.py    From tensorboard with Apache License 2.0 4 votes vote down vote up
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 
Example #16
Source File: log_server_asyncio.py    From pytest-salt with Apache License 2.0 4 votes vote down vote up
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() 
Example #17
Source File: zeroconf.py    From jarvis with GNU General Public License v2.0 4 votes vote down vote up
def __init__(
        self,
        interfaces=InterfaceChoice.All,
    ):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads.

        :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
        """
        # hook for threads
        self._GLOBAL_DONE = False

        self._listen_socket = new_socket()
        interfaces = normalize_interface_choice(interfaces, socket.AF_INET)

        self._respond_sockets = []

        for i in interfaces:
            log.debug('Adding %r to multicast group', i)
            try:
                self._listen_socket.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
            except socket.error as e:
                if get_errno(e) == errno.EADDRINUSE:
                    log.info(
                        'Address in use when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                elif get_errno(e) == errno.EADDRNOTAVAIL:
                    log.info(
                        'Address not available when adding %s to multicast '
                        'group, it is expected to happen on some systems', i,
                    )
                    continue
                else:
                    raise

            respond_socket = new_socket()
            respond_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))

            self._respond_sockets.append(respond_socket)

        self.listeners = []
        self.browsers = {}
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.engine.add_reader(self.listener, self._listen_socket)
        self.reaper = Reaper(self)

        self.debug = None 
Example #18
Source File: __init__.py    From faces with GNU General Public License v2.0 4 votes vote down vote up
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 
Example #19
Source File: __init__.py    From faces with GNU General Public License v2.0 4 votes vote down vote up
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 
Example #20
Source File: _ipv4.py    From pyuavcan with MIT License 4 votes vote down vote up
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 
Example #21
Source File: runserver.py    From GTDWeb with GNU General Public License v2.0 4 votes vote down vote up
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) 
Example #22
Source File: zeroconf.py    From RepetierIntegration with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(
        self,
        interfaces=InterfaceChoice.All,
    ):
        """Creates an instance of the Zeroconf class, establishing
        multicast communications, listening and reaping threads.

        :type interfaces: :class:`InterfaceChoice` or sequence of ip addresses
        """
        # hook for threads
        self._GLOBAL_DONE = False

        self._listen_socket = new_socket()
        interfaces = normalize_interface_choice(interfaces, socket.AF_INET)

        self._respond_sockets = []

        for i in interfaces:
            log.debug('Adding %r to multicast group', i)
            try:
                self._listen_socket.setsockopt(
                    socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP,
                    socket.inet_aton(_MDNS_ADDR) + socket.inet_aton(i))
            except socket.error as e:
                if get_errno(e) == errno.EADDRINUSE:
                    log.info(
                        'Address in use when adding %s to multicast group, '
                        'it is expected to happen on some systems', i,
                    )
                elif get_errno(e) == errno.EADDRNOTAVAIL:
                    log.info(
                        'Address not available when adding %s to multicast '
                        'group, it is expected to happen on some systems', i,
                    )
                    continue
                else:
                    raise

            respond_socket = new_socket()
            respond_socket.setsockopt(
                socket.IPPROTO_IP, socket.IP_MULTICAST_IF, socket.inet_aton(i))

            self._respond_sockets.append(respond_socket)

        self.listeners = []
        self.browsers = {}
        self.services = {}
        self.servicetypes = {}

        self.cache = DNSCache()

        self.condition = threading.Condition()

        self.engine = Engine(self)
        self.listener = Listener(self)
        self.engine.add_reader(self.listener, self._listen_socket)
        self.reaper = Reaper(self)

        self.debug = None 
Example #23
Source File: api_data_reader.py    From satellite with GNU General Public License v3.0 4 votes vote down vote up
def open_udp_sock(sock_addr, ifname):
    """Instantiate UDP socket

    Args:
        sock_addr : Socket address string
        ifname    : Network interface name

    Returns:
        Socket object

    """
    udp_sock_ip, udp_sock_port_str = sock_addr.split(":")
    udp_sock_port                  = int(udp_sock_port_str)
    assert(udp_sock_ip is not None), "UDP source IP is not defined"
    assert(udp_sock_port is not None), "UDP port is not defined"

    logging.debug("Connect with UDP socket %s:%s" %(udp_sock_ip,
                                                    udp_sock_port))
    try:
        # Open and bind socket to Blocksat API port
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

        # Allow reuse and bind
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.bind(('', udp_sock_port))

        # Get the network interface index
        if (ifname is not None):
            ifreq   = struct.pack('16si', ifname.encode(), 0)
            res     = fcntl.ioctl(sock.fileno(), SIOCGIFINDEX, ifreq)
            ifindex = int(struct.unpack('16si', res)[1])
            logging.debug("Join multicast group %s on network interface %d" %(
                udp_sock_ip, ifindex
            ))
        else:
            logging.debug("Join group %s with the default network interface" %(
                udp_sock_ip
            ))
            ifindex = 0

        # Join multicast group on the chosen interface
        ip_mreqn = struct.pack('4s4si',
                               socket.inet_aton(udp_sock_ip),
                               socket.inet_aton('0.0.0.0'),
                               ifindex)
        sock.setsockopt(socket.IPPROTO_IP,
                        socket.IP_ADD_MEMBERSHIP,
                        ip_mreqn)

        # Make sure that this socket receives messages solely from the above
        # group that was explicitly joined above
        sock.setsockopt(socket.IPPROTO_IP, IP_MULTICAST_ALL, 0)
    except socket.error as e:
        if (e.errno == errno.EADDRNOTAVAIL):
            logging.error("Error on connection with UDP socket %s:%s" %(
                udp_sock_ip, udp_sock_port))
            logging.info("Use argument `--sock-addr` to define the socket address.")
        raise

    return sock