当前位置:首页 > 公众号精选 > Linux阅码场
[导读]当然可以,只要你使用 SO_REUSEPORT 这个参数。还是先来看下man文档中是怎么说的:SO_REUSEPORT(sinceLinux3.9)PermitsmultipleAF_INETorAF_INET6socketstobeboundtoanidenticalsocke...

当然可以,只要你使用 SO_REUSEPORT 这个参数。


还是先来看下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.

从文档中可以看到,该参数允许多个socket绑定到同一本地地址,即使socket是处于listen状态的。


当多个listen状态的socket绑定到同一地址时,各个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,
本站声明: 本文章由作者或相关机构授权发布,目的在于传递更多信息,并不代表本站赞同其观点,本站亦不保证或承诺内容真实性等。需要转载请联系该专栏作者,如若文章内容侵犯您的权益,请及时联系本站删除。
关闭
关闭