title: getsockopt doesn't return error when trying to connect to a closed port
body: <p>I try to use <code>connect()</code> &amp; <code>O_NONBLOCK</code> to connect to a port in localhost asynchronously. In order to get the connect result, I use <code>getsockopt</code> to check the socket error status. I can sure no one listen to this port, so <code>ECONNREFUSED</code> should be returned. But in my test, this error may not be returned in some cases.</p>
  <p>My test program:</p>
  <pre><code>int main() {
    uint64_t p = 0;
    while (1) {
      int fd = ::socket(PF_INET, SOCK_STREAM, 0);
      assert(fd &gt; 0);
      int flags = ::fcntl(fd, F_GETFL, 0);
      flags |= O_NONBLOCK;
      int ret = ::fcntl(fd, F_SETFL, flags);
      assert(ret != -1);
      sockaddr_in addr;
      bzero(&amp;addr, sizeof(sockaddr_in));
      addr.sin_family = AF_INET;
      addr.sin_port = htons(25400);
      addr.sin_addr.s_addr = inet_addr(&quot;127.0.0.1&quot;);
      ret = ::connect(fd, (sockaddr *)&amp;addr, sizeof(sockaddr));
      assert(ret != 0);
      switch (errno) {
        case EINPROGRESS:
        case EINTR:
        case EISCONN:
          break;
        default:
          assert(false);
      }
      int epfd = epoll_create1(0);
      assert(epfd &gt; 0);
      epoll_event ev;
      ev.events = EPOLLOUT;
      ev.data.fd = fd;
      ret = epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &amp;ev);
      assert(ret == 0);
      epoll_event events;
      auto nfds = epoll_wait(epfd, &amp;events, 1, -1);
      assert(nfds == 1);
      assert(events.data.fd == fd);
      int err;
      socklen_t optlen = static_cast&lt;socklen_t&gt;(sizeof err);
      ret = ::getsockopt(fd, SOL_SOCKET, SO_ERROR, &amp;err, &amp;optlen);
      assert(ret == 0);
      assert(err != 0);
      ::close(fd);
      ::close(epfd);
      if (p++ % 10000 == 0) {
        std::cout &lt;&lt; p &lt;&lt; std::endl;
      }
    }
  }
  </code></pre>
  <p><code>assert(err != 0);</code> will be triggered.</p>