Sandburg
Sandburg

Reputation: 865

How to detect if a port is already in use server side (in C++ on windows)?

It's certainly a common question, but not in this terms (windows, server side, accept multi connexion).

My goal is to accept to start a server listing on a port for multiple connections only if before that the port is detected "unused".

At the line where I put //HERE..., binddoesn't return a SOCKET_ERROR status as I expected. Maybe I'm doing something wrong.

How to detect that my port is not in use by some other app?

Here is the status of the port before running (it is used)

netstat -an
  TCP    127.0.0.1:2005         0.0.0.0:0              LISTENING

I hope this snippet is sufficent to explain what I'm doing, it's a merge of several steps.

WSADATA WSAData;
int err = WSAStartup(MAKEWORD(2, 2), &WSAData);

SOCKADDR_IN sin;
socklen_t recsize = sizeof(sin);
int one = 1;

SOCKADDR_IN* csin;
SOCKET csock = INVALID_SOCKET;
socklen_t crecsize = sizeof(SOCKADDR_IN);
int sock_err;

if (m_socket != INVALID_SOCKET)
{
    memset(&sin, 0, recsize);
    if(m_blocal)
        sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK);   
    else
        sin.sin_addr.s_addr = htonl(INADDR_ANY);

    sin.sin_family = AF_INET;                       
    sin.sin_port = htons(m_iPort);

    setsockopt(m_socket, SOL_SOCKET, SO_REUSEADDR, (const char*)&one, sizeof(int));
    sock_err = bind(m_socket, (SOCKADDR*)&sin, recsize);
    //HERE I want to be sure no one else runs on this port

    //rest of the code using: select(m_socket + 1, &rd, &wr, &er, &timeout);
}

closesocket(m_socket);
WSACleanup();

Upvotes: 0

Views: 1967

Answers (1)

rveerd
rveerd

Reputation: 4006

Don't set SO_REUSEADDR. Then bind() will fail if the address is already in use and WSAGetLastError() will return WSAEADDRINUSE.

Also note that two processen can still bind to the same port if the IP addresses are different, for example, one process binding to localhost and another process binding to the LAN network address.

Upvotes: 2

Related Questions