socket.AF_UNSPEC

Here are the examples of the python api socket.AF_UNSPEC taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

126 Examples 7

Example 1

Project: kafka-python Source File: test_client.py
    def test_init_with_unicode_csv(self):
        with patch.object(SimpleClient, 'load_metadata_for_topics'):
            client = SimpleClient(hosts=u'kafka01:9092,kafka02:9092,kafka03:9092')

        self.assertEqual(
            sorted([('kafka01', 9092, socket.AF_UNSPEC), ('kafka02', 9092, socket.AF_UNSPEC),
                    ('kafka03', 9092, socket.AF_UNSPEC)]),
            sorted(client.hosts))

Example 2

Project: kafka-python Source File: test_client.py
    def test_init_with_csv(self):
        with patch.object(SimpleClient, 'load_metadata_for_topics'):
            client = SimpleClient(hosts='kafka01:9092,kafka02:9092,kafka03:9092')

        self.assertEqual(
            sorted([('kafka01', 9092, socket.AF_UNSPEC), ('kafka02', 9092, socket.AF_UNSPEC),
                    ('kafka03', 9092, socket.AF_UNSPEC)]),
            sorted(client.hosts))

Example 3

Project: kafka-python Source File: test_client.py
    def test_init_with_list(self):
        with patch.object(SimpleClient, 'load_metadata_for_topics'):
            client = SimpleClient(hosts=['kafka01:9092', 'kafka02:9092', 'kafka03:9092'])

        self.assertEqual(
            sorted([('kafka01', 9092, socket.AF_UNSPEC), ('kafka02', 9092, socket.AF_UNSPEC),
                    ('kafka03', 9092, socket.AF_UNSPEC)]),
            sorted(client.hosts))

Example 4

Project: kafka-python Source File: test_client_async.py
@pytest.mark.parametrize("bootstrap,expected_hosts", [
    (None, [('localhost', 9092, socket.AF_UNSPEC)]),
    ('foobar:1234', [('foobar', 1234, socket.AF_UNSPEC)]),
    ('fizzbuzz', [('fizzbuzz', 9092, socket.AF_UNSPEC)]),
    ('foo:12,bar:34', [('foo', 12, socket.AF_UNSPEC), ('bar', 34, socket.AF_UNSPEC)]),
    (['fizz:56', 'buzz'], [('fizz', 56, socket.AF_UNSPEC), ('buzz', 9092, socket.AF_UNSPEC)]),
])
def test_bootstrap_servers(mocker, bootstrap, expected_hosts):
    mocker.patch.object(KafkaClient, '_bootstrap')
    if bootstrap is None:
        KafkaClient(api_version=(0, 9)) # pass api_version to skip auto version checks
    else:
        KafkaClient(bootstrap_servers=bootstrap, api_version=(0, 9))

    # host order is randomized internally, so resort before testing
    (hosts,), _ = KafkaClient._bootstrap.call_args  # pylint: disable=no-member
    assert sorted(hosts) == sorted(expected_hosts)

Example 5

Project: ifupdown2 Source File: nlmanager.py
    def _get_iface_by_name(self, ifname):
        """
        Return a Link object for ifname
        """
        debug = RTM_GETLINK in self.debug

        link = Link(RTM_GETLINK, debug)
        link.flags = NLM_F_REQUEST | NLM_F_ACK
        link.body = pack('=Bxxxiii', socket.AF_UNSPEC, 0, 0, 0)
        link.add_attribute(Link.IFLA_IFNAME, ifname)
        link.build_message(self.sequence.next(), self.pid)

        try:
            return self.tx_nlpacket_get_response(link)[0]

        except NetlinkNoAddressError:
            log.info("Netlink did not find interface %s" % ifname)
            return None

Example 6

Project: flasktodo Source File: serving.py
Function: select_ip_version
def select_ip_version(host, port):
    """Returns AF_INET4 or AF_INET6 depending on where to connect to."""
    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 7

