Python socket.AF_INET6 Examples

The following are 30 code examples for showing how to use socket.AF_INET6(). These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module socket , or try the search function .

Example 1
Project: rtp_cluster   Author: sippy   File: Udp_server.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def __init__(self, laddress, data_callback, family = None, o = None):
        if o == None:
            if family == None:
                if laddress != None and laddress[0].startswith('['):
                    family = socket.AF_INET6
                    laddress = (laddress[0][1:-1], laddress[1])
                else:
                    family = socket.AF_INET
            self.family = family
            self.laddress = laddress
            self.data_callback = data_callback
        else:
            self.laddress, self.data_callback, self.family, self.nworkers, self.flags, \
              self.ploss_out_rate, self.pdelay_out_max, self.ploss_in_rate, \
              self.pdelay_in_max = o.laddress, o.data_callback, o.family, \
              o.nworkers, o.flags, o.ploss_out_rate, o.pdelay_out_max, o.ploss_in_rate, \
              o.pdelay_in_max 
Example 2
Project: rtp_cluster   Author: sippy   File: Udp_server.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def send_to(self, data, address, delayed = False):
        if not isinstance(address, tuple):
            raise Exception('Invalid address, not a tuple: %s' % str(address))
        if not isinstance(data, bytes):
            data = data.encode('utf-8')
        if self.uopts.ploss_out_rate > 0.0 and not delayed:
            if random() < self.uopts.ploss_out_rate:
                return
        if self.uopts.pdelay_out_max > 0.0 and not delayed:
            pdelay = self.uopts.pdelay_out_max * random()
            Timeout(self.send_to, pdelay, 1, data, address, True)
            return
        addr, port = address
        if self.uopts.family == socket.AF_INET6:
            if not addr.startswith('['):
                raise Exception('Invalid IPv6 address: %s' % addr)
            address = (addr[1:-1], port)
        self.wi_available.acquire()
        self.wi.append((data, address))
        self.wi_available.notify()
        self.wi_available.release() 
Example 3
Project: sanic   Author: huge-success   File: server.py    License: MIT License 6 votes vote down vote up
def bind_socket(host: str, port: int, *, backlog=100) -> socket.socket:
    """Create TCP server socket.
    :param host: IPv4, IPv6 or hostname may be specified
    :param port: TCP port number
    :param backlog: Maximum number of connections to queue
    :return: socket.socket object
    """
    try:  # IP address: family must be specified for IPv6 at least
        ip = ip_address(host)
        host = str(ip)
        sock = socket.socket(
            socket.AF_INET6 if ip.version == 6 else socket.AF_INET
        )
    except ValueError:  # Hostname, may become AF_INET or AF_INET6
        sock = socket.socket()
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((host, port))
    sock.listen(backlog)
    return sock 
Example 4
Project: gist-alfred   Author: danielecook   File: ssl_.py    License: MIT License 6 votes vote down vote up
def is_ipaddress(hostname):
    """Detects whether the hostname given is an IP address.

    :param str hostname: Hostname to examine.
    :return: True if the hostname is an IP address, False otherwise.
    """
    if six.PY3 and isinstance(hostname, bytes):
        # IDN A-label bytes are ASCII compatible.
        hostname = hostname.decode('ascii')

    families = [socket.AF_INET]
    if hasattr(socket, 'AF_INET6'):
        families.append(socket.AF_INET6)

    for af in families:
        try:
            inet_pton(af, hostname)
        except (socket.error, ValueError, OSError):
            pass
        else:
            return True
    return False 
Example 5
Project: rift-python   Author: brunorijsman   File: kernel.py    License: Apache License 2.0 6 votes vote down vote up
def kernel_route_dst_prefix_str(route):
        dst = route.get_attr('RTA_DST')
        if dst is None:
            family = route["family"]
            if family == socket.AF_INET:
                prefix_str = "0.0.0.0/0"
            elif family == socket.AF_INET6:
                prefix_str = "::/0"
            else:
                prefix_str = "Default"
        else:
            prefix_str = dst
            dst_len = route["dst_len"]
            if dst_len is not None:
                prefix_str += "/" + str(dst_len)
        return prefix_str 
