Python socket.AF_INET6 Examples
The following are 30
code examples of socket.AF_INET6().
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: serving.py From recruit with Apache License 2.0 | 7 votes |
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 #2
Source File: simple_httpclient_test.py From tornado-zh with MIT License | 7 votes |
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 #3
Source File: simple_httpclient_test.py From tornado-zh with MIT License | 7 votes |
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 #4
Source File: nameserver.py From Pyro5 with MIT License | 6 votes |
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 #5
Source File: Udp_server.py From rtp_cluster with BSD 2-Clause "Simplified" License | 6 votes |
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 #6
Source File: tcpip_vtypes.py From rekall with GNU General Public License v2.0 | 6 votes |
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 #7
Source File: kernel.py From rift-python with Apache License 2.0 | 6 votes |
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: interface.py From rift-python with Apache License 2.0 | 6 votes |
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 #9
Source File: Udp_server.py From rtp_cluster with BSD 2-Clause "Simplified" License | 6 votes |
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 #10
Source File: server.py From sanic with MIT License | 6 votes |
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 #11
Source File: ssl_.py From gist-alfred with MIT License | 6 votes |
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 #12
Source File: dnschef.py From break-fast-serial with MIT License | 6 votes |
def __init__(self, server_address, RequestHandlerClass, nametodns, nameservers, ipv6, log): self.nametodns = nametodns self.nameservers = nameservers self.ipv6 = ipv6 self.address_family = socket.AF_INET6 if self.ipv6 else socket.AF_INET self.log = log SocketServer.TCPServer.__init__(self,server_address,RequestHandlerClass) # Initialize and start the DNS Server
Example #13
Source File: nfq.py From dionaea with GNU General Public License v2.0 | 6 votes |
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 #14
Source File: interface.py From rift-python with Apache License 2.0 | 6 votes |
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 #15
Source File: httpserver.py From tornado-zh with MIT License | 6 votes |
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 #16
Source File: tcpip_vtypes.py From rekall with GNU General Public License v2.0 | 6 votes |
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 #17
Source File: tcpserver.py From tornado-zh with MIT License | 6 votes |
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 #18
Source File: httpserver.py From tornado-zh with MIT License | 6 votes |
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 #19
Source File: serving.py From jbox with MIT License | 6 votes |
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 #20
Source File: tcpserver.py From tornado-zh with MIT License | 6 votes |
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 #21
Source File: server.py From calibre-web with GNU General Public License v3.0 | 6 votes |
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 #22
Source File: ipip.py From scripts with MIT License | 6 votes |
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 #23
Source File: test_socketutil.py From Pyro5 with MIT License | 6 votes |
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 #24
Source File: socketutil.py From Pyro5 with MIT License | 6 votes |
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 #25
Source File: utils.py From ivre with GNU General Public License v3.0 | 6 votes |
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 #26
Source File: client_cdm_profile.py From codimension with GNU General Public License v3.0 | 5 votes |
def resolveHost(host): """Resolves a hostname to an IP address""" try: host, _ = host.split("@@") family = socket.AF_INET6 except ValueError: # version = 'v4' family = socket.AF_INET return socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)[0][4][0]
Example #27
Source File: clientbase_cdm_dbg.py From codimension with GNU General Public License v3.0 | 5 votes |
def resolveHost(host): """Resolves a hostname to an IP address""" try: host, _ = host.split("@@") family = socket.AF_INET6 except ValueError: # version = 'v4' family = socket.AF_INET return socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)[0][4][0]
Example #28
Source File: client_cdm_run.py From codimension with GNU General Public License v3.0 | 5 votes |
def resolveHost(host): """Resolves a hostname to an IP address""" try: host, _ = host.split("@@") family = socket.AF_INET6 except ValueError: # version = 'v4' family = socket.AF_INET return socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)[0][4][0]
Example #29
Source File: test_socketutil.py From Pyro5 with MIT License | 5 votes |
def testCreateBoundSockets6(self): if not has_ipv6: pytest.skip("no ipv6 capability") s = socketutil.create_socket(bind=('::1', 0)) assert socket.AF_INET6 == s.family bs = socketutil.create_bc_socket(bind=('::1', 0)) assert ':' in s.getsockname()[0] assert ':' in bs.getsockname()[0] s.close() bs.close() with pytest.raises(ValueError): socketutil.create_socket(bind=('::1', 12345), connect=('::1', 1234))
Example #30
Source File: test_socketutil.py From Pyro5 with MIT License | 5 votes |
def testBindUnusedPort6(self): if not has_ipv6: pytest.skip("no ipv6 capability") sock1 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) sock2 = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) port1 = socketutil.bind_unused_port(sock1) port2 = socketutil.bind_unused_port(sock2) assert port1 > 0 assert port1 != port2 host, port, _, _ = sock1.getsockname() assert ":" in host assert port1 == port sock1.close() sock2.close()