且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查socket端口是否可用

更新时间:2021-07-10 22:48:00

您无需手动扫描可用端口——操作系统会为您完成.调用 bind() 时只需指定端口 0,操作系统就会选择一个.这通常对测试很有用——您可以使用端口 0 启动一个端点,让它询问系统它实际获得的端口是什么 (getsockaddr),然后使用该端口号启动第二个端点.

You don't need to manually scan for an available port--the OS will do it for you. Just specify port 0 when you call bind() and the OS will choose one. This is often useful for testing--you can launch one endpoint with port 0, have it ask the system what port it actually got (getsockaddr), then launch the second endpoint with that port number.