Project: StarCluster Source File: sshutils.py
    def _get_socket(self, hostname, port):
        addrinfo = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC,
                                      socket.SOCK_STREAM)
        for (family, socktype, proto, canonname, sockaddr) in addrinfo:
            if socktype == socket.SOCK_STREAM:
                af = family
                break
            else:
                raise exception.SSHError(
                    'No suitable address family for %s' % hostname)
        sock = socket.socket(af, socket.SOCK_STREAM)
        sock.settimeout(self._timeout)
        sock.connect((hostname, port))
        return sock

Example 8

Project: ccs-calendarserver Source File: utils.py
def getIPsFromHost(host):
    """
    Map a hostname to an IPv4 or IPv6 address.

    @param host: the hostname
    @type host: C{str}

    @return: a C{set} of IPs
    """
    ips = set()
    # Use AF_UNSPEC rather than iterating (socket.AF_INET, socket.AF_INET6)
    # because getaddrinfo() will raise an exception if no match is found for
    # the specified family
    # TODO: potentially use twext.internet.gaiendpoint instead
    results = socket.getaddrinfo(host, None, socket.AF_UNSPEC, socket.SOCK_STREAM)
    for _ignore_family, _ignore_socktype, _ignore_proto, _ignore_canonname, sockaddr in results:
        ips.add(sockaddr[0])

    return ips

Example 9

Project: SickGear Source File: netutil.py
Function: is_valid_ip
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True

Example 10

Project: python-driver Source File: policies.py
Function: translate
    def translate(self, addr):
        """
        Reverse DNS the public broadcast_address, then lookup that hostname to get the AWS-resolved IP, which
        will point to the private IP address within the same datacenter.
        """
        # get family of this address so we translate to the same
        family = socket.getaddrinfo(addr, 0, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][0]
        host = socket.getfqdn(addr)
        for a in socket.getaddrinfo(host, 0, family, socket.SOCK_STREAM):
            try:
                return a[4][0]
            except Exception:
                pass
        return addr

Example 11

Project: vdsm Source File: protocoldetector.py
def _create_socket(host, port):
    addrinfo = socket.getaddrinfo(host, port,
                                  socket.AF_UNSPEC, socket.SOCK_STREAM)

    family, socktype, proto, _, sockaddr = addrinfo[0]
    server_socket = socket.socket(family, socktype, proto)
    filecontrol.set_close_on_exec(server_socket.fileno())
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(sockaddr)

    return server_socket

Example 12

Project: p2ptv-pi Source File: Multicast.py
Function: send
    def _send(self, addr, msg):
        for res in socket.getaddrinfo(addr, self.config['multicast_port'], socket.AF_UNSPEC, socket.SOCK_DGRAM):
            af, socktype, proto, canonname, sa = res

        try:
            sock = socket.socket(af, socktype)
            sock.sendto(msg, sa)
        except Exception as e:
            self.log.warning("Error sending '%s...' to %s: %s" % (msg[:8], str(sa), e))

        return sock

Example 13

Project: zygote Source File: _httpserver_2.py
Function: valid_ip
    def _valid_ip(self, ip):
        try:
            res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                     socket.SOCK_STREAM,
                                     0, socket.AI_NUMERICHOST)
            return bool(res)
        except socket.gaierror, e:
            if e.args[0] == socket.EAI_NONAME:
                return False
            raise
        return True

Example 14

Project: simian Source File: wsgi_server_test.py
  def test_start_all_fail_to_bind(self):
    failing_server = self.mox.CreateMock(
        wsgi_server._SingleAddressWsgiServer)
    self.mox.StubOutWithMock(wsgi_server, '_SingleAddressWsgiServer')
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    socket.getaddrinfo('localhost', 123, socket.AF_UNSPEC, socket.SOCK_STREAM,
                       0, socket.AI_PASSIVE).AndReturn(
                           [(None, None, None, None, ('foo', 'bar', 'baz'))])
    wsgi_server._SingleAddressWsgiServer(('foo', 'bar'), None).AndReturn(
        failing_server)
    failing_server.start().AndRaise(wsgi_server.BindError)

    self.mox.ReplayAll()
    self.assertRaises(wsgi_server.BindError, self.server.start)
    self.mox.VerifyAll()

