Why can bind () sometimes give EADDRINUSE when connecting the other side?

In my C ++ application, I use :: bind () for a UDP socket, but in rare cases, after reconnecting due to a lost connection, I get errno EADDRINUSE even after many attempts. The other side of the UDP connection, which will receive data reconnected with a fine and wait for select () to indicate that there is something to read.

I assume this means that the local port is being used. If true, how can I leak the local port so that the other side connects to it normally? The real problem here is that the other side is connected normally and is waiting, but this side is stuck on EADDRINUSE.

- Edit -

Here is a code snippet showing that I am already doing SO_REUSEADDR in my TCP juice and not in this UDP socket for which I have a problem:

// According to "Linux Socket Programming by Example" p. 319, we must call
// setsockopt w/ SO_REUSEADDR option BEFORE calling bind.
// Make the address is reuseable so we don't get the nasty message.
int so_reuseaddr = 1; // Enabled.
int reuseAddrResult
  = ::setsockopt(getTCPSocket(), SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr,
                 sizeof(so_reuseaddr));

Here is my code for closing a UDP socket:

void
disconnectUDP()
{
  if (::shutdown(getUDPSocket(), 2) < 0) {
    clog << "Warning: error during shutdown of data socket("
         << getUDPSocket() << "): " << strerror(errno) << '\n';
  }
  if (::close(getUDPSocket()) < 0 && !seenWarn) {
    clog << "Warning: error while closing data socket("
         << getUDPSocket() << "): " << strerror(errno) << '\n';

  }
}
+3
source share
2 answers

In UDP, there is no such thing as a lost connection, because there is no connection. You can lose the sent packets, that's all.

Do not reconnect, just reuse existing ones fd.

+2
source

Yes, it is normal. You need to set the socket SO_REUSEADDRbefore binding, for example, on * nix:

int sock = socket(...);

int yes = 1;
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));

If you have separate code that reconnects, creating a new socket, install it on this one as well. This is simply due to the default behavior of the OS - a port on a broken socket does not work for a while.

[EDIT] UDP. , , .

+4

All Articles