【问题标题】:Why would connect() give intermittent EINVAL on port to FreeBSD?为什么 connect() 会在 FreeBSD 的端口上给出间歇性的 EINVAL?
【发布时间】:2011-05-01 01:36:32
【问题描述】:

我的 C++ 应用程序在从 32 位 Linux 移植到 32 位 FreeBSD 8.1 时出现故障。我有一个无法连接的 TCP 套接字连接。在对 connect() 的调用中,我得到了一个错误结果,错误结果为 errno == EINVAL,connect() 的手册页没有涵盖。

这个错误是什么意思,哪个参数无效?消息只是说:“无效参数”。

以下是连接的一些细节:

family: AF_INET
len: 16
port: 2357
addr: 10.34.49.13

但它并不总是失败。 FreeBSD 版本只有在让机器闲置几个小时后才会失败。但是在失败一次之后,它可以可靠地工作,直到你让它再次闲置很长一段时间。

以下是部分代码:

void setSocketOptions(const int skt);
void buildAddr(sockaddr_in &addr, const std::string &ip,
               const ushort port);
void deepBind(const int skt, const sockaddr_in &addr);


void
test(const std::string &localHost, const std::string &remoteHost,
     const ushort localPort, const ushort remotePort,
     sockaddr_in &localTCPAddr, sockaddr_in &remoteTCPAddr)
{
  const int skt = socket(AF_INET, SOCK_STREAM, 0);

  if (0 > skt) {
    clog << "Failed to create socket: (errno " << errno
         << ") " << strerror(errno) << endl;
    throw;
  }

  setSocketOptions(skt);

  // Build the localIp address and bind it to the feedback socket.  Although
  // it's not traditional for a client to bind the sending socket to a the
  // local address, we do it to prevent connect() from using an ephemeral port
  // which (our site's firewall may block).  Also build the remoteIp address.
  buildAddr(localTCPAddr, localHost, localPort);
  deepBind(skt, localTCPAddr);
  buildAddr(remoteTCPAddr, remoteHost, remotePort);

  clog << "Info: Command connect family: "
       << (remoteTCPAddr.sin_family == AF_INET ? "AF_INET" : "<unknown>")
       << " len: " << int(remoteTCPAddr.sin_len)
       << " port: " << ntohs(remoteTCPAddr.sin_port)
       << " addr: " << inet_ntoa(remoteTCPAddr.sin_addr) << endl;

  if (0 > ::connect(skt, (sockaddr*)& remoteTCPAddr, sizeof(sockaddr_in)))) {
    switch (errno) {
      case EINVAL: {
        int value = -1;
        socklen_t len = sizeof(value);
        getsockopt(skt, SOL_SOCKET, SO_ERROR, &value, &len);

        cerr << "Error: Command connect failed on local port "
             << getLocFbPort()
             << " and remote port " << remotePort
             << " to remote host '" << remoteHost
             << "' family: "
             << (remoteTCPAddr.sin_family == AF_INET ? "AF_INET" : "<unknown>")
             << " len: " << int(remoteTCPAddr.sin_len)
             << " port: " << ntohs(remoteTCPAddr.sin_port)
             << " addr: " << inet_ntoa(remoteTCPAddr.sin_addr)
             << ": Invalid argument." << endl;
        cerr << "\tgetsockopt => "
             << ((value != 0) ? strerror(value): "success") << endl;

        throw;
      }
      default: {

        cerr << "Error: Command connect failed on local port "
             << localPort << " and remote port " << remotePort
             << ": (errno " << errno << ") " << strerror(errno) << endl;
        throw;
      }
    }
  }
}


void
setSocketOptions(int skt)
{
  // See page 192 of UNIX Network Programming: The Sockets Networking API
  // Volume 1, Third Edition by W. Richard Stevens et. al. for info on using
  // ::setsockopt().

  // According to "Linux Socket Programming by Example" p. 319, we must call
  // setsockopt w/ SO_REUSEADDR option BEFORE calling bind.
  int so_reuseaddr = 1; // Enabled.
  int reuseAddrResult
    = ::setsockopt(skt, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr,
                   sizeof(so_reuseaddr));

  if (reuseAddrResult != 0) {
    cerr << "Failed to set reuse addr on socket.";
    throw;
  }

  // For every two hours of inactivity, a keepalive occurs.
  int so_keepalive = 1; // Enabled.  See page 200 for info on SO_KEEPALIVE.
  int keepAliveResult =
    ::setsockopt(skt, SOL_SOCKET, SO_KEEPALIVE, &so_keepalive,
                 sizeof(so_keepalive));

  if (keepAliveResult != 0) {
    cerr << "Failed to set keep alive on socket.";
    throw;
  }

  struct linger so_linger;

  so_linger.l_onoff = 1;  // Turn linger option on.
  so_linger.l_linger = 5; // Linger time in seconds. (See page 202)

  int lingerResult
    = ::setsockopt(skt, SOL_SOCKET, SO_LINGER, &so_linger,
                   sizeof(so_linger));

  if (lingerResult != 0) {
    cerr << "Failed to set linger on socket.";
    throw;
  }

  // Disable the Nagel algorithm on the command channel.  SOL_TCP is not
  // defined on FreeBSD
#ifndef SOL_TCP
#define SOL_TCP (::getprotobyname("TCP")->p_proto)
#endif

  unsigned int tcpNoDelay = 1;
  int noDelayResult
    = ::setsockopt(skt, SOL_TCP, TCP_NODELAY, &tcpNoDelay,
                   sizeof(tcpNoDelay));

  if (noDelayResult != 0) {
    cerr << "Failed to set tcp no delay on socket.";
    throw;
  }
}

