华强北电脑城 龙岗电子世界 龙华电脑城  凯尔电脑

 找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1142|回复: 0

到底一台服务器上最多能创建多少个TCP连接

[复制链接]
发表于 2022-12-2 14:38:10 | 显示全部楼层 |阅读模式
到底一台服务器上最多能创建多少个TCP连接
经常听到有同学说一台机器最多能创建65535个TCP连接,这其实是错误的理解,为什么会有这个错误的理解呢?
port range
我们都知道linux下本地随机端口范围由参数控制,也就是listen、connect时候如果没有指定本地端口,那么就从下面的port range中随机取一个可用的
1
5 H* N, h4 Q# V4 G" l. z# R2 I2
; D& u# Y% l7 G
# cat /proc/sys/net/ipv4/ip_local_port_range & Q4 ^1 [7 e  s
2000        655352 k4 U& Z0 V  z( Q& O# u) O- D
port range的上限是65535,所以也经常看到这个误解:一台机器上最多能创建65535个TCP连接
到底一台机器上最多能创建多少个TCP连接
先说结论:在内存、文件句柄足够的话可以创建的连接是没有限制的(每个TCP连接至少要消耗一个文件句柄)。
那么/proc/sys/net/ipv4/ip_local_port_range指定的端口范围到底是什么意思呢?
核心规则:一个TCP连接只要保证四元组(src-ip src-port dest-ip dest-port)唯一就可以了,而不是要求src port唯一
后面所讲都遵循这个规则,所以在心里反复默念:四元组唯一 五个大字,就能分析出来到底能创建多少TCP连接了。
比如如下这个机器上的TCP连接实际状态:
1
1 v6 R* }. b5 Q" C7 n' E, s2 `2, @' w* [& A& o
3
3 o2 R& R4 K0 D- D# O( c4
9 \3 x+ E4 A+ c% W' \: t0 C  R# P5 B5! P/ d: O) L( Q+ l  r. n7 N0 g/ V
66 y* M8 k+ i2 @4 G/ P, x
# netstat -ant |grep 180897 x$ x) c8 ~$ U1 S/ o
tcp        0      0 192.168.1.79:18089      192.168.1.79:22         ESTABLISHED$ a9 `$ }( e% r5 X/ y- J
tcp        0      0 192.168.1.79:18089      192.168.1.79:18080      ESTABLISHED0 P- O$ M. x: R- v
tcp        0      0 192.168.0.79:18089      192.168.0.79:22         TIME_WAIT
5 D$ N8 g: ~: J' C" K) ytcp        0      0 192.168.1.79:22         192.168.1.79:18089      ESTABLISHED
; W4 @! x8 F- A: r# S0 C3 ftcp        0      0 192.168.1.79:18080      192.168.1.79:18089      ESTABLISHED
& ]0 A  K: j+ G% `3 t
从前三行可以清楚地看到18089被用了三次,第一第二行src-ip、dest-ip也是重复的,但是dest port不一样,第三行的src-port还是18089,但是src-ip变了。他们的四元组均不相同。
所以一台机器能创建的TCP连接是没有限制的,而ip_local_port_range是指没有bind的时候OS随机分配端口的范围,但是分配到的端口要同时满足五元组唯一,这样 ip_local_port_range 限制的是连同一个目标(dest-ip和dest-port一样)的port的数量(请忽略本地多网卡的情况,因为dest-ip为以后route只会选用一个本地ip)。
那么为什么大家有这样的误解呢?我总结了下,大概是以下两个原因让大家误解了:
  • 如果是listen服务,那么肯定端口不能重复使用,这样就跟我们的误解对应上了,一个服务器上最多能监听65535个端口。比如nginx监听了80端口,那么tomcat就没法再监听80端口了,这里的80端口只能监听一次(如果有个连接用了80连别人,这里80还是不能被listen……想想)。
  • 另外如果我们要连的server只有一个,比如:1.1.1.1:80 ,同时本机只有一个ip的话,那么这个时候即使直接调connect 也只能创建出65535个连接,因为四元组中的三个是固定的了。0 k' l4 E+ s  o0 w2 @7 w+ |# n* B
