多進(jìn)程可以監(jiān)聽同一端口嗎
時(shí)間:2021-09-23 15:39:02
手機(jī)看文章
掃描二維碼
隨時(shí)隨地手機(jī)看文章
[導(dǎo)讀]當(dāng)然可以,只要你使用?SO_REUSEPORT?這個(gè)參數(shù)。還是先來看下man文檔中是怎么說的:SO_REUSEPORT(sinceLinux3.9)PermitsmultipleAF_INETorAF_INET6socketstobeboundtoanidenticalsocke...
當(dāng)然可以,只要你使用?SO_REUSEPORT?這個(gè)參數(shù)。
還是先來看下man文檔中是怎么說的:
從文檔中可以看到,該參數(shù)允許多個(gè)socket綁定到同一本地地址,即使socket是處于listen狀態(tài)的。
當(dāng)多個(gè)listen狀態(tài)的socket綁定到同一地址時(shí),各個(gè)socket的accept操作都能接受到新的tcp連接。
很神奇對吧,寫段代碼測試下:
還是先來看下man文檔中是怎么說的:
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the pro‐ cesses binding to the same address must have the same effec‐ tive UID. This option can be employed with both TCP and UDP sockets.
For TCP sockets, this option allows accept(2) load distribu‐ tion in a multi-threaded server to be improved by using a dis‐ tinct listener socket for each thread. This provides improved load distribution as compared to traditional techniques such using a single accept(2)ing thread that distributes connec‐ tions, or having multiple threads that compete to accept(2) from the same socket.
For UDP sockets, the use of this option can provide better distribution of incoming datagrams to multiple processes (or threads) as compared to the traditional technique of having multiple processes compete to receive datagrams on the same socket.從文檔中可以看到,該參數(shù)允許多個(gè)socket綁定到同一本地地址,即使socket是處于listen狀態(tài)的。
當(dāng)多個(gè)listen狀態(tài)的socket綁定到同一地址時(shí),各個(gè)socket的accept操作都能接受到新的tcp連接。
很神奇對吧,寫段代碼測試下:
#include #include #include #include #include #include #include #include
static int tcp_listen(char *ip, int port) { int lfd, opt, err; struct sockaddr_in addr;
lfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); assert(lfd != -1);
opt = 1; err = setsockopt(lfd, SOL_SOCKET, SO_REUSEPORT, 