Example 6
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 6 votes vote down vote up
def log_tx_protocol_packet(self, level, sock, prelude, packet_info):
        if not self._tx_log.isEnabledFor(level):
            return
        if sock.family == socket.AF_INET:
            fam_str = "IPv4"
            from_str = "from {}:{}".format(sock.getsockname()[0], sock.getsockname()[1])
            to_str = "to {}:{}".format(sock.getpeername()[0], sock.getpeername()[1])
        else:
            assert sock.family == socket.AF_INET6
            fam_str = "IPv6"
            from_str = "from [{}]:{}".format(sock.getsockname()[0], sock.getsockname()[1])
            to_str = "to [{}]:{}".format(sock.getpeername()[0], sock.getpeername()[1])
        type_str = self.protocol_packet_type(packet_info.protocol_packet)
        packet_str = str(packet_info)
        self._tx_log.log(level, "[%s] %s %s %s %s %s %s" %
                         (self._log_id, prelude, fam_str, type_str, from_str, to_str, packet_str)) 
Example 7
Project: rift-python   Author: brunorijsman   File: interface.py    License: Apache License 2.0 6 votes vote down vote up
def create_socket_ipv6_tx_ucast(self, remote_address, port):
        try:
            sock = socket.socket(socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        except IOError as err:
            self.warning("Could not create IPv6 UDP socket: %s", err)
            return None
        self.enable_addr_and_port_reuse(sock)
        try:
            sock_addr = socket.getaddrinfo(remote_address, port, socket.AF_INET6,
                                           socket.SOCK_DGRAM)[0][4]
            sock.connect(sock_addr)
        except IOError as err:
            self.warning("Could not connect UDP socket to address %s port %d: %s",
                         remote_address, port, err)
            return None
        return sock 
Example 8
Project: tornado-zh   Author: tao12345666333   File: httpserver.py    License: MIT License 6 votes vote down vote up
def __init__(self, stream, address, protocol):
        self.address = address
        # Save the socket's address family now so we know how to
        # interpret self.address even after the stream is closed
        # and its socket attribute replaced with None.
        if stream.socket is not None:
            self.address_family = stream.socket.family
        else:
            self.address_family = None
        # In HTTPServerRequest we want an IP, not a full socket address.
        if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
                address is not None):
            self.remote_ip = address[0]
        else:
            # Unix (or other) socket; fake the remote address.
            self.remote_ip = '0.0.0.0'
        if protocol:
            self.protocol = protocol
        elif isinstance(stream, iostream.SSLIOStream):
            self.protocol = "https"
        else:
            self.protocol = "http"
        self._orig_remote_ip = self.remote_ip
        self._orig_protocol = self.protocol 
Example 9
Project: tornado-zh   Author: tao12345666333   File: simple_httpclient_test.py    License: MIT License 6 votes vote down vote up
def test_ipv6(self):
        try:
            [sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
            port = sock.getsockname()[1]
            self.http_server.add_socket(sock)
        except socket.gaierror as e:
            if e.args[0] == socket.EAI_ADDRFAMILY:
                # python supports ipv6, but it's not configured on the network
                # interface, so skip this test.
                return
            raise
        url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)

        # ipv6 is currently enabled by default but can be disabled
        self.http_client.fetch(url, self.stop, allow_ipv6=False)
        response = self.wait()
        self.assertEqual(response.code, 599)

        self.http_client.fetch(url, self.stop)
        response = self.wait()
        self.assertEqual(response.body, b"Hello world!") 