Example 15

Project: gajim Source File: socks5.py
Function: init
	def __init__(self, idlequeue, port):
		''' handle all incomming connections on (0.0.0.0, port) 
		This class implements IdleObject, but we will expect
		only pollin events though
		'''
		self.port = port
		self.ais = socket.getaddrinfo(None, port, socket.AF_UNSPEC,
					socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_PASSIVE)
		self.queue_idx = -1	
		self.idlequeue = idlequeue
		self.queue = None
		self.started = False
		self._sock = None
		self.fd = -1

Example 16

Project: blackhole Source File: test_config.py
    def test_ipv6_disabled(self):
        cfile = create_config(('listen=:::25', ))
        conf = Config(cfile).load()
        conf._listen = [('::', 25, socket.AF_UNSPEC, {})]
        with pytest.raises(ConfigException), \
                mock.patch('socket.has_ipv6', False):
            conf.test_ipv6_support()

Example 17

Project: free-outernet Source File: free-outernet.py
Function: get_socket
def getSocket():
    s = None
    for res in socket.getaddrinfo(UDP_HOST, UDP_PORT, socket.AF_UNSPEC, socket.SOCK_DGRAM, 0,
                   socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = res
        try:
            s = socket.socket(af, socktype, proto)
        except OSError as msg:
            print('Socket error', msg)
            continue
        try:
            s.bind(sa)
        except OSError as msg:
            print('Bind error', msg)
            s.close()
            continue
        break
    return s

Example 18

Project: aiosocks Source File: protocols.py
    @asyncio.coroutine
    def _get_dst_addr(self):
        infos = yield from self._loop.getaddrinfo(
            self._dst_host, self._dst_port, family=socket.AF_UNSPEC,
            type=socket.SOCK_STREAM, proto=socket.IPPROTO_TCP,
            flags=socket.AI_ADDRCONFIG)
        if not infos:
            raise OSError('getaddrinfo() returned empty list')
        return infos[0][0], infos[0][4][0]

Example 19

Project: rosbridge_suite Source File: netutil.py
Function: resolve
    @run_on_executor
    def resolve(self, host, port, family=socket.AF_UNSPEC):
        # 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 family, socktype, proto, canonname, address in addrinfo:
            results.append((family, address))
        return results

Example 20

Project: site Source File: base_server.py
Function: init
    def __init__(self, addresses, client):
        self._servers = set()
        for address, port in addresses:
            info = socket.getaddrinfo(address, port, socket.AF_UNSPEC, socket.SOCK_STREAM)
            for af, socktype, proto, canonname, sa in info:
                sock = socket.socket(af, socktype, proto)
                sock.setblocking(0)
                sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                sock.bind(sa)
                self._servers.add(sock)

        self._stop = threading.Event()
        self._clients = set()
        self._ClientClass = client
        self._send_queue = defaultdict(deque)
        self._job_queue = []
        self._job_queue_lock = threading.Lock()

Example 21

Project: ccm Source File: common.py
def check_socket_available(itf, return_on_error=False):
    info = socket.getaddrinfo(itf[0], itf[1], socket.AF_UNSPEC, socket.SOCK_STREAM)
    if not info:
        raise UnavailableSocketError("Failed to get address info for [%s]:%s" % itf)

    (family, socktype, proto, canonname, sockaddr) = info[0]
    s = socket.socket(family, socktype)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    try:
        s.bind(sockaddr)
        s.close()
        return True
    except socket.error as msg:
        s.close()
        if return_on_error:
            return False
        addr, port = itf
        raise UnavailableSocketError("Inet address %s:%s is not available: %s" % (addr, port, msg))

Example 22

Project: ccm Source File: common.py
def interface_is_ipv6(itf):
    info = socket.getaddrinfo(itf[0], itf[1], socket.AF_UNSPEC, socket.SOCK_STREAM)
    if not info:
        raise UnavailableSocketError("Failed to get address info for [%s]:%s" % itf)

    return socket.AF_INET6 == info[0][0]

Example 23

Project: rosbridge_suite Source File: netutil_test.py
Function: test_future_interface
    @gen_test
    def test_future_interface(self):
        addrinfo = yield self.resolver.resolve('localhost', 80,
                                               socket.AF_UNSPEC)
        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)),
                      addrinfo)

