Example of the SO_REUSEADDR Option

來源:互聯網
上載者:User

quoted from

http://www.docs.hp.com/en/B2355-90136/ch03s01.html

 

This option is AF_INET socket-specific.

SO_REUSEADDR
enables you to restart a daemon which was killed or terminated.

This option modifies the rules used by bind to validate local addresses, but it does not violate the uniqueness requirements of an association. SO_REUSEADDR modifies the bind rules only when a wildcard Internet Protocol (IP) address is used in combination with a particular protocol port. The host still checks at connection time to be sure any other sockets with the same local address and local port do not have the same remote address and remote port. Connect
fails if the uniqueness requirement is violated.

Example of the SO_REUSEADDR Option

A network daemon server is listening on a specific port: port 2000. If you executed netstat an
, part of the output would resemble:


Active connections (including   servers)
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp 0 0 *.2000 *.* LISTEN

Network Daemon Server Listening at Port 2000

When the network daemon accepts a connection request, the accepted socket will bind
to port 2000 and to the address where the daemon is running (e.g. 192.6.250.100
). If you executed netstat an
, the output would resemble:


Active connections (including servers)
Proto Recv-Q Send-Q Local Address Foreign Address (state)
tcp 0 0 192.6.250.100.2000 192.6.250.101.4000 ESTABLISHED
tcp 0 0 *.2000 *.* LISTEN

New Connection Established, Daemon Server Still Listening

Here the network daemon has established a connection to the client (192.6.250.101.4000
) with a new server socket. The original network daemon server continues to listen for more connection requests.

If the listening network daemon process is killed, attempts to restart the daemon fail if SO_REUSEADDR is not set. The restart fails because the daemon attempts to bind to port 2000 and a wildcard IP address (e.g. *.2000
). The wildcard address matches the address of the established connection (192.6.250.100
), so the bind
aborts to avoid duplicate socket naming.

When SO_REUSEADDR
is set, bind
ignores the wildcard match, so the network daemon can be restarted. An example usage of this option is:


int optval = 1;
setsockopt (s, SOL_SOCKET, SO_REUSEADDR, &optval,
sizeof(optval));
bind (s, &sin, sizeof(sin));

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.