Example 10
Project: tornado-zh   Author: tao12345666333   File: tcpserver.py    License: MIT License 6 votes vote down vote up
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 11
Project: tornado-zh   Author: tao12345666333   File: httpserver.py    License: MIT License 6 votes vote down vote up
def __init__(self, stream, address, protocol):
        self.address = address
        # Save the socket's address family now so we know how to
        # interpret self.address even after the stream is closed
        # and its socket attribute replaced with None.
        if stream.socket is not None:
            self.address_family = stream.socket.family
        else:
            self.address_family = None
        # In HTTPServerRequest we want an IP, not a full socket address.
        if (self.address_family in (socket.AF_INET, socket.AF_INET6) and
                address is not None):
            self.remote_ip = address[0]
        else:
            # Unix (or other) socket; fake the remote address.
            self.remote_ip = '0.0.0.0'
        if protocol:
            self.protocol = protocol
        elif isinstance(stream, iostream.SSLIOStream):
            self.protocol = "https"
        else:
            self.protocol = "http"
        self._orig_remote_ip = self.remote_ip
        self._orig_protocol = self.protocol 
Example 12
Project: tornado-zh   Author: tao12345666333   File: simple_httpclient_test.py    License: MIT License 6 votes vote down vote up
def test_ipv6(self):
        try:
            [sock] = bind_sockets(None, '::1', family=socket.AF_INET6)
            port = sock.getsockname()[1]
            self.http_server.add_socket(sock)
        except socket.gaierror as e:
            if e.args[0] == socket.EAI_ADDRFAMILY:
                # python supports ipv6, but it's not configured on the network
                # interface, so skip this test.
                return
            raise
        url = '%s://[::1]:%d/hello' % (self.get_protocol(), port)

        # ipv6 is currently enabled by default but can be disabled
        self.http_client.fetch(url, self.stop, allow_ipv6=False)
        response = self.wait()
        self.assertEqual(response.code, 599)

        self.http_client.fetch(url, self.stop)
        response = self.wait()
        self.assertEqual(response.body, b"Hello world!") 
Example 13
Project: tornado-zh   Author: tao12345666333   File: tcpserver.py    License: MIT License 6 votes vote down vote up
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 14
Project: scripts   Author: KiriKira   File: ipip.py    License: MIT License 6 votes vote down vote up
def domain_ip_parser(ip_or_domain_or_url, local_dns, ipv6):
    """parsing the arg to get the hostname to query."""
    #ip_or_domain_or_url = str(sys.argv[1])
    if ip_or_domain_or_url.startswith("https://") or ip_or_domain_or_url.startswith("http://"):
        ip_or_domain = ip_or_domain_or_url.split('/')[2]
    elif ip_or_domain_or_url == ".":
        ip_or_domain = ""
    else:
        ip_or_domain = ip_or_domain_or_url

    if local_dns:
        import socket
        ip_or_domain = socket.gethostbyname(ip_or_domain)
    elif ipv6:
        import socket
        ip_or_domain = socket.getaddrinfo(ip_or_domain, None, socket.AF_INET6)[0][-1][0]

    return ip_or_domain 
Example 15
Project: recruit   Author: Frank-qlu   File: serving.py    License: Apache License 2.0 6 votes vote down vote up
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 16
Project: Pyro5   Author: irmen   File: socketutil.py    License: MIT License 6 votes vote down vote up
def bind_unused_port(sock: socket.socket, host: Union[str, ipaddress.IPv4Address, ipaddress.IPv6Address] = 'localhost') -> int:
    """Bind the socket to a free port and return the port number.
    This code is based on the code in the stdlib's test.test_support module."""
    if sock.family in (socket.AF_INET, socket.AF_INET6) and sock.type == socket.SOCK_STREAM:
        if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):
            with contextlib.suppress(socket.error):
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)
    if not isinstance(host, str):
        host = str(host)
    if sock.family == socket.AF_INET:
        if host == 'localhost':
            sock.bind(('127.0.0.1', 0))
        else:
            sock.bind((host, 0))
    elif sock.family == socket.AF_INET6:
        if host == 'localhost':
            sock.bind(('::1', 0, 0, 0))
        else:
            sock.bind((host, 0, 0, 0))
    else:
        raise CommunicationError("unsupported socket family: " + str(sock.family))
    return sock.getsockname()[1] 