我们在创建连接前,经常会先调bind,bind后可以调listen当做服务端监听,也可以直接调connect当做client来连服务端。
bind(ip,port=0) 的时候是让系统绑定到某个网卡和自动分配的端口,此时系统没有办法确定接下来这个socket是要去connect还是listen. 如果是listen的话,那么肯定是不能出现端口冲突的,如果是connect的话,只要满足4元组唯一即可。在这种情况下,系统只能尽可能满足更强的要求,就是先要求端口不能冲突,即使之后去connect的时候四元组是唯一的。
但如果我只是个client端,只需要连接server建立连接,也就不需要bind,直接调connect就可以了,这个时候只要保证四元组唯一就行。
bind()的时候内核是还不知道四元组的,只知道src_ip、src_port,所以这个时候单网卡下src_port是没法重复的,但是connect()的时候已经知道了四元组的全部信息,所以只要保证四元组唯一就可以了,那么这里的src_port完全是可以重复使用的。
是不是加上了 SO_REUSEADDR、SO_REUSEPORT 就能重用端口了呢?
TCP SO_REUSEADDR
文档描述:
SO_REUSEADDR Indicates that the rules used in validating addresses supplied in a bind(2) call should allow reuse of local addresses. For AF_INET sockets this means that a socket may bind, except when there is an active listening socket bound to the address. When the listening socket is bound to INADDR_ANY with a specific port then it is not possible to bind to this port for any local address. Argument is an integer boolean flag.
从这段文档中我们可以知道三个事:
  • 使用这个参数后,bind操作是可以重复使用local address的,注意,这里说的是local address,即ip加端口组成的本地地址,也就是两个本地地址,如果有任意ip或端口部分不一样,它们本身就是可以共存的,不需要使用这个参数。
  • 当local address被一个处于listen状态的socket使用时,加上该参数也不能重用这个地址。
  • 当处于listen状态的socket监听的本地地址的ip部分是INADDR_ANY,即表示监听本地的所有ip,即使使用这个参数,也不能再bind包含这个端口的任意本地地址,这个和 2 中描述的其实是一样的。- `  ^9 z, u# ]3 }2 K* O) c
==SO_REUSEADDR 可以用本地相同的(sip, sport) 去连connect 远程的不同的(dip、dport)//而 SO_REUSEPORT主要是解决Server端的port重用==
SO_REUSEADDR 还可以重用TIME_WAIT状态的port, 在程序崩溃后之前的TCP连接会进入到TIME_WAIT状态,需要一段时间才能释放,如果立即重启就会抛出Address Already in use的错误导致启动失败。这时候可以通过在调用bind函数之前设置SO_REUSEADDR来解决。
What exactly does SO_REUSEADDR do?
This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.
It has been pointed out that “A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!” This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port.
By setting SO_REUSEADDR user informs the kernel of an intention to share the bound port with anyone else, but only if it doesn’t cause a conflict on the protocol layer. There are at least three situations when this flag is useful:
  • Normally after binding to a port and stopping a server it’s neccesary to wait for a socket to time out before another server can bind to the same port. With SO_REUSEADDR set it’s possible to rebind immediately, even if the socket is in a TIME_WAIT state.
  • When one server binds to INADDR_ANY, say 0.0.0.0:1234, it’s impossible to have another server binding to a specific address like 192.168.1.21:1234. With SO_REUSEADDR flag this behaviour is allowed.
  • When using the bind before connect trick only a single connection can use a single outgoing source port. With this flag, it’s possible for many connections to reuse the same source port, given that they connect to different destination addresses.
    / r9 ^" z9 n3 L8 {
TCP SO_REUSEPORT
SO_REUSEPORT主要用来解决惊群、性能等问题。通过多个进程、线程来监听同一端口,进来的连接通过内核来hash分发做到负载均衡,避免惊群。
SO_REUSEPORT is also useful for eliminating the try-10-times-to-bind hack in ftpd’s data connection setup routine. Without SO_REUSEPORT, only one ftpd thread can bind to TCP (lhost, lport, INADDR_ANY, 0) in preparation for connecting back to the client. Under conditions of heavy load, there are more threads colliding here than the try-10-times hack can accomodate. With SO_REUSEPORT, things work nicely and the hack becomes unnecessary.
SO_REUSEPORT使用场景:linux kernel 3.9 引入了最新的SO_REUSEPORT选项,使得多进程或者多线程创建多个绑定同一个ip:port的监听socket,提高服务器的接收链接的并发能力,程序的扩展性更好;此时需要设置SO_REUSEPORT(注意所有进程都要设置才生效)。
setsockopt(listenfd, SOL_SOCKET, SO_REUSEPORT,(const void *)&reuse , sizeof(int));
目的:每一个进程有一个独立的监听socket,并且bind相同的ip:port,独立的listen()和accept();提高接收连接的能力。(例如nginx多进程同时监听同一个ip:port)
(a) on Linux SO_REUSEPORT is meant to be used purely for load balancing multiple incoming UDP packets or incoming TCP connection requests across multiple sockets belonging to the same app. ie. it’s a work around for machines with a lot of cpus, handling heavy load, where a single listening socket becomes a bottleneck because of cross-thread contention on the in-kernel socket lock (and state).
(b) set IP_BIND_ADDRESS_NO_PORT socket option for tcp sockets before binding to a specific source ip
3 V# P3 V; y& c0 {" F" @with port 0 if you’re going to use the socket for connect() rather then listen() this allows the kernel
6 H7 A  Q+ p& d. m& r% Mto delay allocating the source port until connect() time at which point it is much cheaper
The Ephemeral Port Range
Ephemeral Port Range就是我们前面所说的Port Range(/proc/sys/net/ipv4/ip_local_port_range)
A TCP/IPv4 connection consists of two endpoints, and each endpoint consists of an IP address and a port number. Therefore, when a client user connects to a server computer, an established connection can be thought of as the 4-tuple of (server IP, server port, client IP, client port).
Usually three of the four are readily known – client machine uses its own IP address and when connecting to a remote service, the server machine’s IP address and service port number are required.
What is not immediately evident is that when a connection is established that the client side of the connection uses a port number. Unless a client program explicitly requests a specific port number, the port number used is an ephemeral port number.
Ephemeral ports are temporary ports assigned by a machine’s IP stack, and are assigned from a designated range of ports for this purpose. When the connection terminates, the ephemeral port is available for reuse, although most IP stacks won’t reuse that port number until the entire pool of ephemeral ports have been used.
So, if the client program reconnects, it will be assigned a different ephemeral port number for its side of the new connection.
linux 如何选择Ephemeral Port
有资料说是随机从Port Range选择port,有的说是顺序选择,那么实际验证一下。
如下测试代码:
1
, C$ a) t. J+ `' I' n' a2
1 m, m3 z: w+ E: j; Y4 l; h3' p( X+ Y. D( W# {
4# c% l3 `; R  J. O5 n; g; j
5: B4 Z$ O# B7 j" p- I  I9 E: J
6" }3 n% n# n- x4 C7 X
7; R# d2 `$ x- c7 i0 e' o
8
6 r4 D- i" P1 @2 ^: l9
3 O4 D$ }2 j0 e1 `# @+ i  t10$ ^. O% q2 r6 E7 @- B
117 @# M: k# D  D
129 l9 I- t9 m* m5 A) d9 `& v
13
- R8 j; Z0 q( A1 K14& c+ @2 t+ f7 |$ j* N: ]; U
156 s* V/ |" ?6 k  R% A. o& V! b
164 S% G. N5 i/ b, a+ B
17+ e8 g  c0 f- {5 V1 v
182 E/ A+ {9 \6 ?& ^3 c0 _
19
, m. W/ O0 z3 d+ L) `6 a20& T/ d& |3 M) i
21
! X2 H( P7 x- i; l2 R22
. V6 e5 S. W1 D& b" y23
5 F8 F3 C& G. g7 U24+ E, [7 W) [6 |. Y( K# K1 a
25+ q1 g1 [9 S' b$ a* z- O
26
. n3 Z2 E  r1 l* |27
) {4 F5 E+ e5 u. V283 _3 h- t6 s2 J  ^! J
29
" l% ^) O1 g) M+ t; L30/ H4 z6 w) V1 v. y. C
31
& G$ b6 `9 F* y32' r2 Y& ^7 u0 I$ S; J
33
9 H+ a1 v) l- m) F34
8 Y8 X8 Y  H  k! l! r: d; b35
! b  {; y9 I2 y4 Y361 K& N9 J9 u' J2 G
37
9 W4 G0 r' j7 n0 X/ B38
, J% H  O3 V) n7 F7 ^2 b6 W39
* n/ j8 t- X- N# K$ c' T/ o5 m408 ^% ^$ M! a& }
41
9 D+ ~. Y; ]+ h9 A42
- X7 j, L( m5 U! G& m, Q  \
#include <stdio.h>      // printf, S3 [, b! o, t- _: I$ y" _
#include <stdlib.h>     // atoi
, h% ?  l  |( n5 Q#include <unistd.h>     // close
( {  Y' z- ~, I( ~. n: U# g#include <arpa/inet.h>  // ntohs
( b' `: C  Y; K; g& b#include <sys/socket.h> // connect, socket
$ T' I9 F. T+ E9 g4 |4 N' G/ O" E, s" q+ N  t
void sample() {* \6 H# f+ x( U# Z& r; a$ k
    // Create socket
% B% ?7 H, I3 b: _  P    int sockfd;8 o7 o/ y% F  v: p2 X1 b% P
    if (sockfd = socket(AF_INET, SOCK_STREAM, 0), -1 == sockfd) {
; o* e6 \# L7 b! J# D        perror("socket");
8 P" c* v# i) s1 i3 P" x- v- ~    }
+ @- z; {. ]- t1 C3 E  l( T$ c
. Z3 x5 G9 D8 _( E3 y- Z  r0 W' Q    // Connect to remote. This does NOT actually send a packet.
' p1 m* P& u, Y$ [" k2 g    const struct sockaddr_in raddr = {
6 X: h+ k0 M1 g. k* o        .sin_family = AF_INET,* b+ G/ d% X2 n. c. \5 l
        .sin_port   = htons(8080),     // arbitrary remote port
% @4 o) P: \7 g7 u' R4 G+ R        .sin_addr   = htonl(INADDR_ANY)  // arbitrary remote host* U; O' A3 }1 U0 Z; F8 z
    };
+ i$ S4 m. g4 k% L! T2 y6 J% u- R: i    if (-1 == connect(sockfd, (const struct sockaddr *)&raddr, sizeof(raddr))) {
- g: a: ?" U9 r8 E7 t# W        perror("connect");5 F4 k! |/ n* q( `; `8 C
    }/ o; {, m' U9 S4 t" i8 L

$ y' w; k7 u. [. L    // Display selected ephemeral port
- ]8 n! z3 a0 O! z$ j    const struct sockaddr_in laddr;* I' y7 c* l/ q6 k9 a
    socklen_t laddr_len = sizeof(laddr);1 L4 @1 e- A5 X% J9 z0 `
    if (-1 == getsockname(sockfd, (struct sockaddr *)&laddr, &laddr_len)) {; _' |. c. c5 i4 }9 b3 w3 |6 `
        perror("getsockname");5 e3 S0 M- c8 C$ E
    }% i* e% G5 m0 O! ?* t' ]3 x% G) r
    printf("local port: %i\n", ntohs(laddr.sin_port));! N- u* Y! A! y! j/ e

# a1 e# g& i+ V  Z    // Close socket4 O; ]: B$ ^* H% N/ \
    close(sockfd);( f, L9 F3 S: O0 Z. n! K2 [
}
* @& C2 g% a/ A
; j' z7 k* R4 z8 }2 G6 vint main() {
5 Y, X1 B6 \- f) g    for (int i = 0; i < 5; i++) {
8 i5 Q/ `1 }' D+ B0 b6 i        sample();
  G0 v8 g' @# R+ m8 J5 X# ~% r    }
$ Y2 U4 g8 |3 }7 [
* G. P9 `% `  g) B2 h" D! m    return 0;" X4 {& g! l( t
}
% l0 i* [1 y9 K/ w' j
bind逻辑测试代码
1- N! N* C7 ?% h6 m0 P- @4 f
2
* H2 n, D5 E" @! h( Z3' e5 g) g5 W% I. ^0 ?
4
- o. o( Q, h" T) c. b3 j% y5" G6 w7 g9 v0 p
6
3 S( i% X5 Z. r. ?5 P0 u( i7
- O1 ]* c3 S/ o5 v  E! _8$ F$ i  d' N2 w" {* e
9) e! {9 z) S- y6 e6 V
10
! \( A" s! F* U4 ?8 i114 I) H& F& \% e) Z% t
12
! a4 `7 B1 R0 r130 ^1 [% K5 h% t2 X0 _. n
14
/ S! X- b/ ?9 F& G' d) P15* l8 w- w* O3 b( }0 N/ ]
16
/ G" K1 c7 G, M6 @* I2 \0 \0 p17
8 U6 `2 ]& s  `% e& B18: s/ A6 Q$ ~4 ?+ w- _
199 a0 U* y# F% A6 h8 e: D( O
20
2 f# E! `  y6 t) j/ Y3 u# F213 ~! G# C# \" l0 P( e
22
3 ^! q" `8 [) V# m2 A1 f23
, y3 R5 j2 U: s$ j248 j& X+ S( ~& t$ }! ^3 m
25, p9 {' h0 O6 }
26" t; t; R0 X7 d8 O' Q  {7 |* u
27
8 {5 ?: l7 C  O- p28: l! c3 r: E2 |/ S- _7 D  h
29
0 _1 z' g: Q3 \7 w, _3 d305 `0 ?& ]; ]: Y" ]! a$ T5 v3 k
31" z$ {3 `4 x! [# ]& ^! p
32
; r6 Z5 G: w0 T6 \% C7 \: w336 k, O% |. u: |* N. p
34* X0 S8 ^2 Q; F' }( v
35  q, S- }7 a8 F, d9 S2 y5 q6 {
36
! z  D* _* U# q; A37
3 [- N8 J# h* ]0 p  E( y38
$ B( u: {6 N# v2 O! `39
- K9 K% d) _  i. s7 B! C40
. y5 a- b; x$ j4 Y4 U0 s7 W4 A41
+ q- @- H9 b- N0 ?+ I7 e42  P3 g3 ]6 V4 D! m4 q( w7 o
#include <netinet/in.h>
" q: ^2 ~& X' Q8 Z6 _#include <arpa/inet.h>
' D4 ]; t* ~( n#include <stdio.h>; L+ H) T0 r8 M: h/ G, m
#include <stdlib.h>9 V, ]# `7 z* `) j9 G7 J
#include <unistd.h>
+ z2 F7 o/ [! q' I4 |#include <errno.h>" O! G6 E8 G7 j# d3 o
#include <string.h>
: K% D" V1 j- Y( [#include <sys/types.h>
6 v$ {( K7 G6 n/ A0 ~' z#include <time.h>& N2 i. C1 M0 w
# s/ v/ Z1 @& Z1 P& E
void test_bind(){2 N: n7 y- K9 P  d: _' N+ Y- ?
    int listenfd = 0, connfd = 0;
% h- y2 i* c& D$ t7 ?    struct sockaddr_in serv_addr;# Q1 \: e+ Y  I. e/ x0 h& H
    char sendBuff[1025];: F& z: [) X6 |! W8 M5 e3 [
    time_t ticks;& h( l1 h& `8 q
          socklen_t len;
% S; \5 A! k! a
8 G8 m2 I' H. {  H) k$ ]    listenfd = socket(AF_INET, SOCK_STREAM, 0);7 Y* ?1 t! O3 [9 Y# Q! v' Q
    memset(&serv_addr, '0', sizeof(serv_addr));! I$ Y$ w& {" q, B0 P. m* I
    memset(sendBuff, '0', sizeof(sendBuff));3 b* h8 R# W/ u& N7 t- m+ @
5 S& s0 Z! P' q. u+ s
    serv_addr.sin_family = AF_INET;
9 P/ {. b& v# }, q    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
/ u! Z- D, ]2 q/ Y6 i8 n    serv_addr.sin_port = htons(0);
5 A) c4 b* E& m8 i4 |( T4 a7 U0 s! `6 |$ d
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));
$ }0 I% p: ~0 `* u! @& q3 p
+ |  [( h3 c" ?; M' }          len = sizeof(serv_addr);
4 u4 E" [; h, y" O% I5 _: W0 J          if (getsockname(listenfd, (struct sockaddr *)&serv_addr, &len) == -1) {
2 j4 \( @! [0 r                      perror("getsockname");( _/ e$ r/ T# m2 w3 x
                            return;. c/ n2 I* s' N' l# N0 T
          }1 K+ H& _6 I: D) \/ s3 a
          printf("port number %d\n", ntohs(serv_addr.sin_port)); //只是挑选到了port,在系统层面保留,tcp连接还没有,netstat是看不到的
$ A, s1 T* I; b& j- H5 D  C}2 E+ W% K; v4 c, }  r% C
0 l: H: K- ]* m+ j% ~
int main(int argc, char *argv[])
) u: X) C* k* z: T: }. z0 I+ Y{
  e# }* O5 D( v' I# U3 u* }6 ^            for (int i = 0; i < 5; i++) {
. ^( ~) y' H5 \# ^$ v3 v& ?                                 test_bind();
- P7 k+ s# k  p. J$ t2 {9 F  J                                             }" w7 \2 i$ k( d. U+ w3 Z1 j0 p
                    return 0;
. ?8 n6 B0 r3 \" ?0 O% w- \2 B8 m}( V5 e" y6 s: R# S, Y8 k- {! L" H
3.10.0-327.ali2017.alios7.x86_64
编译后,执行(3.10.0-327.ali2017.alios7.x86_64):
1
$ m" M# b: l7 H! U' \; S* I$ o9 C2  R: U: e7 Y2 C/ f7 W4 J/ Y( u
3' q+ \4 {1 }( X. z( R; }) M2 d% T
44 K6 H6 l8 e& ?7 Q2 a
5
9 Q- `0 ~8 v0 G- W$ b9 I% Y& ^60 c9 A5 I) K- q/ u/ N) p$ b9 S
7
8 g: q4 N8 q, S$ v* @% W0 Y8
( G0 a5 {! `% p, o9 H9
# G# x; ?* Q6 q) _3 \6 ]10
9 B" ]0 d/ n( p; P* r/ U11, l7 P9 R6 T" R
12. I, C9 U  }- C+ ]0 N/ A* h
13+ _' Z+ P+ A4 R7 F. Y7 y; K* b
14
! y# G! ^5 x. z9 J% i" P# p15
4 O! O* p% x( d" ~/ J16* }/ N3 c" t( {: G
17& [4 L% m' f& y: I; \
18+ `4 v3 f+ @- T3 s
19
# O7 L# g3 s" T- A208 C/ B8 J) ^4 }* y  x: ~
21
7 r6 d  }" t1 J225 {3 m9 I6 g! A4 r9 c
23
. q6 Y# M0 a+ C& e$ a24
( k; E$ l9 ?9 V% Q% ]" U5 o2 q25
3 X2 M" A3 a7 z8 X9 T3 s269 }$ U9 Q& M1 W0 O5 p
277 n: k" Q0 z4 c- E# ]
28: G6 k) c& p: K$ k; j1 V8 J
29
5 {) \) D8 R7 g2 v" A, k* p8 ]30
6 K* b( ?7 ]: B6 W, ^/ |0 o31- H) E0 e$ [( G& Q/ B. F9 A. c
321 H4 x* {! A& K5 Y+ E
335 f. G. s. b) R* w
34
- L! \$ @0 u, y" V& n5 ^( S0 l350 Z" j6 |9 P. u3 {
36
3 _; d3 e5 W* ~  V5 p37
$ L, S' n  y6 f# b' ^: f
#date; ./client && echo "+++++++" ; ./client && sleep 0.1 ; echo "-------" && ./client && sleep 10; date; ./client && echo "+++++++" ; ./client && sleep 0.1 && echo "******"; ./client;9 c; v; `/ ]7 u) ^8 C9 E5 b
Fri Nov 27 10:52:52 CST 2020& \5 q- w1 I$ f- Q. o8 @
local port: 174486 p8 x- M% h+ v$ T+ Q
local port: 17449
4 e: D- I% G9 Dlocal port: 17451$ R! u& G+ O3 l0 o0 @
local port: 17452
- m: l: m% w- l* w* K! p: P& ulocal port: 17453
, F7 t# J# C* f* {++++++++ a% b+ X: I& o
local port: 17455
+ k$ X4 T8 v7 B  k1 y: e- Klocal port: 17456; ]0 |+ ^8 z! M; K
local port: 17457
6 ~5 ]% R0 T/ F0 T$ e2 R/ Clocal port: 17458$ o4 C3 D" ~. o  Y- Z2 `
local port: 17460. O2 e& w+ b. t: i
-------9 A$ E! f4 B( \- T% w" p0 P
local port: 17475
! C% p0 {- r( h( ylocal port: 17476: ]4 x7 Q8 a0 u: f. O
local port: 17477
1 ?7 E7 _3 H6 j  h/ c3 slocal port: 17478
: D) T- Q; ]  O; d- N& T( v' alocal port: 17479
$ f6 j* y) f& N8 gFri Nov 27 10:53:02 CST 2020
/ `+ c7 f6 C9 r4 W& g$ H- J/ n$ Tlocal port: 179979 X" F4 y) g) k' o: \
local port: 17998
9 n! \7 A$ r# O; c6 r( t& qlocal port: 17999( ]1 ~6 O) j4 P# m) ?) v" H- D
local port: 18000
4 G6 O' U" |$ _6 D( x8 `' S/ h7 dlocal port: 18001% \% w( ]" e$ G/ b0 i9 J
+++++++
$ }1 |! k& _  n: w' k7 slocal port: 18002; g' i( Q; a8 }* \0 t
local port: 18003, w! r8 u6 T+ H) K- `
local port: 18004! H' N% }- t2 P( i: V+ J+ P9 B
local port: 18005
; f, Z3 N. `7 y8 @local port: 18006
* u; H8 X+ F9 t7 ?******
( c3 M) D$ a# U# K/ Tlocal port: 18010& }5 z. o$ G( t8 b; c
local port: 18011
/ D; |. _8 \, c# ^" Q% `local port: 18012
2 _+ X6 |2 j2 t5 ?" ]4 Qlocal port: 18013$ j3 `% w' p, n0 G: G0 ?" }
local port: 180149 s& x5 Y. Q; [, |6 y. p& J' S
从测试看起来linux下端口选择跟时间有关系,起始端口肯定是顺序增加,起始端口应该是在Ephemeral Port范围内并且和时间戳绑定的某个值(也是递增的),即使没有使用任何端口,起始端口也会随时间增加而增加。
4.19.91-19.1.al7.x86_64
换个内核版本编译后,执行(4.19.91-19.1.al7.x86_64):
12 L* I. `8 u& [7 o) G7 p
24 {; I$ x8 `8 W+ G9 M0 l. J
3- u, L0 F4 ?4 x) z
4
, X# N! @/ g/ @. }% W2 o5! O6 ^: n7 J1 M, Q  d
64 @6 h) o! z" K* F4 [3 H
7( y! Y0 |& H- P+ m5 J
8* l7 P: p5 E5 x6 k# o8 O3 A( h+ J
9
" F) T, n9 ]" q% Z100 f& _3 k8 u: |# y
11
  m2 x3 d. S' E9 |. K1 d12; W* W* u6 C% ~, |) N3 i" b/ f
13
+ ]/ s9 O0 l9 _14# n  C7 w2 S. {3 y' ?/ z
159 K# w7 [( S0 q- h
16% M6 E" H0 A0 ~9 `; _
17
7 a+ T% {& H! T18
! J/ x7 D5 z3 V: K+ N19, ]6 o- I' W! u8 S) b* b
20
' g3 Y7 n/ Y$ P5 w+ q$ |1 a21
9 v( J2 F( d5 o2 t9 j! p22
7 p* Z9 c: I+ m+ |2 Z236 U2 F# t0 o6 v5 S8 j
24. D) W* c4 `- B0 \! i0 X8 B$ Z, N* O
253 ~0 W3 q% o; C; A. E# r
26& l# R& e" ^+ V4 |
27
1 e. V, E- y) L287 e" V1 d( y/ z# S# V9 d
290 z$ {" D/ R; d/ c+ R% U- f7 D0 c
309 {0 @/ e* J" f9 L
31
5 J% R! @$ _# z7 [8 d328 s6 [# {, x" @1 r' T
33
; b5 B, k) `0 ~& M/ d34( r) c4 V) a8 y: M4 h9 x1 y
35
( S7 M* Z8 U- d( }1 G& m36, z# h+ E8 F: R! c& x4 [( ]
37
$ D; H* @8 G: w" M4 ^
$date; ./client && echo "+++++++" ; ./client && sleep 0.1 ; echo "-------" && ./client && sleep 10; date; ./client && echo "+++++++" ; ./client && sleep 0.1 && echo "******"; ./client;
. F& m  R' ~+ q; i+ {8 d2 m: vFri Nov 27 14:10:47 CST 2020
+ ?6 b8 D7 v9 K; e( o& mlocal port: 78902 _/ A, J1 `0 U; U# [& |1 S
local port: 7892
, W5 Q7 Y- [( \& v1 r8 ]) Klocal port: 7894+ Y2 D6 G4 p- P
local port: 78968 f: B1 s4 Z3 D: U4 {  A# @5 u4 r
local port: 7898
% A3 z2 Z& |  ~2 c, Q2 l$ }: S5 `+++++++
  S! }- e: R6 plocal port: 7900+ X. q7 k! }5 z: ]  Z, Y9 U
local port: 79024 ^# H& z* o) b/ g5 J
local port: 7904$ t2 ^, T" b% C% B$ |% L; k: `5 w7 h
local port: 7906
0 v  \! r/ v0 ^! c( o0 i( blocal port: 7908
8 W# b! [/ V: k1 u-------
% T* Z% n8 @% `: o. j/ h% y1 Alocal port: 7910
' F  [9 ?6 r0 D6 n9 s" Vlocal port: 7912
! f+ x1 u8 k" _" G% \local port: 7914
  G( x7 G) E$ t) Clocal port: 7916' O& s" b+ T) S
local port: 7918+ {8 _5 E# H5 K+ o# K9 w3 O
Fri Nov 27 14:10:57 CST 2020
5 f( K  e4 Y, b. S3 V5 tlocal port: 7966
* P8 n& F% E% l5 d+ Ylocal port: 7968# q% L; Q) T2 H4 \; D* k
local port: 7970
6 U/ ~% W! H! S8 @local port: 7972# V/ N) o0 B! E
local port: 79741 J$ |! P' w, y& q% {
+++++++
6 ^) J) T3 i* B* A  @% Xlocal port: 7976' ~4 w7 T2 B9 a8 G( |
local port: 7978
4 \& z6 F; D3 ~+ F9 Zlocal port: 79800 a( y6 q# ]' X# o! u; _2 J9 q" j% Z
local port: 7982
5 F3 _4 m3 z/ e: glocal port: 7984/ x0 k# s6 j8 {' y
******: O5 X# t- @, n. [$ [5 f+ U
local port: 7988
+ k- z4 \+ T6 u) R  Plocal port: 79906 f2 q3 N/ v# E# U: L, v
local port: 7992
& g* x) h. d* i$ s- q# b) ]local port: 79947 |6 d8 i. _5 L* j& k5 ]( B' ^
local port: 7996
( D" b/ ^" E1 U$ ?
以上测试时的参数
1
. c# ]8 H# ^7 l, t! a  Z) @2: ?$ U/ n4 K0 V# p
$cat /proc/sys/net/ipv4/ip_local_port_range6 z9 U! c2 w2 {' T
1024    65535; _8 o8 [5 n, K( r
将1024改成1025后,分配出来的都是奇数端口了:
1
8 {$ K" w- b; j4 J+ H1 u* K2# e" {- u, l: z0 i* Z5 @$ h
3, {" j# H- q! ^( q+ Q4 b" h
4
& R. p; [- U+ k4 k( I5
! K! c* e, U  v) m' O8 C6
8 }2 w, Z$ x& ^! r2 Y( x0 U* ~! }7
  l6 H# J! U  W# n3 ?! }: p3 G8
7 C# d# Q4 ^1 j+ N: o% ~9
* r3 \+ }4 b; [4 O# q' E! Y, ]103 O9 U! Z% ?9 u% W. j& p! d: S
11( Y# b2 d" E' F6 X* n, f
12* c& i" G% h+ a
13! \5 h/ e8 [" ]. d
14
; f6 @! T, S: a" q0 q# k5 x5 W1 u5 m157 ~. T0 `5 n% n
16# q( X1 E( u! n8 z8 `
17
/ Q. I! |# r0 r- V! q- Q: F6 F18
$ S& Y7 ~1 N9 ?" Q/ n19
0 R/ o/ M3 B" q
$cat /proc/sys/net/ipv4/ip_local_port_range
  v, I" r4 ~; \2 R1025    1034
$ @0 D+ l5 l0 h9 O( X! m+ u) F7 m5 D" }
$./client: {  W. ]4 u" c9 l9 |
local port: 1033
  z( q4 t% l, t; L. Jlocal port: 1025
* R) p  q$ v- s# u$ J; D8 P- I% flocal port: 10278 |  ]$ u7 w; f$ V/ K9 U
local port: 10297 e7 E3 F! C1 s
local port: 1031
  a  u% I+ c* |: ^( A6 C' _- }local port: 1033
. X5 z' d/ k5 _" ~2 V- Vlocal port: 1025
9 o0 s  r# A1 ~$ elocal port: 1027
0 \6 R/ W8 a7 v. z6 Ylocal port: 1029
+ q5 s2 Q$ J. r7 ^2 S) l* t+ w/ \+ ?local port: 1031' P! G: @! j" F- a% O, [& c+ o
local port: 10333 g. C  l! ~3 K% P- O# \
local port: 1025
% h1 A, e; v* P6 T+ M! ?local port: 1027( x0 Z6 V* ^3 ^5 w5 Z8 }
local port: 1029
2 x  `+ ?' x) Ulocal port: 1031
8 |+ K* q% ?5 M4 Q6 L5 B1 z! F
之所以都是偶数端口,是因为port_range 从偶数开始, 每次从++变到+2的原因,connect挑选随机端口时都是在起始端口的基础上+2,而bind挑选随机端口的起始端口是系统port_range起始端口+1(这样和connect错开),然后每次仍然尝试+2,这样connect和bind基本一个用偶数另外一个就用奇数,一旦不够了再尝试使用另外一组
1
8 G/ w2 D: V& @+ ?9 O" T2( d& p9 j' e( W, K: Z+ l
3. n3 r# J& Y* f. U
4
2 T$ G; l. O* _59 k( r) e. n5 V( k
6% F/ Y8 t& f  e" L6 X
75 E  Z1 _( }7 D+ J; O
8" J; p9 C8 S1 K5 X5 ^6 _/ F$ C: R& V
9
8 @. v4 q7 V" a! L! K) D% R5 S( @10. B+ X  z, W4 H! {
11% D' \! p5 S3 k3 w, W* O. U6 `
126 T2 C& l1 ?+ h4 G& g0 `
13
8 z$ S4 o* U% I  D0 o14
  [4 }6 `) k# r& p% w# i15
6 I5 V4 ^! D! s: q- f, ~, {0 U7 k8 ]16" p  r: O) q* W
179 D6 B% H0 M( W, I( W$ \
$cat /proc/sys/net/ipv4/ip_local_port_range
. \' Z( r1 k8 l1 m6 W1024    1047
: M# [8 P2 `) D& `
2 I- I: ]7 T- \& l" F4 Y$ _$./bind &  ---bind程序随机挑选5个端口
( o+ J1 T1 w5 h* ~2 xport number 1039
4 M& M$ t/ C" L) V0 ^) E. dport number 1043
% |# O; @2 a% lport number 1045
$ }( V2 z" S  z0 B* w6 X! bport number 1041
! Z! Z6 ?1 M. g  c' f3 Cport number 1047  --用完所有奇数端口1 `. v# N; l0 }  `; i4 ~8 D

( R0 v& V2 B8 R  y+ w7 _$./bind &    --继续挑选偶数端口
2 k5 ?6 x: U2 C% T[8] 4170
/ ~" ?5 Z/ Q$ F5 l' ?. k8 G8 xport number 1044% z; p5 @$ Y! s
port number 10422 J! U+ h" K. [5 R  K+ r9 f
port number 10461 L3 T& f8 q9 R& b
port number 0    --实在没有了
# J* o4 T2 G1 b, b' d! S1 h3 @% @port number 0* c2 m2 w) |/ h$ w" D5 T
可见4.19内核下每次port是+2,在3.10内核版本中是+1. 并且都是递增的,同时即使port不使用,也会随着时间的变化这个起始port增大。
Port Range有点像雷达转盘数字,时间就像是雷达上的扫描指针,这个指针不停地旋转,如果这个时候刚好有应用要申请Port,那么就从指针正好指向的Port开始向后搜索可用port
tcp_max_tw_buckets
tcp_max_tw_buckets: 在 TIME_WAIT 数量等于 tcp_max_tw_buckets 时,新的连接断开不再进入TIME_WAIT阶段,而是直接断开,并打印warnning.
实际测试发现 在 TIME_WAIT 数量等于 tcp_max_tw_buckets 时 新的连接仍然可以不断地创建和断开,这个参数大小不会影响性能,只是影响TIME_WAIT 数量的展示(当然 TIME_WAIT 太多导致local port不够除外), 这个值设置小一点会避免出现端口不够的情况
tcp_max_tw_buckets - INTEGER. `! S7 p7 F% H2 @& s; ~: L6 N
Maximal number of timewait sockets held by system simultaneously.If this number is exceeded time-wait socket is immediately destroyed and warning is printed. This limit exists only to prevent simple DoS attacks, you must not lower the limit artificially, but rather increase it (probably, after increasing installed memory), if network conditions require more than default value.
SO_LINGER
SO_LINGER选项用来设置延迟关闭的时间,等待套接字发送缓冲区中的数据发送完成。 没有设置该选项时,在调用close() 后,在发送完FIN后会立即进行一些清理工作并返回。 如果设置了SO_LINGER选项,并且等待时间为正值,则在清理之前会等待一段时间。
如果把延时设置为 0 时,Socket就丢弃数据,并向对方发送一个 RST 来终止连接,因为走的是 RST 包,所以就不会有 TIME_WAIT 了。
This option specifies how the close function operates for a connection-oriented protocol (for TCP, but not for UDP). By default, close returns immediately, but ==if there is any data still remaining in the socket send buffer, the system will try to deliver the data to the peer==.
SO_LINGER 有三种情况
  • l_onoff 为false(0), 那么 l_linger 的值没有意义,socket主动调用close时会立即返回,操作系统会将残留在缓冲区中的数据发送到对端,并按照正常流程关闭(交换FIN-ACK),最后连接进入TIME_WAIT状态。这是默认情况
  • l_onoff 为true(非0), l_linger 为0,主动调用close的一方也是立刻返回,但是这时TCP会丢弃发送缓冲中的数据,而且不是按照正常流程关闭连接(不发送FIN包),直接发送RST,连接不会进入 time_wait 状态,对端会收到 java.net.SocketException: Connection reset异常
  • l_onoff 为true(非0), l_linger 也为非 0,这表示 SO_LINGER选项生效,并且超时时间大于零,这时调用close的线程被阻塞,TCP会发送缓冲区中的残留数据,这时有两种可能的情况:
    + D& ?+ o7 I3 T# H6 s  n5 L8 p
    • 数据发送完毕,收到对方的ACK,然后进行连接的正常关闭(交换FIN-ACK)
    • 超时,未发送完成的数据被丢弃,连接发送RST进行非正常关闭. }! t) }* r7 X9 h
1) V5 O7 D! Z. R+ D! h5 `* X
2
# J; {) ^) A! A, o0 r3
: U% P& P8 V. R* X7 }4 g. {4# s3 S4 Z  m0 v3 B. d$ d
struct linger {! ^/ u6 n% J3 P1 A( @; q* s- z8 Y
  int   l_onoff;        /* 0=off, nonzero=on */
7 ^# m; h# A; _9 B9 f) `' w  int   l_linger;       /* linger time, POSIX specifies units as seconds */: ^8 J/ P  {! Z4 Q
};' a9 J* R, s7 O
NIO下设置 SO_LINGER 的错误案例
在使用NIO时,最好不设置SO_LINGER。比如Tomcat服务端接收到请求创建新连接时,做了这样的设置:
1) s# m! Z' v( c4 b- s! U; l! @0 Z
SocketChannel.setOption(SocketOption.SO_LINGER, 1000)
& o# o1 R/ G1 a; U5 T
SO_LINGER的单位为秒!在网络环境比较好的时候,例如客户端、服务器都部署在同一个机房,close虽然会被阻塞,但时间极短可以忽略。但当网络环境不那么好时,例如存在丢包、较长的网络延迟,buffer中的数据一直无法发送成功,那么问题就出现了:close会被阻塞较长的时间,从而直接或间接引起NIO的IO线程被阻塞,服务器会不响应,不能处理accept、read、write等任何IO事件。也就是应用频繁出现挂起现象。解决方法就是删掉这个设置,close时立即返回,由操作系统接手后面的工作。
这时会看到如下连接状态
以及对应的堆栈
查看其中一个IO线程等待的锁,发现锁是被HTTP线程持有。这个线程正在执行preClose0,就是在这里等待连接的关闭
每次HTTP线程在关闭连接被阻塞时,同时持有了SocketChannelImpl的对象锁,而IO线程在把这个连接移除出它的selector管理队列时,也要获得同一个SocketChannelImpl的对象锁。IO线程就这么一次次的被阻塞,悲剧的无以复加。有些NIO框架会让IO线程去做close,这时候就更加悲剧了。
总之这里的错误原因有两点:1)网络状态不好;2)错误理解了l_linger 的单位,是秒,不是毫秒。 在这两个原因的共同作用下导致了数据迟迟不能发送完毕,l_linger 超时又需要很久,所以服务会出现一直阻塞的状态。
为什么要有 time_wait 状态
TIME-WAIT - represents waiting for enough time to pass to be sure the remote TCP received the acknowledgment of its connection termination request.
短连接的开销
用ab通过短连接走 lo 网卡压本机 nginx,CPU0是 ab 进程,CPU3/4 是 Nginx 服务,可以看到 si 非常高,QPS 2.2万
再将 ab 改用长连接来压,可以看到si、sy都有下降,并且 si 下降到短连接的20%,QPS 还能提升到 5.2万
一条连接的开销
主要是内存开销(如图,来源见水印),另外就是每个连接都会占用一个文件句柄,可以通过参数来设置:fs.nr_open、nofile(其实 nofile 还分 soft 和 hard) 和 fs.file-max
从上图可以看到:
  • 没有收发数据的时候收发buffer不用提前分配,3K多点的内存是指一个连接的元信息数据空间,不包含传输数据的内存buffer
  • 客户端发送数据后,会根据数据大小分配send buffer(一般不超过wmem,默认kernel会根据系统内存压力来调整send buffer大小)
  • server端kernel收到数据后存放在rmem中,应用读走后就会释放对应的rmem
  • rmem和wmem都不会重用,用时分配用完释放

    " {: o6 `8 ?: p' c7 x. q
可见,内核在 socket 内存开销优化上采取了不少方法:
  • 内核会尽量及时回收发送缓存区、接收缓存区,但高版本做的更好
  • 发送接收缓存区最小并一定不是 rmem 内核参数里的最小值,实际大部分时间都是0
  • 其它状态下,例如对于TIME_WAIT还会回收非必要的 socket_alloc 等对象/ F" S8 j' A0 p4 ^' [5 i+ I
可用 local port 不够导致对端time_wait 连接重用进而卡顿案例
A进程选择某个端口,并设置了 reuseaddr opt(表示其它进程还能继续用这个端口),这时B进程选了这个端口,并且bind了,如果 A 进程一直不释放这个端口对应的连接,那么这个端口会一直在内核中记录被bind用掉了(能bind的端口 是65535个,四元组不重复的连接你理解可以无限多),这样的端口越来越多后,剩下可供 A 进程发起连接的本地随机端口就越来越少了,这时会造成新建连接的时候这个四元组高概率重复,一般这个时候对端大概率还在 time_wait 状态,会忽略掉握手 syn 包并回复 ack ,进而造成建连接卡顿的现象
结论
  • 在内存、文件句柄足够的话一台服务器上可以创建的TCP连接数量是没有限制的
  • SO_REUSEADDR 主要用于快速重用 TIME_WAIT状态的TCP端口,避免服务重启就会抛出Address Already in use的错误
  • SO_REUSEPORT主要用来解决惊群、性能等问题
  • 全局范围可以用 net.ipv4.tcp_max_tw_buckets = 50000 来限制总 time_wait 数量,但是会掩盖问题
  • local port的选择是递增搜索的,搜索起始port随时间增加也变大/ j( ~" z8 i1 e9 _
参考资料
2 o6 w. K6 R  p% K" f9 \4 ]0 F
4 e  N" z' ?) U* X' _4 p

: Y" w6 K* s9 k, }) ]: V/ y% @% b5 c; T
# Linux # TCP # SO_REUSEADDR # ip_local_port_range
# F2 K! c4 L3 F* f7 t5 O8 p% N3 e- j, L
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|华强北 电脑城 龙岗电子世界 龙华电脑城 pc4g.com ( 粤ICP备16039863号 )

GMT+8, 2024-9-18 17:37 , Processed in 0.181422 second(s), 15 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表