我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用socket.SOL_TCP。
def handle(self): client_ip = self.client_address[0] addr = '' server = '' try: sock = self.connection sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) odestdata = sock.getsockopt(socket.SOL_IP, 80, 16) port, addr_ip = struct.unpack("!xxH4sxxxxxxxx", odestdata) addr = socket.inet_ntoa(addr_ip) server = reverse(addr) print_log('%s connecting %s:%d %d %s' % (client_ip, addr, port, server[0], str(server[1]))) Proxy[server[0]].proxy(sock, server[1], (addr, port)) except socket.error, e: logging.warn(addr + ':' + str(server) + ':' + str(e)) sock.close()
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 _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 _gethostbyaddr(ip): try: addr = 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 _create_remote_socket(self, ip, port): addrs = socket.getaddrinfo(ip, port, 0, socket.SOCK_STREAM, socket.SOL_TCP) if len(addrs) == 0: raise Exception("getaddrinfo failed for %s:%d" % (ip, port)) af, socktype, proto, canonname, sa = addrs[0] if self._forbidden_iplist: if common.to_str(sa[0]) in self._forbidden_iplist: raise Exception('IP %s is in forbidden list, reject' % common.to_str(sa[0])) remote_sock = socket.socket(af, socktype, proto) self._remote_sock = remote_sock self._fd_to_handlers[remote_sock.fileno()] = self remote_sock.setblocking(False) remote_sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) return remote_sock
def _convert_host_to_ip(host): """ Perform forward DNS resolution on host, IP will give the same IP Args: host: String with either hostname, IPv4, or IPv6 address Returns: List of tuples containing address family and IP """ addrinfo = socket.getaddrinfo(host, 80, 0, 0, socket.SOL_TCP) ips = [] for family, socktype, proto, canonname, sockaddr in addrinfo: ip = sockaddr[0] ips.append((family, ip)) if family == socket.AF_INET: ips.append((socket.AF_INET6, "::ffff:" + ip)) return ips
def modify_buff_size(): sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM ) # Get the size of the socket's send buffer bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) print ("Buffer size [Before]:%d" %bufsize) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) sock.setsockopt( socket.SOL_SOCKET, socket.SO_SNDBUF, SEND_BUF_SIZE) sock.setsockopt( socket.SOL_SOCKET, socket.SO_RCVBUF, RECV_BUF_SIZE) bufsize = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF) print ("Buffer size [After]:%d" %bufsize)
def __init__(self, ip, port, callbacks_info, max_client = 50): assert (ip != '') skt = socket.socket() # Avoid 'Address already in use' error when trying to lanch server # again right after shutting it down. skt.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) skt.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) if sys.platform == 'linux': skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60) skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPCNT, 4) skt.setsockopt(socket.SOL_TCP, socket.TCP_KEEPINTVL, 15) skt.bind((ip, port)) skt.listen(max_client) self.connections = [] self.clients = {} self.msg_handler = MessageHandler(skt, callbacks_info, mh_creator = self.client_mh_creator, mh_remover = self.client_mh_remover) self.thread = TaskThread(name='server_recv_loop') self.thread.daemon = True self.evt_break = threading.Event() self.evt_break.clear()
def open_socket(self): if self.useInetSocket: this_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM, socket.SOL_TCP) else: this_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) if this_socket: try: if self.useInetSocket: this_socket.connect((self.socketHost, self.socketPort)) else: this_socket.connect(self.socket_name) except: this_socket.close() return this_socket
def _gethostbyaddr(ip): try: dns.ipv6.inet_aton(ip) sockaddr = (ip, 80, 0, 0) family = socket.AF_INET6 except Exception: 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 open(self, session_id): # Stats self.server.stats.on_conn_opened() # Disable nagle if self.server.settings['disable_nagle']: self.stream.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) # Handle session self.session = self.server.create_session(session_id, register=False) if not self.session.set_handler(self): self.close() return self.session.verify_state() if self.session: self.session.flush()
def _gethostbyaddr(ip): try: addr = 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 connect(self): if not self._stream: try: if self.unix_socket_path: sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.settimeout(self.timeout) sock.connect(self.unix_socket_path) else: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0) sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) sock.settimeout(self.timeout) sock.connect((self.host, self.port)) self._stream = IOStream(sock, io_loop=self._io_loop) self._stream.set_close_callback(self.on_stream_close) self.info['db'] = 0 self.info['pass'] = None except socket.error as e: raise ConnectionError(str(e)) self.fire_event('on_connect')
def bind_and_activate(self): server_listen_ip = self.orig_server_address[0] try: #???? IPv6 sock = socket.socket(socket.AF_INET6) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # server_address ??????? v6 ? v4 ???'::' ????????? if server_listen_ip == '': sock.setsockopt(IPPROTO_IPV6, socket.IPV6_V6ONLY, 0) sock.bind(self.orig_server_address) except: sock.close() sock = socket.socket(socket.AF_INET) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind(self.orig_server_address) #???????????? if sys.platform != 'darwin' and server_listen_ip in ('127.0.0.1', '::1'): sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0) #?? nagle's algorithm ?? sock.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, True) self.socket = sock self.server_address = sock.getsockname() sock.listen(self.request_queue_size) self.is_not_online = False
def get_ip_address(host='', ipv6=False): """Get IP address associated with the given host name. This could be run as an instance or class method. """ if len(host) != 0: ipstr = "v6" if ipv6 else "v4" family = socket.AF_INET6 if ipv6 else socket.AF_INET try: infolist = socket.getaddrinfo(host, 2049, 0, 0, socket.SOL_TCP) except Exception: infolist = [] for info in infolist: # Ignore loopback addresses if info[0] == family and info[4][0] not in ('127.0.0.1', '::1'): return info[4][0] raise Exception("Unable to get IP%s address for host '%s'" % (ipstr, host)) else: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) if ipv6: s.connect(("2001:4860:4860::8888", 53)) else: s.connect(("8.8.8.8", 53)) ip = s.getsockname()[0] s.close() return ip
def _connect(self): "Create a TCP socket connection" # we want to mimic what socket.create_connection does to support # ipv4/ipv6, but we want to set options prior to calling # socket.connect() err = None for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): family, socktype, proto, canonname, socket_address = res sock = None try: sock = socket.socket(family, socktype, proto) # TCP_NODELAY sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # TCP_KEEPALIVE if self.socket_keepalive: sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1) for k, v in iteritems(self.socket_keepalive_options): sock.setsockopt(socket.SOL_TCP, k, v) # set the socket_connect_timeout before we connect sock.settimeout(self.socket_connect_timeout) # connect sock.connect(socket_address) # set the socket_timeout now that we're connected sock.settimeout(self.socket_timeout) return sock except socket.error as _: err = _ if sock is not None: sock.close() if err is not None: raise err raise socket.error("socket.getaddrinfo returned an empty list")
def proxy(sock, server, addr): if addr[1] == 80: redirect_https(sock) return remote = socket.create_connection((server[0], addr[1])) remote.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) try: fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break result = send_all(remote, data) if result < len(data): raise Exception('failed to send all data') if remote in r: data = remote.recv(4096) if len(data) <= 0: break result = send_all(sock, data) if result < len(data): raise Exception('failed to send all data') finally: sock.close() remote.close()
def proxy(sock, server, addr): remote = socket.create_connection(addr) remote.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) try: fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break result = send_all(remote, data) if result < len(data): raise Exception('failed to send all data') if remote in r: data = remote.recv(4096) if len(data) <= 0: break result = send_all(sock, data) if result < len(data): raise Exception('failed to send all data') finally: sock.close() remote.close()
def proxy(sock, server, addr): if isinstance(server, list): server = (server[random.randint(0, len(server)-1)], addr[1]) elif isinstance(server, str): server = (server, addr[1]) remote = socket.create_connection(server) remote.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1) try: fdset = [sock, remote] while True: r, w, e = select.select(fdset, [], []) if sock in r: data = sock.recv(4096) if len(data) <= 0: break result = send_all(remote, data) if result < len(data): raise Exception('failed to send all data') if remote in r: data = remote.recv(4096) if len(data) <= 0: break result = send_all(sock, data) if result < len(data): raise Exception('failed to send all data') finally: sock.close() remote.close()
def _update_tcp_mss(self, local_sock): self._tcp_mss = TCP_MSS try: tcp_mss = local_sock.getsockopt(socket.SOL_TCP, socket.TCP_MAXSEG) if tcp_mss > 500 and tcp_mss <= 1500: self._tcp_mss = tcp_mss logging.debug("TCP MSS = %d" % (self._tcp_mss,)) except: pass