Example 17
Project: Pyro5   Author: irmen   File: nameserver.py    License: MIT License 6 votes vote down vote up
def start_ns(host=None, port=None, enableBroadcast=True, bchost=None, bcport=None,
             unixsocket=None, nathost=None, natport=None, storage=None):
    """utility fuction to quickly get a Name server daemon to be used in your own event loops.
    Returns (nameserverUri, nameserverDaemon, broadcastServer)."""
    daemon = NameServerDaemon(host, port, unixsocket, nathost=nathost, natport=natport, storage=storage)
    bcserver = None
    nsUri = daemon.uriFor(daemon.nameserver)
    if not unixsocket:
        hostip = daemon.sock.getsockname()[0]
        if hostip.startswith("127."):
            # not starting broadcast server for localhost.
            enableBroadcast = False
        if enableBroadcast:
            internalUri = daemon.uriFor(daemon.nameserver, nat=False)
            bcserver = BroadcastServer(internalUri, bchost, bcport, ipv6=daemon.sock.family == socket.AF_INET6)
    return nsUri, daemon, bcserver 
Example 18
Project: Pyro5   Author: irmen   File: test_socketutil.py    License: MIT License 6 votes vote down vote up
def testCreateUnboundSockets6(self):
        if not has_ipv6:
            pytest.skip("no ipv6 capability")
        s = socketutil.create_socket(ipv6=True)
        assert socket.AF_INET6 == s.family
        bs = socketutil.create_bc_socket(ipv6=True)
        assert socket.AF_INET6 == bs.family
        with contextlib.suppress(socket.error):
            host, port, _, _ = s.getsockname()
            # can either fail with socket.error or return (host,0)
            assert 0 == port
        with contextlib.suppress(socket.error):
            host, port, _, _ = bs.getsockname()
            # can either fail with socket.error or return (host,0)
            assert 0 == port
        s.close()
        bs.close() 
Example 19
Project: calibre-web   Author: janeczku   File: server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _make_gevent_socket(self):
        if os.name != 'nt':
            unix_socket_file = os.environ.get("CALIBRE_UNIX_SOCKET")
            if unix_socket_file:
                return self._make_gevent_unix_socket(unix_socket_file), "unix:" + unix_socket_file

        if self.listen_address:
            return (self.listen_address, self.listen_port), None

        if os.name == 'nt':
            self.listen_address = '0.0.0.0'
            return (self.listen_address, self.listen_port), None

        try:
            address = ('::', self.listen_port)
            sock = WSGIServer.get_listener(address, family=socket.AF_INET6)
        except socket.error as ex:
            log.error('%s', ex)
            log.warning('Unable to listen on "", trying on IPv4 only...')
            address = ('', self.listen_port)
            sock = WSGIServer.get_listener(address, family=socket.AF_INET)

        return sock, _readable_listen_address(*address) 
Example 20
Project: jbox   Author: jpush   File: serving.py    License: MIT License 6 votes vote down vote up
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 21
Project: rekall   Author: google   File: tcpip_vtypes.py    License: GNU General Public License v2.0 6 votes vote down vote up
def dual_stack_sockets(self, vm=None):
        """Handle Windows dual-stack sockets"""

        # If this pointer is valid, the socket is bound to
        # a specific IP address. Otherwise, the socket is
        # listening on all IP addresses of the address family.
        local_addr = self.LocalAddr.dereference(vm=vm)

        # Switch to the correct address space.
        af_inet = self.InetAF.dereference(vm=vm)

        # Note the remote address is always INADDR_ANY or
        # INADDR6_ANY for sockets. The moment a client
        # connects to the listener, a TCP_ENDPOINT is created
        # and that structure contains the remote address.
        if local_addr:
            inaddr = local_addr.pData.dereference().dereference()
            if af_inet.AddressFamily == AF_INET:
                yield "v4", inaddr.addr4, inaddr_any
            else:
                yield "v6", inaddr.addr6, inaddr6_any
        else:
            yield "v4", inaddr_any, inaddr_any
            if af_inet.AddressFamily.v() == AF_INET6:
                yield "v6", inaddr6_any, inaddr6_any 
