c - 错误 : Address already in use while binding socket with address but the port number is shown free by `netstat`

标签 c linux sockets

我尝试将我的套接字(服务器套接字)绑定(bind)到端口号 8000。它为我工作并完成了工作。在代码的末尾,我也关闭了套接字。下一刻我再次运行我的代码,它告诉我地址​​已经在使用中。我已经打印了错误值 strerror(errno); 的含义,以查看我的代码是否在每个点都正常工作。为了检查端口是否空闲,我使用 netstat 检查了它,但它显示端口号 8000 是空闲的。它发生在我身上很多次。每次我再等几秒钟,然后它又开始工作了。我正在使用c语言。那么他是什么原因导致我的操作系统出现这种行为。

几秒钟后,我运行代码,然后它就可以工作了。

anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo ./a.out 
Socket Creation: Success
File open: Success
Socket Bind: Address already in use
Socket Listen: Address already in use
^C
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo netstat -lntp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1348/lighttpd   
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      984/sshd        
tcp        0      0 127.0.0.1:631           0.0.0.0:*               LISTEN      1131/cupsd      
tcp        0      0 0.0.0.0:3306            0.0.0.0:*               LISTEN      1211/mysqld     
tcp6       0      0 :::22                   :::*                    LISTEN      984/sshd        
tcp6       0      0 ::1:631                 :::*                    LISTEN      1131/cupsd      
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo ./a.out 
Socket Creation: Success
File open: Success
Socket Bind: Address already in use
Socket Listen: Address already in use
^C
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ 

最佳答案

我也遇到了同样的问题。这是因为您正在关闭与套接字的连接,而不是套接字本身。套接字可以进入 TIME_WAIT 状态(以确保所有数据都已传输,如果可能,TCP 保证交付)and take up to 4 minutes to release .

或者,对于真正详细/技术性的解释,check this link

这当然很烦人,但这不是错误。请参阅@Vereb 对以下关于使用 SO_REUSEADDR 的答案的评论。

关于c - 错误 : Address already in use while binding socket with address but the port number is shown free by `netstat` ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5106674/

相关文章:

c++ - 使用 automake 和 autoconf 包含动态库

Java 通过套接字发送和接收文件 (byte[])

c - 在 c 中返回带有自定义函数的数组不起作用

c - 处理多个C中的相似代码 "projects"

c - recv - 始终填充第一个字节

Linux (玛吉亚) : make not found/usr/bin/make

c - GCC 无法包含指定了 -l 选项的 header

linux - 在 Linux 中通过网页进行一些管理工作的最佳方法(安全性)?

python通过TCP套接字发送/接收十六进制数据

java - ServerSocket 连接问题