Python socket.AF_INET Examples

The following are 30 code examples of socket.AF_INET(). 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 socket , or try the search function .
Example #1
Source File: fig20_06.py    From PythonClassBook with GNU General Public License v3.0 8 votes vote down vote up
def __init__( self ):
      """Initialize variables and setup server"""
      
      HOST = ""
      PORT = 5000

      self.board = []
      self.currentPlayer = 0
      self.turnCondition = threading.Condition()
      self.gameBeginEvent = threading.Event()

      for i in range( 9 ):
         self.board.append( None )

      # setup server socket
      self.server = socket.socket( socket.AF_INET,
         socket.SOCK_STREAM )
      self.server.bind( ( HOST, PORT ) )
      self.display( "Server awaiting connections..." ) 
Example #2
Source File: usbmux.py    From facebook-wda with MIT License 7 votes vote down vote up
def __init__(self, addr: Union[str, tuple, socket.socket]):
        """
        Args:
            addr: can be /var/run/usbmuxd or (localhost, 27015)
        """
        self._sock = None
        if isinstance(addr, socket.socket):
            self._sock = addr
            return
        if isinstance(addr, str):
            if not os.path.exists(addr):
                raise MuxError("socket unix:{} unable to connect".format(addr))
            family = socket.AF_UNIX
        else:
            family = socket.AF_INET

        self._sock = socket.socket(family, socket.SOCK_STREAM)
        self._sock.connect(addr) 
Example #3
Source File: httpserver.py    From tornado-zh with 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 #4
Source File: ssl_.py    From gist-alfred with 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
Source File: httpserver.py    From tornado-zh with 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 #6
Source File: cli.py    From pyberny with Mozilla Public License 2.0 6 votes vote down vote up
def server(args):
    berny = get_berny(args)
    host, port = args.socket
    server = socket(AF_INET, SOCK_STREAM)
    server.bind((host, int(port)))
    server.listen(0)
    while True:
        sock, addr = server.accept()
        f = sock.makefile('r+')
        geom = handler(berny, f)
        if geom:
            f.write(geom.dumps(args.format))
            f.flush()
        f.close()
        sock.close()
        if not geom:
            break 
Example #7
Source File: kernel.py    From rift-python with 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 #8
Source File: server.py    From sanic with 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 #9
Source File: interface.py    From rift-python with 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 #10
Source File: connections.py    From python-gvm with GNU General Public License v3.0 6 votes vote down vote up
def _new_socket(self):
        transport_socket = socketlib.socket(
            socketlib.AF_INET, socketlib.SOCK_STREAM
        )

        if self.certfile and self.cafile and self.keyfile:
            context = ssl.create_default_context(
                ssl.Purpose.SERVER_AUTH, cafile=self.cafile
            )
            context.check_hostname = False
            context.load_cert_chain(
                certfile=self.certfile,
                keyfile=self.keyfile,
                password=self.password,
            )
            sock = context.wrap_socket(transport_socket, server_side=False)
        else:
            context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
            sock = context.wrap_socket(transport_socket)

        sock.settimeout(self._timeout)

        return sock 
Example #11
Source File: Udp_server.py    From rtp_cluster with 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 #12
Source File: server_setting.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def _do_dns_lookup(hostname: str, port: int) -> str:
    try:
        addr_infos = socket.getaddrinfo(hostname, port, socket.AF_UNSPEC, socket.IPPROTO_IP)
    except (socket.gaierror, IndexError, ConnectionError):
        raise ServerHostnameCouldNotBeResolved(f"Could not resolve {hostname}")

    family, socktype, proto, canonname, sockaddr = addr_infos[0]

    # By default use the first DNS entry, IPv4 or IPv6
    tentative_ip_addr = sockaddr[0]

    # But try to use IPv4 if we have both IPv4 and IPv6 addresses, to work around buggy networks
    for family, socktype, proto, canonname, sockaddr in addr_infos:
        if family == socket.AF_INET:
            tentative_ip_addr = sockaddr[0]

    return tentative_ip_addr 