Example 22
Project: rekall   Author: google   File: tcpip_vtypes.py    License: GNU General Public License v2.0 6 votes vote down vote up
def dual_stack_sockets(self, vm=None):
        """Handle Windows dual-stack sockets"""

        # If this pointer is valid, the socket is bound to
        # a specific IP address. Otherwise, the socket is
        # listening on all IP addresses of the address family.
        local_addr = self.LocalAddr.dereference(vm=vm)

        # Switch to the correct address space.
        af_inet = self.InetAF.dereference(vm=vm)

        # Note the remote address is always INADDR_ANY or
        # INADDR6_ANY for sockets. The moment a client
        # connects to the listener, a TCP_ENDPOINT is created
        # and that structure contains the remote address.
        if local_addr:
            inaddr = local_addr.pData.dereference()
            if af_inet.AddressFamily == AF_INET:
                yield "v4", inaddr.addr4, inaddr_any
            else:
                yield "v6", inaddr.addr6, inaddr6_any
        else:
            yield "v4", inaddr_any, inaddr_any
            if af_inet.AddressFamily.v() == AF_INET6:
                yield "v6", inaddr6_any, inaddr6_any 
Example 23
Project: dionaea   Author: DinoTools   File: nfq.py    License: GNU General Public License v2.0 6 votes vote down vote up
def is_local_addr(addr):
    # sanatize addr, maybe IPv4 mapped
    # I think it is impossible to connect yourself via
    # IPv4 mapped IPv6 sockets, but ...
    if addr.startswith('::ffff:'):
        addr = addr[7:]

    # getifaddrs and compile a dict of addrs assigned to the host
    ifaddrs = g_dionaea.getifaddrs()

    vX = {}
    for iface in ifaddrs:
        for family in ifaddrs[iface]:
            if family != AF_INET and family != AF_INET6:
                continue
            for i in ifaddrs[iface][family]:
                if 'addr' in i:
                    vX[i['addr']] = iface


    if addr in vX:
        return True
    return False 
Example 24
Project: ivre   Author: cea-sec   File: utils.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ip2int(ipstr):
    """Converts the classical decimal, dot-separated, string
    representation of an IPv4 address, or the hexadecimal,
    colon-separated, string representation of an IPv6 address, to an
    integer.

    """
    try:
        ipstr = ipstr.decode()
    except AttributeError:
        pass
    try:
        return struct.unpack('!I', socket.inet_aton(ipstr))[0]
    except socket.error:
        val1, val2 = struct.unpack(
            '!QQ', socket.inet_pton(socket.AF_INET6, ipstr),
        )
        return (val1 << 64) + val2 
Example 25
Project: rtp_cluster   Author: sippy   File: Rtp_proxy_client_net.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def getdestbyaddr(self, address, af):
        #print('getaddrinfo', address[0], address[1], af, self.sock_type)
        if af == AF_INET6 and address[0].startswith('['):
            return address
        ainfo = getaddrinfo(address[0], address[1], af, self.sock_type)
        amatch = [x[4] for x in ainfo if x[0] == af]
        if len(amatch) == 0:
            raise Exception('no match for the %s in AF %s' % (address, af))
        amatch = amatch[0]
        if af == AF_INET6:
            return (('[%s]' % amatch[0], amatch[1]))
        return ((amatch[0], amatch[1])) 