Example 24

Project: scales Source File: scales_socket.py
Function: resolveaddr
  def _resolveAddr(self):
    return socket.getaddrinfo(
      self.host,
      self.port,
      socket.AF_UNSPEC,
      socket.SOCK_STREAM,
      0,
      socket.AI_PASSIVE | socket.AI_ADDRCONFIG)

Example 25

Project: Supybot Source File: net.py
Function: get_socket
def getSocket(host):
    """Returns a socket of the correct AF_INET type (v4 or v6) in order to
    communicate with host.
    """
    addrinfo = socket.getaddrinfo(host, None,
                                  socket.AF_UNSPEC, socket.SOCK_STREAM)
    family = addrinfo[0][0]
    return socket.socket(family, socket.SOCK_STREAM)

Example 26

Project: fail2ban Source File: ipdns.py
Function: eq
	def __eq__(self, other):
		if self._family == IPAddr.CIDR_RAW and not isinstance(other, IPAddr):
			return self._raw == other
		if not isinstance(other, IPAddr):
			if other is None: return False
			other = IPAddr(other)
		if self._family != other._family: return False
		if self._family == socket.AF_UNSPEC:
			return self._raw == other._raw
		return (
			(self._addr == other._addr) and
			(self._plen == other._plen)
		)

Example 27

Project: amqpstorm Source File: io.py
    def _get_socket_addresses(self):
        """Get Socket address information.

        :rtype: list
        """
        family = socket.AF_UNSPEC
        if not socket.has_ipv6:
            family = socket.AF_INET
        try:
            addresses = socket.getaddrinfo(self._parameters['hostname'],
                                           self._parameters['port'], family)
        except socket.gaierror as why:
            raise AMQPConnectionError(why)
        return addresses

Example 28

Project: send_nsca Source File: nsca.py
Function: sock_connect
    def _sock_connect(self, host, port, timeout=None, connect_all=True):
        conns = []
        for (family, socktype, proto, canonname, sockaddr) in socket.getaddrinfo(
                host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, 0):
            try:
                s = socket.socket(family, socktype, proto)
                s.connect(sockaddr)
                conns.append(s)
                if timeout is not None:
                    s.settimeout(timeout)
                if not connect_all:
                    break
            except socket.error:
                continue
        if not conns:
            raise socket.error("could not connect to %s:%d" % (self.remote_host, self.port))
        return conns

Example 29

Project: freeipa Source File: krbinstance.py
    def __common_setup(self, realm_name, host_name, domain_name, admin_password):
        self.fqdn = host_name
        self.realm = realm_name.upper()
        self.host = host_name.split(".")[0]
        self.ip = socket.getaddrinfo(host_name, None, socket.AF_UNSPEC, socket.SOCK_STREAM)[0][4][0]
        self.domain = domain_name
        self.suffix = ipautil.realm_to_suffix(self.realm)
        self.kdc_password = ipautil.ipa_generate_password()
        self.admin_password = admin_password
        self.dm_password = admin_password

        self.__setup_sub_dict()

        self.backup_state("running", self.is_running())
        try:
            self.stop()
        except Exception:
            # It could have been not running
            pass