Example #13
Source File: XAsyncSockets.py    From MicroWebSrv2 with MIT License 6 votes vote down vote up
def Create(asyncSocketsPool, srvAddr, srvBacklog=256, bufSlots=None) :
        try :
            srvSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except :
            raise XAsyncTCPServerException('Create : Cannot open socket (no enought memory).')
        try :
            srvSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            srvSocket.bind(srvAddr)
            srvSocket.listen(srvBacklog)
        except :
            raise XAsyncTCPServerException('Create : Error to binding the TCP server on this address.')
        if not bufSlots :
            bufSlots = XBufferSlots(256, 4096, keepAlloc=True)
        xAsyncTCPServer = XAsyncTCPServer( asyncSocketsPool,
                                           srvSocket,
                                           srvAddr,
                                           bufSlots )
        asyncSocketsPool.NotifyNextReadyForReading(xAsyncTCPServer, True)
        return xAsyncTCPServer

    # ------------------------------------------------------------------------ 
Example #14
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			#set ip, serverip and netmask
			ifaliasreq = struct.pack('<16sBBHI8sBBHI8sBBHI8sI', self.iface_name,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(ip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton(serverip))[0], '\x00'*8,
				16, socket.AF_INET, 0, struct.unpack('<I', socket.inet_aton('255.255.255.255'))[0],
				'\x00'*8,
				0)
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCAIFADDR, ifaliasreq)

			# get flags
			ifr = struct.pack('<16sh', self.iface_name, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCGIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_FREEBSD_IFF_UP
			ifr = struct.pack('<16sh', self.iface_name, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		ps = subprocess.Popen(["route", "add", "-net", rangeip+"/"+netmask, serverip], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example #15
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def freebsd_tun_alloc(self, dev, flags):
		try:
			sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			ifr = struct.pack('<16si', 'tun', 0)
			self.iface_name = fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCIFCREATE2, ifr)
			self.iface_name = self.iface_name.rstrip("\x00")

			buff = array.array('c', dev+"\x00")
			caddr_t, _ = buff.buffer_info()
			ifr = struct.pack('16sP', self.iface_name, caddr_t);

			fcntl.ioctl(sockfd, self.IOCTL_FREEBSD_SIOCSIFNAME, ifr)
			tun = os.open("/dev/"+self.iface_name, os.O_RDWR | os.O_NONBLOCK)
			self.iface_name = dev

		except IOError as e:
			print e
			common.internal_print("Error: Cannot create tunnel. Is {0} in use?".format(dev), -1)
			sys.exit(-1)

		return tun 
Example #16
Source File: SCTP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def stop(self):
		self._stop = True

		if self.threads:
			for t in self.threads:
				t.stop()
		
		# not so nice solution to get rid of the block of listen()
		# unfortunately close() does not help on the block
		try:
			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			if self.config.get("Global", "serverbind") == "0.0.0.0":
				server_socket.connect(("127.0.0.1", int(self.config.get(self.get_module_configname(), "serverport"))))
			else:
				server_socket.connect((self.config.get("Global", "serverbind"), int(self.config.get(self.get_module_configname(), "serverport"))))
		except:
			pass

		return 
Example #17
Source File: interface.py    From XFLTReaT with MIT License 6 votes vote down vote up
def lin_set_ip_address(self, dev, ip, serverip, netmask):
		sockfd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		try:
			# set IP
			ifr  = struct.pack('<16sH2s4s8s', dev, socket.AF_INET, "\x00"*2, socket.inet_aton(ip), "\x00"*8)
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFADDR, ifr)

			# get flags
			ifr = struct.pack('<16sh', dev, 0)
			flags = struct.unpack('<16sh', fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr))[1]

			# set new flags
			flags = flags | self.IOCTL_LINUX_IFF_UP
			ifr = struct.pack('<16sh', dev, flags)

			# iface up
			fcntl.ioctl(sockfd, self.IOCTL_LINUX_SIOCSIFFLAGS, ifr)
		except Exception as e:
			common.internal_print("Something went wrong with setting up the interface.", -1)
			print(e)
			sys.exit(-1)

		# adding new route for forwarding packets properly.
		integer_ip = struct.unpack(">I", socket.inet_pton(socket.AF_INET, serverip))[0]
		rangeip = socket.inet_ntop(socket.AF_INET, struct.pack(">I", integer_ip & ((2**int(netmask))-1)<<32-int(netmask)))

		integer_netmask = struct.pack(">I", ((2**int(netmask))-1)<<32-int(netmask))
		netmask = socket.inet_ntoa(integer_netmask)

		ps = subprocess.Popen(["route", "add", "-net", rangeip, "netmask", netmask, "dev", dev], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
		(stdout, stderr) = ps.communicate()
		if stderr:
			if not "File exists" in stderr:
				common.internal_print("Error: adding client route: {0}".format(stderr), -1)
				sys.exit(-1)

		return 
Example #18
Source File: SCTP_generic.py    From XFLTReaT with MIT License 6 votes vote down vote up
def check(self):
		try:
			common.internal_print("Checking module on server: {0}".format(self.get_module_name()))

			server_socket = self.sctp.sctpsocket_tcp(socket.AF_INET)
			server_socket.settimeout(3)
			server_socket.connect((self.config.get("Global", "remoteserverip"), int(self.config.get(self.get_module_configname(), "serverport"))))
			client_fake_thread = SCTP_generic_thread(0, 0, None, None, server_socket, None, self.authentication, self.encryption_module, self.verbosity, self.config, self.get_module_name())
			client_fake_thread.do_check()
			client_fake_thread.communication(True)

			self.cleanup(server_socket)

		except socket.timeout:
			common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)
		except socket.error as exception:
			if exception.args[0] == 111:
				common.internal_print("Checking failed: {0}".format(self.get_module_name()), -1)
			else:
				common.internal_print("Connection error: {0}".format(self.get_module_name()), -1)
			self.cleanup(server_socket)

		return 
