void Device::connect()

in gloo/transport/uv/device.cc [246:295]


void Device::connect(
    const Address& local,
    const Address& remote,
    std::chrono::milliseconds timeout,
    ConnectCallback fn) {
  int rv;

  // The remote side of a pair will be called with the same
  // addresses, but in reverse. There should only be a single
  // connection between the two, so we pick one side as the listener
  // and the other side as the connector.
  const auto& ss1 = local.getSockaddr();
  const auto& ss2 = remote.getSockaddr();
  GLOO_ENFORCE_EQ(ss1.ss_family, ss2.ss_family);
  const int family = ss1.ss_family;
  if (family == AF_INET) {
    const struct sockaddr_in* sa = (struct sockaddr_in*)&ss1;
    const struct sockaddr_in* sb = (struct sockaddr_in*)&ss2;
    const auto addrlen = sizeof(struct sockaddr_in);
    rv = memcmp(&sa->sin_addr, &sb->sin_addr, sizeof(struct in_addr));
    if (rv == 0) {
      rv = sa->sin_port - sb->sin_port;
    }
  } else if (family == AF_INET6) {
    const struct sockaddr_in6* sa = (struct sockaddr_in6*)&ss1;
    const struct sockaddr_in6* sb = (struct sockaddr_in6*)&ss2;
    const auto addrlen = sizeof(struct sockaddr_in6);
    rv = memcmp(&sa->sin6_addr, &sb->sin6_addr, sizeof(struct in6_addr));
    if (rv == 0) {
      rv = sa->sin6_port - sb->sin6_port;
    }
  } else {
    FAIL("Unknown address family: ", family);
  }

  // If both sides of the pair use the same address and port, they are
  // sharing the same device instance. This happens in tests. Compare
  // sequence number to allow pairs to connect.
  if (rv == 0) {
    rv = local.getSeq() - remote.getSeq();
  }

  if (rv < 0) {
    connectAsListener(local, timeout, std::move(fn));
  } else if (rv > 0) {
    connectAsInitiator(remote, timeout, std::move(fn));
  } else {
    FAIL("Cannot connect to self");
  }
}