Example 30

Project: bernhard Source File: __init__.py
Function: init
    def __init__(self, host, port):
        log.debug("Using UDP Transport")

        self.host = None
        self.port = None
        for res in socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_DGRAM):
            af, socktype, proto, canonname, sa = res
            try:
                self.sock = socket.socket(af, socktype, proto)
                self.host = sa[0]
                self.port = sa[1]
            except socket.error as e:
                log.exception("Exception opening socket: %s", e)
                self.sock = None
                continue
            break
        if self.sock is None:
            raise TransportError("Could not open socket.")

Example 31

Project: rabbitpy Source File: io.py
Function: get_addr_info
    def _get_addr_info(self):
        family = socket.AF_UNSPEC
        if not socket.has_ipv6:
            family = socket.AF_INET
        try:
            res = socket.getaddrinfo(self._args['host'], self._args['port'],
                                     family, socket.SOCK_STREAM, 0)
        except socket.error as error:
            LOGGER.error('Could not resolve %s: %s', self._args['host'], error,
                         exc_info=True)
            return []
        return res

Example 32

Project: ifupdown2 Source File: nllistener.py
    def get_all_addresses(self):
        family = socket.AF_UNSPEC
        debug = RTM_GETADDR in self.debug

        addr = Address(RTM_GETADDR, debug)
        addr.flags = NLM_F_REQUEST | NLM_F_DUMP
        addr.body = pack('Bxxxi', family, 0)
        addr.build_message(self.sequence.next(), self.pid)

        if debug:
            self.debug_seq_pid[(addr.seq, addr.pid)] = True

        self.tx_nlpacket_get_response(addr)

Example 33

Project: python-compat-runtime Source File: wsgi_server_test.py
  def test_start_port_in_use(self):
    self.mox.StubOutWithMock(socket, 'getaddrinfo')
    self.mox.StubOutWithMock(self.server, 'bind')
    af = object()
    socktype = object()
    proto = object()
    socket.getaddrinfo('localhost', 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0,
                       socket.AI_PASSIVE).AndReturn(
                           [(af, socktype, proto, None, None)])
    self.server.bind(af, socktype, proto).AndRaise(socket.error)
    self.mox.ReplayAll()
    self.assertRaises(wsgi_server.BindError, self.server.start)
    self.mox.VerifyAll()

Example 34

Project: asyncio Source File: test_windows_utils.py
    def test_winsocketpair_invalid_args(self):
        self.assertRaises(ValueError,
                          windows_utils.socketpair, family=socket.AF_UNSPEC)
        self.assertRaises(ValueError,
                          windows_utils.socketpair, type=socket.SOCK_DGRAM)
        self.assertRaises(ValueError,
                          windows_utils.socketpair, proto=1)

Example 35

Project: calibre Source File: pre_activated.py
        def pre_activated_socket():  # noqa
            num = systemd.sd_listen_fds(1)  # Remove systemd env vars so that child processes do not inherit them
            if num > 1:
                raise EnvironmentError('Too many file descriptors received from systemd')
            if num != 1:
                return None
            fd = 3  # systemd starts activated sockets at 3
            ret = systemd.sd_is_socket(fd, socket.AF_UNSPEC, socket.SOCK_STREAM, -1)
            if ret == 0:
                raise EnvironmentError('The systemd socket file descriptor is not valid')
            if ret < 0:
                raise EnvironmentError('Failed to check the systemd socket file descriptor for validity')
            family = getsockfamily(fd)
            return socket.fromfd(fd, family, socket.SOCK_STREAM)

Example 36