Example #19
Source File: bot.py    From bot with MIT License 5 votes vote down vote up
def _recreate(self) -> None:
        """Re-create the connector, aiohttp session, the APIClient and the Redis session."""
        # Use asyncio for DNS resolution instead of threads so threads aren't spammed.
        # Doesn't seem to have any state with regards to being closed, so no need to worry?
        self._resolver = aiohttp.AsyncResolver()

        # Its __del__ does send a warning but it doesn't always show up for some reason.
        if self._connector and not self._connector._closed:
            log.warning(
                "The previous connector was not closed; it will remain open and be overwritten"
            )

        if self.redis_session and not self.redis_session.closed:
            log.warning(
                "The previous redis pool was not closed; it will remain open and be overwritten"
            )

        # Create the redis session
        self.loop.create_task(self._create_redis_session())

        # Use AF_INET as its socket family to prevent HTTPS related problems both locally
        # and in production.
        self._connector = aiohttp.TCPConnector(
            resolver=self._resolver,
            family=socket.AF_INET,
        )

        # Client.login() will call HTTPClient.static_login() which will create a session using
        # this connector attribute.
        self.http.connector = self._connector

        # Its __del__ does send a warning but it doesn't always show up for some reason.
        if self.http_session and not self.http_session.closed:
            log.warning(
                "The previous session was not closed; it will remain open and be overwritten"
            )

        self.http_session = aiohttp.ClientSession(connector=self._connector)
        self.api_client.recreate(force=True, connector=self._connector) 
Example #20
Source File: caresresolver.py    From tornado-zh with MIT License 5 votes vote down vote up
def resolve(self, host, port, family=0):
        if is_valid_ip(host):
            addresses = [host]
        else:
            # gethostbyname doesn't take callback as a kwarg
            self.channel.gethostbyname(host, family, (yield gen.Callback(1)))
            callback_args = yield gen.Wait(1)
            assert isinstance(callback_args, gen.Arguments)
            assert not callback_args.kwargs
            result, error = callback_args.args
            if error:
                raise Exception('C-Ares returned error %s: %s while resolving %s' %
                                (error, pycares.errno.strerror(error), host))
            addresses = result.addresses
        addrinfo = []
        for address in addresses:
            if '.' in address:
                address_family = socket.AF_INET
            elif ':' in address:
                address_family = socket.AF_INET6
            else:
                address_family = socket.AF_UNSPEC
            if family != socket.AF_UNSPEC and family != address_family:
                raise Exception('Requested socket family %d but got %d' %
                                (family, address_family))
            addrinfo.append((address_family, (address, port)))
        raise gen.Return(addrinfo) 
Example #21
Source File: httpserver.py    From tornado-zh with MIT License 5 votes vote down vote up
def __str__(self):
        if self.address_family in (socket.AF_INET, socket.AF_INET6):
            return self.remote_ip
        elif isinstance(self.address, bytes):
            # Python 3 with the -bb option warns about str(bytes),
            # so convert it explicitly.
            # Unix socket addresses are str on mac but bytes on linux.
            return native_str(self.address)
        else:
            return str(self.address) 