Example 26
Project: rtp_cluster   Author: sippy   File: Udp_server.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def run(self):
        maxemptydata = 100
        while True:
            try:
                data, address = self.userv.skt.recvfrom(8192)
                if not data and address == None:
                    # Ugly hack to detect socket being closed under us on Linux.
                    # The problem is that even call on non-closed socket can
                    # sometimes return empty data buffer, making AsyncReceiver
                    # to exit prematurely.
                    maxemptydata -= 1
                    if maxemptydata == 0:
                        break
                    continue
                else:
                    maxemptydata = 100
                rtime = MonoTime()
            except Exception as why:
                if isinstance(why, socket.error) and why.errno in (ECONNRESET, ENOTCONN, ESHUTDOWN):
                    break
                if isinstance(why, socket.error) and why.errno in (EINTR,):
                    continue
                else:
                    print(datetime.now(), 'Udp_server: unhandled exception when receiving incoming data')
                    print('-' * 70)
                    traceback.print_exc(file = sys.stdout)
                    print('-' * 70)
                    sys.stdout.flush()
                    sleep(1)
                    continue
            if self.userv.uopts.family == socket.AF_INET6:
                address = ('[%s]' % address[0], address[1])
            ED2.callFromThread(self.userv.handle_read, data, address, rtime)
        self.userv = None 
Example 27
Project: rtp_cluster   Author: sippy   File: Udp_server.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def isWildCard(self):
        if (self.family, self.laddress[0]) in ((socket.AF_INET, '0.0.0.0'), \
          (socket.AF_INET6, '::')):
            return True
        return False 
Example 28
Project: custodia   Author: latchset   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def peer_info(self):
        if self.peer_creds is not None:
            return self._creds['pid']
        elif self.request.family in {socket.AF_INET, socket.AF_INET6}:
            return self.request.getpeername()
        return None 
Example 29
Project: custodia   Author: latchset   File: server.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_systemd_socket(self, address):
        fds = sd.listen_fds()
        if not fds:
            return address
        elif len(fds) > 1:
            raise ValueError('Too many listening sockets', fds)

        if isinstance(address, tuple):
            port = address[1]
            # systemd uses IPv6
            if not sd.is_socket_inet(fds[0], family=socket.AF_INET6,
                                     type=socket.SOCK_STREAM,
                                     listening=True, port=port):
                raise ValueError(
                    "FD {} is not TCP IPv6 socket on port {}".format(
                        fds[0], port
                    )
                )
            logger.info('Using systemd socket activation on port %i', port)
            sock = socket.fromfd(fds[0], socket.AF_INET6, socket.SOCK_STREAM)
        else:
            if not sd.is_socket_unix(fds[0], socket.SOCK_STREAM,
                                     listening=True, path=address):
                raise ValueError(
                    "FD {} is not Unix stream socket on path {}".format(
                        fds[0], address
                    )
                )
            logger.info('Using systemd socket activation on path %s', address)
            sock = socket.fromfd(fds[0], socket.AF_UNIX, socket.SOCK_STREAM)

        if sys.version_info[0] < 3:
            # Python 2.7's socket.fromfd() returns _socket.socket
            sock = socket.socket(_sock=sock)
        return sock 
Example 30
Project: custodia   Author: latchset   File: test_cli.py    License: GNU General Public License v3.0 5 votes vote down vote up
def find_free_address():
    """Bind to None, 0 to find an unused port on localhost (IPv4 or IPv6)

    :return:
    """
    err = None
    for info in socket.getaddrinfo(None, 0, socket.AF_UNSPEC,
                                   socket.SOCK_STREAM):
        family, stype, proto, _, addr = info
        sock = None
        try:
            sock = socket.socket(family, stype, proto)
            sock.bind(addr)
            if family == socket.AF_INET:
                return "{}:{}".format(*sock.getsockname())
            elif family == socket.AF_INET6:
                return "[{}]:{}".format(*sock.getsockname()[:2])
        except socket.error as e:
            err = e
        finally:
            if sock is not None:
                sock.close()
    if err is not None:
        raise err  # pylint: disable=raising-bad-type
    else:
        raise socket.error("getaddrinfo returns an empty list")