Project: ifupdown2 Source File: nlmanager.py
Function: link_add
    def _link_add(self, ifindex, ifname, kind, ifla_info_data):
        """
        Build and TX a RTM_NEWLINK message to add the desired interface
        """
        debug = RTM_NEWLINK in self.debug

        link = Link(RTM_NEWLINK, debug)
        link.flags = NLM_F_CREATE | NLM_F_REQUEST | NLM_F_ACK
        link.body = pack('Bxxxiii', socket.AF_UNSPEC, 0, 0, 0)
        link.add_attribute(Link.IFLA_IFNAME, ifname)
        link.add_attribute(Link.IFLA_LINK, ifindex)
        link.add_attribute(Link.IFLA_LINKINFO, {
            Link.IFLA_INFO_KIND: kind,
            Link.IFLA_INFO_DATA: ifla_info_data
        })
        link.build_message(self.sequence.next(), self.pid)
        return self.tx_nlpacket_get_response(link)

Example 37

Project: blackhole Source File: test_config.py
    def test_ipv6_disabled(self):
        cfile = create_config(('tls_listen=:::465', ))
        conf = Config(cfile).load()
        conf._tls_listen = [('::', 465, socket.AF_UNSPEC, {})]
        with pytest.raises(ConfigException), \
                mock.patch('socket.has_ipv6', False):
            conf.test_tls_ipv6_support()

Example 38

Project: gajim Source File: transports.py
Function: connect
    def connect(self,server=None):
        """ Try to connect. Returns non-empty string on success. """
        try:
            if not server:
                server=self._server
            for ai in socket.getaddrinfo(server[0],server[1],socket.AF_UNSPEC,socket.SOCK_STREAM):
                try:
                    self._sock=socket.socket(*ai[:3])
                    self._sock.connect(ai[4])
                    self._send=self._sock.sendall
                    self._recv=self._sock.recv
                    self.DEBUG("Successfully connected to remote host %s"%repr(server),'start')
                    return 'ok'
                except: continue
        except: pass

Example 39

Project: mlat-client Source File: adeptclient.py
Function: start
    def start(self):
        addrlist = socket.getaddrinfo(host=self.host,
                                      port=self.port,
                                      family=socket.AF_UNSPEC,
                                      type=socket.SOCK_DGRAM,
                                      proto=0,
                                      flags=socket.AI_NUMERICHOST)

        if len(addrlist) != 1:
            # expect exactly one result since we specify AI_NUMERICHOST
            raise IOError('unexpectedly got {0} results when resolving {1}'.format(len(addrlist), self.host))
        a_family, a_type, a_proto, a_canonname, a_sockaddr = addrlist[0]
        self.sock = socket.socket(a_family, a_type, a_proto)
        self.remote_address = a_sockaddr

Example 40

Project: electrum-dash Source File: interface.py
Function: get_simple_socket
    def get_simple_socket(self):
        try:
            l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            self.print_error("cannot resolve hostname")
            return
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.connect(res[4])
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                return s
            except BaseException as e:
                continue
        else:
            self.print_error("failed to connect", str(e))

Example 41

Project: python-opentsdbclient Source File: test_socket_client.py
    @mock.patch.object(socket, 'getaddrinfo')
    @mock.patch.object(socket, 'socket')
    def test_maintain_connection(self, sock_mock, sock_addr_mock):
        self.client.verify_connection = mock.MagicMock()
        pop_list = [True, False]
        self.client.verify_connection.side_effect = lambda: pop_list.pop()
        sock_addr_mock.side_effect = lambda a, b, c, d, e: [(1, 2, 3, 4, 5)]
        tsd = mock.MagicMock()
        tsd.connect = mock.MagicMock()
        sock_mock.side_effect = tsd
        self.client.maintain_connection()
        sock_addr_mock.assert_called_once_with(self.host, self.port,
                                               socket.AF_UNSPEC,
                                               socket.SOCK_STREAM, 0)
        sock_mock.assert_called_once_with(1, 2, 3)
        self.client.tsd.connect.assert_called_once_with(5)

Example 42