void
buildAddr(sockaddr_in &addr, const std::string &ip, const ushort port)
{
  memset(&addr, 0, sizeof(sockaddr_in)); // Clear all fields.
  addr.sin_len    = sizeof(sockaddr_in);
  addr.sin_family = AF_INET;             // Set the address family
  addr.sin_port   = htons(port);         // Set the port.

  if (0 == inet_aton(ip.c_str(), &addr.sin_addr)) {
    cerr << "BuildAddr IP.";
    throw;
  }
};

void
deepBind(const int skt, const sockaddr_in &addr)
{
  // Bind the requested port.
  if (0 <= ::bind(skt, (sockaddr *)&addr, sizeof(addr))) {
    return;
  }

  // If the port is already in use, wait up to 100 seconds.
  int count = 0;
  ushort port = ntohs(addr.sin_port);

  while ((errno == EADDRINUSE) && (count < 10)) {
    clog << "Waiting for port " << port << " to become available..."
         << endl;
    ::sleep(10);
    ++count;
    if (0 <= ::bind(skt, (sockaddr*)&addr, sizeof(addr))) {
      return;
    }
  }

  cerr << "Error: failed to bind port.";
  throw;
}

这是 EINVAL 时的示例输出(它并不总是在这里失败,有时它会成功并在通过套接字发送的第一个数据包被加扰时失败):

Info: Command connect family: AF_INET len: 16 port: 2357 addr: 10.34.49.13
Error: Command connect failed on local port 2355 and remote port 2357 to remote host '10.34.49.13' family: AF_INET len: 16 port: 2357 addr: 10.34.49.13: Invalid argument.
    getsockopt => success

【问题讨论】:

  • 我们可以看看一些代码吗?
  • @blaze 我添加了代码示例。
  • 你的 sockaddr 初始化代码 (buildAddr) 是什么?我已经看到至少一个操作系统(虽然不记得是哪一个),如果你不初始化填充它会抱怨。此外,您确实应该传递 sizeof(sockaddr_in) 尽管我认为 IPv4 在几乎所有实现上它们都是相同的。
  • @tyranid buidAddr() 已在代码末尾附近提供。需要初始化哪些填充? sizeof() 哪里不对,我以为我是用 sizeof(sockaddr_in) 弄的?
  • 快速运行内核代码,我找到了EINVAL的原因: // sa_len != sizeof(AF_INET) // socket处于TIMEWAIT或DROPPED状态(看起来它可以这样的唯一方法是套接字重用)//内部错误,例如使用本地端口或本地 IP == 0 的部分绑定套接字 //一些 jail() 东西我不太明白 :) // 可能你应该尝试禁用所有套接字选项并重复bind() 出错,然后尝试一一启用它们只是为了检查它何时会中断。顺便说一句,这是什么投掷;陈述?是异常处理程序吗?

标签: sockets tcp porting freebsd connect


【解决方案1】:

有趣的是FreeBSD connect() manpage 没有列出EINVALA different BSD manpage 状态:

[EINVAL]    An invalid argument was detected (e.g., address_len is
            not valid for the address family, the specified
            address family is invalid).

根据来自不同 BSD 风格的不同文档,我敢冒险在 FreeBSD 中可能存在未记录的返回代码,例如参见 here

我的建议是在调用connect 之前打印出您的地址长度和sizeof 以及您的套接字地址结构的内容 - 这将有助于您找出问题所在。

除此之外,最好向我们展示用于设置连接的代码。这包括用于套接字地址的类型(struct sockaddrstruct sockaddr_in 等)、初始化它的代码以及对connect 的实际调用。这样会更容易提供帮助。

【讨论】:

    【解决方案2】:

    本地地址是什么?你默默地忽略了来自 bind(2) 的错误,这看起来不仅是错误的形式,而且可能导致这个问题开始!

    【讨论】:

    • 不,bind() 的返回不会被忽略:cerr
    • 啊,你是对的。我对你的早期回报和(我认为的)反转条件感到困惑。我理解将常量与函数或系统调用的返回值进行比较的基本原理,但如果您不小心在条件表达式中创建了一个裸赋值,每个现代编译器都会警告您,所以我希望人们只使用(syscall() != −1)
    【解决方案3】:

    我发现问题出在哪里,我首先得到一个 ECONNREFUSED,在 Linux 上我可以在短暂暂停后重试 connect(),一切都很好,但在 FreeBSD 上,以下重试 connect() 失败与 EINVAL。

    解决方案是在 ECONNREFUSED 进一步备份时开始重试回到上面的 test() 定义的开头。通过此更改,代码现在可以正常工作了。

    【讨论】:

      猜你喜欢
      • 2017-10-17
      • 2013-05-15
      • 2011-04-22
      • 1970-01-01
      • 2011-07-10
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      • 2017-07-05
      相关资源
      最近更新 更多