c - 绑定(bind)失败: Address already in use

标签 c linux sockets

我正在尝试将套接字绑定(bind)到以下端口:

if( bind(socket_desc,(struct sockaddr *) &server, sizeof(server)) < 0)
{
    perror("bind failed. Error");
    return 1;
}
puts("bind done");

但它给出了:

$ ./serve   
Socket created    
bind failed. Error: Address already in use

为什么会出现这个错误?

最佳答案

大家都是对的。但是,如果您还忙于测试代码,则您的自己的应用程序可能仍然“拥有”套接字(如果它启动和停止相对较快)。试试SO_REUSEADDR作为套接字选项:

What exactly does SO_REUSEADDR do?

This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.

It has been pointed out that "A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!" by Michael Hunter (mphunter@qnx.com). This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port. This is explained by Richard Stevens in ``2.7 Please explain the TIME_WAIT state.''.

关于c - 绑定(bind)失败: Address already in use,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57484464/

相关文章:

c++ - Waf:递归收集源文件并包含路径

c - 将 rodata 与创建它的函数一起定位

c - 如何消除这种段错误?

linux - DLNA FLAC 音频客户端可以在 Linux 上 headless 地工作吗?

android - 如何测量wifi LAN速度?

c++ - 是否可以将 long long 返回值分配给 int64_t 而不会丢失 64 位机器的精度?

c - 如何设置以 root 身份使用 execl 以用户身份启动应用程序?

c++ - g++ libc.so 绝对路径交叉编译错误

c - 重用 linux 抽象命名空间套接字

java - 如何使用 Java 套接字连接到特定文件夹?