我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.AF_INET。
def __init__(self, addr, requestHandler=StratumJSONRPCRequestHandler, logRequests=False, encoding=None, bind_and_activate=True, address_family=socket.AF_INET): self.logRequests = logRequests StratumJSONRPCDispatcher.__init__(self, encoding) # TCPServer.__init__ has an extra parameter on 2.6+, so # check Python version and decide on how to call it vi = sys.version_info self.address_family = address_family if USE_UNIX_SOCKETS and address_family == socket.AF_UNIX: # Unix sockets can't be bound if they already exist in the # filesystem. The convention of e.g. X11 is to unlink # before binding again. if os.path.exists(addr): try: os.unlink(addr) except OSError: logging.warning("Could not unlink socket %s", addr) SocketServer.TCPServer.__init__(self, addr, requestHandler, bind_and_activate) if fcntl is not None and hasattr(fcntl, 'FD_CLOEXEC'): flags = fcntl.fcntl(self.fileno(), fcntl.F_GETFD) flags |= fcntl.FD_CLOEXEC fcntl.fcntl(self.fileno(), fcntl.F_SETFD, flags)
def _socketpair(): if hasattr(socket, 'socketpair'): return socket.socketpair() srv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv_sock.bind(('127.0.0.1', 0)) srv_sock.listen(1) write_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: write_sock.setblocking(False) try: write_sock.connect(srv_sock.getsockname()[:2]) except socket.error as e: if e.args[0] in (EINPROGRESS, EWOULDBLOCK): pass else: raise write_sock.setblocking(True) read_sock = srv_sock.accept()[0] except: write_sock.close() raise finally: srv_sock.close() return (read_sock, write_sock)
def Start(self, serverAddress, serverPort, bruteforce_file): """ serverHost = string: localhost/ip address/url for server serverPort = int: port number to connect for server bruteforce_file = string: name of the file that has password guesses """ serverSckt = socket(AF_INET, SOCK_STREAM) serverSckt.connect((serverAddress, serverPort)) print "Client: Connected to Server at %s:%d" \ % (serverAddress, serverPort) success, time_taken, attempts = self.Client(serverSckt, bruteforce_file) # used to close socket when client is done serverSckt.sendCloseSignal() if success: print "Success! Cracked the password and got in." else: print "Failure! Tried to get in but couldn't." print "Took %d guesses and %d seconds." \ % (attempts, time_taken.seconds) serverSckt.shutdown(1) # send close signal to server socket serverSckt.close() # close connection
def Start(self, serverAddress, serverPort, password_file): """ serverAddress = string: localhost/ip address/url serverPort = int: port number to run server password_file = string: file that contains username/password pairs """ serverSckt = socket(AF_INET, SOCK_STREAM) serverSckt.bind((serverAddress, serverPort)) serverSckt.listen(1) # await requests print "Server: Listening at %s:%d" % (serverAddress, serverPort) sckt, addr = serverSckt.accept() # accept a connection (blocking) self.Host(sckt, password_file) sckt.shutdown(1) # send close signal sckt.close() # close connection
def main(): application = get_application() port = get_port() if CONFIG.IPV4_ONLY: family = socket.AF_INET else: family = socket.AF_UNSPEC if CONFIG.DEBUG_MODE: address = None else: address = 'localhost' sockets = tornado.netutil.bind_sockets(port, address, family=family) server = HTTPServer(application, xheaders=CONFIG.XHEADERS) server.add_sockets(sockets) server.listen_exit_signal(CONFIG.MAX_WAIT_SECONDS_BEFORE_SHUTDOWN) tornado.ioloop.IOLoop.instance().start()
def __init__(self, address): self.log = logging.getLogger(self.server_logger) self.socket = None if ":" in address[0]: self.address_family = socket.AF_INET6 else: self.address_family = socket.AF_INET self.log.debug("Listening on %s", address) super(_SpoonMixIn, self).__init__(address, self.handler_klass, bind_and_activate=False) self.load_config() self._setup_socket() # Finally, set signals if self.signal_reload is not None: signal.signal(self.signal_reload, self.reload_handler) if self.signal_shutdown is not None: signal.signal(self.signal_shutdown, self.shutdown_handler)
def send(self,send_data): if self.__is_addr_reset or \ self._is_close_for_invoker or \ self.__is_connection_closed(): self.__connection = socket(AF_INET,SOCK_STREAM) if self.__is_ssl: self.__connection = ssl.wrap_socket(self.__connection) try : self.__connection.connect(self.__addr) self.__connection.settimeout(self.__timeout) self._is_close_for_invoker = False self.__is_addr_reset = False except Exception as exception: self.__recorder.write( 'Cannot connect %s' % str(self.__addr), Exception = str(exception)) return None self.__connection.send(send_data) return self
def __init__(self, localaddr, remoteaddr): self._localaddr = localaddr self._remoteaddr = remoteaddr asyncore.dispatcher.__init__(self) try: self.create_socket(socket.AF_INET, socket.SOCK_STREAM) # try to re-use a server port if possible self.set_reuse_addr() self.bind(localaddr) self.listen(5) except: # cleanup asyncore.socket_map before raising self.close() raise else: print >> DEBUGSTREAM, \ '%s started at %s\n\tLocal addr: %s\n\tRemote addr:%s' % ( self.__class__.__name__, time.ctime(time.time()), localaddr, remoteaddr)
def __init__(self, family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0, *args, **kwargs): if type not in (socket.SOCK_STREAM, socket.SOCK_DGRAM): msg = "Socket type must be stream or datagram, not {!r}" raise ValueError(msg.format(type)) super(socksocket, self).__init__(family, type, proto, *args, **kwargs) self._proxyconn = None # TCP connection to keep UDP relay alive if self.default_proxy: self.proxy = self.default_proxy else: self.proxy = (None, None, None, None, None, None) self.proxy_sockname = None self.proxy_peername = None self._timeout = None
def api_has_bwctl(host, timeout=5, bind=None): """ Determine if a host is running the BWCTL daemon """ # Null implies localhost if host is None: host = "localhost" # HACK: BWTCLBC # If the environment says to bind to a certain address, do it. if bind is None: bind = os.environ.get('PSCHEDULER_LEAD_BIND_HACK', None) for family in [socket.AF_INET, socket.AF_INET6]: try: with closing(socket.socket(family, socket.SOCK_STREAM)) as sock: if bind is not None: sock.bind((bind, 0)) sock.settimeout(timeout) return sock.connect_ex((host, 4823)) == 0 except socket.error: pass return False
def source_interface(address, port=80, ip_version=None): """Figure out what local interface is being used to reach an address. Returns a tuple of (address, interface_name) """ sock = socket.socket( socket.AF_INET6 if ip_version == 6 else socket.AF_INET, socket.SOCK_DGRAM) try: sock.connect((address, port)) except socket.error: return (None, None) interface_address = sock.getsockname()[0] sock.close() interface_name = address_interface(interface_address, ip_version=ip_version) if interface_name: return (interface_address, interface_name) return (None, None)
def inet_pton(address_family, ip_string): if address_family == socket.AF_INET: return socket.inet_aton(ip_string) addr = sockaddr() addr.sa_family = address_family addr_size = ctypes.c_int(ctypes.sizeof(addr)) if WSAStringToAddressA( ip_string, address_family, None, ctypes.byref(addr), ctypes.byref(addr_size) ) != 0: raise socket.error(ctypes.FormatError()) if address_family == socket.AF_INET6: return ctypes.string_at(addr.ipv6_addr, 16) raise socket.error('unknown address family')
def _socket_bind_addr(self, sock, af): bind_addr = '' if self._bind and af == socket.AF_INET: bind_addr = self._bind elif self._bindv6 and af == socket.AF_INET6: bind_addr = self._bindv6 else: bind_addr = self._accept_address[0] bind_addr = bind_addr.replace("::ffff:", "") if bind_addr in self._ignore_bind_list: bind_addr = None if bind_addr: local_addrs = socket.getaddrinfo(bind_addr, 0, 0, socket.SOCK_STREAM, socket.SOL_TCP) if local_addrs[0][0] == af: logging.debug("bind %s" % (bind_addr,)) try: sock.bind((bind_addr, 0)) except Exception as e: logging.warn("bind %s fail" % (bind_addr,))
def handle_event(self, sock, fd, event): if sock != self._sock: return if event & eventloop.POLL_ERR: logging.error('dns socket err') self._loop.remove(self._sock) self._sock.close() # TODO when dns server is IPv6 self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.SOL_UDP) self._sock.setblocking(False) self._loop.add(self._sock, eventloop.POLL_IN, self) else: data, addr = sock.recvfrom(1024) if addr not in self._servers: logging.warn('received a packet other than our dns') return self._handle_data(data)
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
def postprocess(self, name, val): if name == 'GetSettings': if 'ssid' in val.get('802-11-wireless', {}): val['802-11-wireless']['ssid'] = fixups.ssid_to_python(val['802-11-wireless']['ssid']) for key in val: val_ = val[key] if 'mac-address' in val_: val_['mac-address'] = fixups.mac_to_python(val_['mac-address']) if 'cloned-mac-address' in val_: val_['cloned-mac-address'] = fixups.mac_to_python(val_['cloned-mac-address']) if 'bssid' in val_: val_['bssid'] = fixups.mac_to_python(val_['bssid']) if 'ipv4' in val: val['ipv4']['addresses'] = [fixups.addrconf_to_python(addr, socket.AF_INET) for addr in val['ipv4']['addresses']] val['ipv4']['routes'] = [fixups.route_to_python(route, socket.AF_INET) for route in val['ipv4']['routes']] val['ipv4']['dns'] = [fixups.addr_to_python(addr, socket.AF_INET) for addr in val['ipv4']['dns']] if 'ipv6' in val: val['ipv6']['addresses'] = [fixups.addrconf_to_python(addr, socket.AF_INET6) for addr in val['ipv6']['addresses']] val['ipv6']['routes'] = [fixups.route_to_python(route, socket.AF_INET6) for route in val['ipv6']['routes']] val['ipv6']['dns'] = [fixups.addr_to_python(addr, socket.AF_INET6) for addr in val['ipv6']['dns']] return val
def request(self, check_config): domain = check_config.get('domain') if check_config.get('ip_version') == 6: af = socket.AF_INET6 elif check_config.get('ip_version') == 4: af = socket.AF_INET else: af = 0 try: result = socket.getaddrinfo(domain, 0, af) except Exception as e: return Plugin.STATUS_CRIT, '{}'.format(e) ips = [ip[4][0] for ip in result] return ( Plugin.STATUS_OK, 'Domain was resolved with {}'.format(', '.join(ips)) )
def bind(self, addr, port, tos, ttl, df): log.debug( "bind(addr=%s, port=%d, tos=%d, ttl=%d)", addr, port, tos, ttl) self.socket = socket.socket( socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP) self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_TOS, tos) self.socket.setsockopt(socket.SOL_IP, socket.IP_TTL, ttl) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind((addr, port)) if df: if (sys.platform == "linux2"): self.socket.setsockopt(socket.SOL_IP, 10, 2) elif (sys.platform == "win32"): self.socket.setsockopt(socket.SOL_IP, 14, 1) elif (sys.platform == "darwin"): log.error("do-not-fragment can not be set on darwin") else: log.error("unsupported OS, ignore do-not-fragment option") else: if (sys.platform == "linux2"): self.socket.setsockopt(socket.SOL_IP, 10, 0)
def _resolve_one(self, ip): """ overloaded version to provide a Whois resolution on the embedded IPv4 address if the address is 6to4 or Teredo. Otherwise, the native IPv6 address is passed. """ if in6_isaddr6to4(ip): # for 6to4, use embedded @ tmp = inet_pton(socket.AF_INET6, ip) addr = inet_ntop(socket.AF_INET, tmp[2:6]) elif in6_isaddrTeredo(ip): # for Teredo, use mapped address addr = teredoAddrExtractInfo(ip)[2] else: addr = ip _, asn, desc = AS_resolver_riswhois._resolve_one(self, addr) return ip,asn,desc
def inet_pton(family, text): """Convert the textual form of a network address into its binary form. @param family: the address family @type family: int @param text: the textual address @type text: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ if family == AF_INET: return dns.ipv4.inet_aton(text) elif family == AF_INET6: return dns.ipv6.inet_aton(text) else: raise NotImplementedError
def inet_ntop(family, address): """Convert the binary form of a network address into its textual form. @param family: the address family @type family: int @param address: the binary address @type address: string @raises NotImplementedError: the address family specified is not implemented. @rtype: string """ if family == AF_INET: return dns.ipv4.inet_ntoa(address) elif family == AF_INET6: return dns.ipv6.inet_ntoa(address) else: raise NotImplementedError
def af_for_address(text): """Determine the address family of a textual-form network address. @param text: the textual address @type text: string @raises ValueError: the address family cannot be determined from the input. @rtype: int """ try: dns.ipv4.inet_aton(text) return AF_INET except: try: dns.ipv6.inet_aton(text) return AF_INET6 except: raise ValueError
def _gethostbyaddr(ip): try: dns.ipv6.inet_aton(ip) sockaddr = (ip, 80, 0, 0) family = socket.AF_INET6 except: sockaddr = (ip, 80) family = socket.AF_INET (name, port) = _getnameinfo(sockaddr, socket.NI_NAMEREQD) aliases = [] addresses = [] tuples = _getaddrinfo(name, 0, family, socket.SOCK_STREAM, socket.SOL_TCP, socket.AI_CANONNAME) canonical = tuples[0][3] for item in tuples: addresses.append(item[4][0]) # XXX we just ignore aliases return (canonical, aliases, addresses)
def testNToP(self): from twisted.python.compat import inet_ntop f = lambda a: inet_ntop(socket.AF_INET6, a) g = lambda a: inet_ntop(socket.AF_INET, a) self.assertEquals('::', f('\x00' * 16)) self.assertEquals('::1', f('\x00' * 15 + '\x01')) self.assertEquals( 'aef:b01:506:1001:ffff:9997:55:170', f('\x0a\xef\x0b\x01\x05\x06\x10\x01\xff\xff\x99\x97\x00\x55\x01\x70')) self.assertEquals('1.0.1.0', g('\x01\x00\x01\x00')) self.assertEquals('170.85.170.85', g('\xaa\x55\xaa\x55')) self.assertEquals('255.255.255.255', g('\xff\xff\xff\xff')) self.assertEquals('100::', f('\x01' + '\x00' * 15)) self.assertEquals('100::1', f('\x01' + '\x00' * 14 + '\x01'))
def m2i(self, pkt, s): family = None if pkt.type == 1: # A family = socket.AF_INET elif pkt.type == 12: # PTR s = DNSgetstr(s, 0)[0] elif pkt.type == 16: # TXT ret_s = "" tmp_s = s # RDATA contains a list of strings, each are prepended with # a byte containing the size of the following string. while tmp_s: tmp_len = struct.unpack("!B", tmp_s[0])[0] + 1 if tmp_len > len(tmp_s): warning("DNS RR TXT prematured end of character-string (size=%i, remaining bytes=%i)" % (tmp_len, len(tmp_s))) ret_s += tmp_s[1:tmp_len] tmp_s = tmp_s[tmp_len:] s = ret_s elif pkt.type == 28: # AAAA family = socket.AF_INET6 if family is not None: s = inet_ntop(family, s) return s
def h2i(self, pkt, x): if x is tuple and type(x[0]) is int: return x val = None try: # Try IPv6 inet_pton(socket.AF_INET6, x) val = (0, x) except: try: # Try IPv4 inet_pton(socket.AF_INET, x) val = (2, x) except: # Try DNS if x is None: x = "" x = names2dnsrepr(x) val = (1, x) return val
def af_for_address(text): """Determine the address family of a textual-form network address. @param text: the textual address @type text: string @raises ValueError: the address family cannot be determined from the input. @rtype: int """ try: junk = dns.ipv4.inet_aton(text) return AF_INET except: try: junk = dns.ipv6.inet_aton(text) return AF_INET6 except: raise ValueError
def discover_peers(self, port=None): """This method can be invoked (periodically?) to broadcast message to discover peers, if there is a chance initial broadcast message may be lost (as these messages are sent over UDP). """ ping_msg = {'signature': self._signature, 'name': self._name, 'version': __version__} def _discover(addrinfo, port, task=None): ping_sock = AsyncSocket(socket.socket(addrinfo.family, socket.SOCK_DGRAM)) ping_sock.settimeout(2) if addrinfo.family == socket.AF_INET: ping_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) else: # addrinfo.family == socket.AF_INET6 ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_HOPS, struct.pack('@i', 1)) ping_sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_MULTICAST_IF, addrinfo.ifn) ping_sock.bind((addrinfo.ip, 0)) if not port: port = addrinfo.udp_sock.getsockname()[1] ping_msg['location'] = addrinfo.location try: yield ping_sock.sendto('ping:'.encode() + serialize(ping_msg), (addrinfo.broadcast, port)) except: pass ping_sock.close() for addrinfo in self._addrinfos: SysTask(_discover, addrinfo, port)
def _ensureConnected(self, address): """Make sure client has a socket connected to address""" if not self.socket: if len(address) == 4: address_family = socket.AF_INET6 else: address_family = socket.AF_INET self._setSocket(socket.socket(address_family, socket.SOCK_DGRAM)) self.socket.connect(address)
def __init__(self): self._txMutex = threading.Lock() OSCAddressSpace.__init__(self) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, self.sndbuf_size) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, self.rcvbuf_size) self.socket.settimeout(1.0) self._running = False
def allowed_gai_family(): """This function is designed to work in the context of getaddrinfo, where family=socket.AF_UNSPEC is the default and will perform a DNS search for both IPv6 and IPv4 records.""" family = socket.AF_INET if HAS_IPV6: family = socket.AF_UNSPEC return family
def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) try: #self.set_reuse_addr() self.bind((host, port)) self.listen(socket.SOMAXCONN) self.ipaddr, self.port = self.getsockname() self.current_client_id = 0 except: PrintMessage("Unable to listen on {0}:{1}. Is the port already in use?".format(host, port)) exit(1)
def run(self, app): # pragma: no cover from wsgiref.simple_server import make_server from wsgiref.simple_server import WSGIRequestHandler, WSGIServer import socket class FixedHandler(WSGIRequestHandler): def address_string(self): # Prevent reverse DNS lookups please. return self.client_address[0] def log_request(*args, **kw): if not self.quiet: return WSGIRequestHandler.log_request(*args, **kw) handler_cls = self.options.get('handler_class', FixedHandler) server_cls = self.options.get('server_class', WSGIServer) if ':' in self.host: # Fix wsgiref for IPv6 addresses. if getattr(server_cls, 'address_family') == socket.AF_INET: class server_cls(server_cls): address_family = socket.AF_INET6 self.srv = make_server(self.host, self.port, app, server_cls, handler_cls) self.port = self.srv.server_port # update port actual port (0 means random) try: self.srv.serve_forever() except KeyboardInterrupt: self.srv.server_close() # Prevent ResourceWarning: unclosed socket raise
def _recreate_socket(self): if self._proxy is None: self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) else: import socks self._socket = socks.socksocket(socket.AF_INET, socket.SOCK_STREAM) if type(self._proxy) is dict: self._socket.set_proxy(**self._proxy) else: # tuple, list, etc. self._socket.set_proxy(*self._proxy)
def sendeprt(self, host, port): '''Send a EPRT command with the current host and the given port number.''' af = 0 if self.af == socket.AF_INET: af = 1 if self.af == socket.AF_INET6: af = 2 if af == 0: raise error_proto, 'unsupported address family' fields = ['', repr(af), host, repr(port), ''] cmd = 'EPRT ' + '|'.join(fields) return self.voidcmd(cmd)
def makeport(self): '''Create a new socket and send a PORT command for it.''' msg = "getaddrinfo returns an empty list" sock = None for res in socket.getaddrinfo(None, 0, self.af, socket.SOCK_STREAM, 0, socket.AI_PASSIVE): af, socktype, proto, canonname, sa = res try: sock = socket.socket(af, socktype, proto) sock.bind(sa) except socket.error, msg: if sock: sock.close() sock = None continue break if not sock: raise socket.error, msg sock.listen(1) port = sock.getsockname()[1] # Get proper port host = self.sock.getsockname()[0] # Get proper host if self.af == socket.AF_INET: resp = self.sendport(host, port) else: resp = self.sendeprt(host, port) if self.timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(self.timeout) return sock
def makepasv(self): if self.af == socket.AF_INET: host, port = parse227(self.sendcmd('PASV')) else: host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername()) return host, port
def _write_SOCKS5_address(self, addr, file): """ Return the host and port packed for the SOCKS5 protocol, and the resolved address as a tuple object. """ host, port = addr proxy_type, _, _, rdns, username, password = self.proxy family_to_byte = {socket.AF_INET: b"\x01", socket.AF_INET6: b"\x04"} # If the given destination address is an IP address, we'll # use the IP address request even if remote resolving was specified. # Detect whether the address is IPv4/6 directly. for family in (socket.AF_INET, socket.AF_INET6): try: addr_bytes = socket.inet_pton(family, host) file.write(family_to_byte[family] + addr_bytes) host = socket.inet_ntop(family, addr_bytes) file.write(struct.pack(">H", port)) return host, port except socket.error: continue # Well it's not an IP number, so it's probably a DNS name. if rdns: # Resolve remotely host_bytes = host.encode("idna") file.write(b"\x03" + chr(len(host_bytes)).encode() + host_bytes) else: # Resolve locally addresses = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG) # We can't really work out what IP is reachable, so just pick the # first. target_addr = addresses[0] family = target_addr[0] host = target_addr[4][0] addr_bytes = socket.inet_pton(family, host) file.write(family_to_byte[family] + addr_bytes) host = socket.inet_ntop(family, addr_bytes) file.write(struct.pack(">H", port)) return host, port