Example #22
Source File: tcpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_connect_ipv4_ipv4(self):
        self.do_test_connect(socket.AF_INET, '127.0.0.1') 
Example #23
Source File: httpserver.py    From tornado-zh with MIT License 5 votes vote down vote up
def __str__(self):
        if self.address_family in (socket.AF_INET, socket.AF_INET6):
            return self.remote_ip
        elif isinstance(self.address, bytes):
            # Python 3 with the -bb option warns about str(bytes),
            # so convert it explicitly.
            # Unix socket addresses are str on mac but bytes on linux.
            return native_str(self.address)
        else:
            return str(self.address) 
Example #24
Source File: tcpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_connect_ipv4_dual(self):
        self.do_test_connect(socket.AF_INET, 'localhost') 
Example #25
Source File: caresresolver.py    From tornado-zh with MIT License 5 votes vote down vote up
def resolve(self, host, port, family=0):
        if is_valid_ip(host):
            addresses = [host]
        else:
            # gethostbyname doesn't take callback as a kwarg
            self.channel.gethostbyname(host, family, (yield gen.Callback(1)))
            callback_args = yield gen.Wait(1)
            assert isinstance(callback_args, gen.Arguments)
            assert not callback_args.kwargs
            result, error = callback_args.args
            if error:
                raise Exception('C-Ares returned error %s: %s while resolving %s' %
                                (error, pycares.errno.strerror(error), host))
            addresses = result.addresses
        addrinfo = []
        for address in addresses:
            if '.' in address:
                address_family = socket.AF_INET
            elif ':' in address:
                address_family = socket.AF_INET6
            else:
                address_family = socket.AF_UNSPEC
            if family != socket.AF_UNSPEC and family != address_family:
                raise Exception('Requested socket family %d but got %d' %
                                (family, address_family))
            addrinfo.append((address_family, (address, port)))
        raise gen.Return(addrinfo) 
Example #26
Source File: tcpclient_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_connect_ipv4_ipv4(self):
        self.do_test_connect(socket.AF_INET, '127.0.0.1') 
Example #27
Source File: netutil_test.py    From tornado-zh with MIT License 5 votes vote down vote up
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)


# It is impossible to quickly and consistently generate an error in name
# resolution, so test this case separately, using mocks as needed. 
Example #28
Source File: netutil_test.py    From tornado-zh with MIT License 5 votes vote down vote up
def test_localhost(self):
        self.resolver.resolve('localhost', 80, callback=self.stop)
        result = self.wait()
        self.assertIn((socket.AF_INET, ('127.0.0.1', 80)), result) 
Example #29
Source File: twisted.py    From tornado-zh with MIT License 5 votes vote down vote up
def resolve(self, host, port, family=0):
        # getHostByName doesn't accept IP addresses, so if the input
        # looks like an IP address just return it immediately.
        if twisted.internet.abstract.isIPAddress(host):
            resolved = host
            resolved_family = socket.AF_INET
        elif twisted.internet.abstract.isIPv6Address(host):
            resolved = host
            resolved_family = socket.AF_INET6
        else:
            deferred = self.resolver.getHostByName(utf8(host))
            resolved = yield gen.Task(deferred.addBoth)
            if isinstance(resolved, failure.Failure):
                resolved.raiseException()
            elif twisted.internet.abstract.isIPAddress(resolved):
                resolved_family = socket.AF_INET
            elif twisted.internet.abstract.isIPv6Address(resolved):
                resolved_family = socket.AF_INET6
            else:
                resolved_family = socket.AF_UNSPEC
        if family != socket.AF_UNSPEC and family != resolved_family:
            raise Exception('Requested socket family %d but got %d' %
                            (family, resolved_family))
        result = [
            (resolved_family, (resolved, port)),
        ]
        raise gen.Return(result) 
Example #30
Source File: testing.py    From tornado-zh with MIT License 5 votes vote down vote up
def bind_unused_port(reuse_port=False):
    """Binds a server socket to an available port on localhost.

    Returns a tuple (socket, port).
    """
    [sock] = netutil.bind_sockets(None, 'localhost', family=socket.AF_INET,
                                  reuse_port=reuse_port)
    port = sock.getsockname()[1]
    return sock, port