Project: shapy Source File: __init__.py
    def delete_root_qdisc(self):
        """
        Deletes root egress qdisc on a interface designated by self.if_index
        and returns the resulting ACK message.
        """
        if_index = getattr(self, 'if_index', self.interface.if_index)
        tm = tcmsg(socket.AF_UNSPEC, if_index, 0, TC_H_ROOT, 0)
        return self._del_qdisc(tm)

Example 43

Project: vdsm Source File: utils.py
Function: create_connected_socket
def create_connected_socket(host, port, sslctx=None, timeout=None):
    addrinfo = socket.getaddrinfo(host, port,
                                  socket.AF_UNSPEC, socket.SOCK_STREAM)
    family, socktype, proto, _, _ = addrinfo[0]
    sock = socket.socket(family, socktype, proto)

    if sslctx:
        sock = sslctx.wrapSocket(sock)

    sock.settimeout(timeout)
    sock.connect((host, port))
    return sock

Example 44

Project: python-driver Source File: test_ipv6.py
    def test_error_multiple(self):
        if len(socket.getaddrinfo('localhost', 9043, socket.AF_UNSPEC, socket.SOCK_STREAM)) < 2:
            raise unittest.SkipTest('localhost only resolves one address')
        cluster = Cluster(connection_class=self.connection_class, contact_points=['localhost'], port=9043,
                          connect_timeout=10, protocol_version=PROTOCOL_VERSION)
        self.assertRaisesRegexp(NoHostAvailable, '\(\'Unable to connect.*Tried connecting to \[\(.*\(.*\].*Last error',
                                cluster.connect)

Example 45

Project: electrum Source File: interface.py
Function: get_simple_socket
    def get_simple_socket(self):
        try:
            l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            self.print_error("cannot resolve hostname")
            return
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.settimeout(10)
                s.connect(res[4])
                s.settimeout(2)
                s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
                return s
            except BaseException as e:
                continue
        else:
            self.print_error("failed to connect", str(e))

Example 46

Project: shapy Source File: test_qdiscs.py
Function: make_msg
    def make_msg(self, attrs):
        """Creates and sends a qdisc-creating message and service template."""
        tcm = tcmsg(socket.AF_UNSPEC, self.if_index, self.qhandle, TC_H_ROOT, 0,
                   attrs)
        msg = Message(type=RTM_NEWQDISC,
                      flags=NLM_F_EXCL | NLM_F_CREATE | NLM_F_REQUEST | NLM_F_ACK,
                      service_template=tcm)
        self.conn.send(msg)
        self.check_ack(self.conn.recv())

Example 47

Project: shapy Source File: __init__.py
    def delete_ingress_qdisc(self):
        """
        Deletes ingress qdisc on a interface designated by self.if_index
        and returns the resulting ACK message.
        """
        if_index = getattr(self, 'if_index', self.interface.if_index)
        tm = tcmsg(socket.AF_UNSPEC, if_index, 0, TC_H_INGRESS, 0)
        return self._del_qdisc(tm)

Example 48

Project: rosbridge_suite Source File: netutil_test.py
    @gen_test
    def test_future_interface_bad_host(self):
        self.skipOnCares()
        with self.assertRaises(Exception):
            yield self.resolver.resolve('an invalid domain', 80,
                                        socket.AF_UNSPEC)

Example 49

Project: viewfinder Source File: netutil.py
Function: is_valid_ip
def is_valid_ip(ip):
    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True

Example 50

Project: electrum-doge Source File: interface.py
    def get_simple_socket(self):
        try:
            l = socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM)
        except socket.gaierror:
            print_error("error: cannot resolve", self.host)
            return
        for res in l:
            try:
                s = socket.socket(res[0], socket.SOCK_STREAM)
                s.connect(res[4])
                return s
            except:
                continue
        else:
            print_error("failed to connect", self.host, self.port)
See More Examples - Go to Next Page
Page 1 Selected Page 2 Page 3