c++ - 数据报 Unix 套接字上的 ECONNREFUSED

标签 c++ sockets unix unix-socket

通过无连接数据报 Unix 套接字发送时出现 ECONNREFUSED 的可能原因是什么?

也欢迎任何有关如何调试此问题的建议,因为此问题是可重现的。

无论是否使用 sendto()sendmsg() 我都会收到错误消息。

if ((sock = socket(PF_UNIX, SOCK_DGRAM, 0)) < 0)
{
    return 0;
}
unlink("/tmp/serv");
addr.sun_family = AF_UNIX;    

strncpy(&addr.sun_path[0], "/tmp/serv", sizeof(addr.sun_path));

if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
    return 0;
}

sockaddr_un from;
int fromlen = sizeof(from);
if (recvfrom(sock, &i, sizeof(i),0,(sockaddr*)&from,(socklen_t*)&fromlen) < 0 )
{
    //some error handling code
}

printf("from.sun_family=%d, from.sun_path=%s",from.sun_family,from.sun_path); // this prints, as expected "from.sun_family=1, from.sun_path=/tmp/client"
strncpy(&addr.sun_path[0], "/tmp/client", sizeof(addr.sun_path));
sendto(sock,"abc",3,0,(sockaddr*)&addr, sizeof(addr)); //this fails with ECONNREFUSED

最佳答案

来自 man 7 unix :

ECONNREFUSED The remote address specified by connect(2) was not a listening socket. This error can also occur if the target filename is not a socket.

在 Linux 中,sendto 在 Unix 套接字上 does the following :

1548         if (sock_flag(other, SOCK_DEAD)) {
1549                 /*
1550                  *      Check with 1003.1g - what should
1551                  *      datagram error
1552                  */
1553                 unix_state_unlock(other);
1554                 sock_put(other);
1555 
1556                 err = 0;
1557                 unix_state_lock(sk);
1558                 if (unix_peer(sk) == other) {
1559                         unix_peer(sk) = NULL;
1560                         unix_state_unlock(sk);
1561 
1562                         unix_dgram_disconnected(sk, other);
1563                         sock_put(other);
1564                         err = -ECONNREFUSED;
1565                 } else {
1566                         unix_state_unlock(sk);
1567                 }
1568 
1569                 other = NULL;
1570                 if (err)
1571                         goto out_free;
1572                 goto restart;
1573         }

换句话说,您发送到的套接字的另一端没有读取器,或者套接字不再存在于文件系统中。

关于c++ - 数据报 Unix 套接字上的 ECONNREFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26016189/

相关文章:

c++ - 从字节数组创建IMFByteStream

php - 如何在 PHP 中处理套接字

Java NIO : Sending more than 16 objects causes error

c++ - ASM at&t 语法

c++ - 是否有用于从点语言字符串制作 png 的 C++ 函数?

c++ - 从类中返回一个字符串——奇怪的行为

Python - UDP套接字绑定(bind)()到正确的地址

shell - 不关闭ssh

bash - 如何使用 awk 或 grep 从不同行中选择数据?

c++ - Visual Studio 中///<comment> </comment> 的用途是什么