简体   繁体   English

如何检测端口是否已经在服务器端使用(在Windows的C ++中)?

[英]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). 这当然是一个普遍的问题,但不是这个意思(Windows,服务器端,接受多重连接)。

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... , bind doesn't return a SOCKET_ERROR status as I expected. 在我放置//HERE...的行上, bind不会返回我期望的SOCKET_ERROR状态。 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();

Don't set SO_REUSEADDR . 不要设置SO_REUSEADDR Then bind() will fail if the address is already in use and WSAGetLastError() will return WSAEADDRINUSE . 然后,如果该地址已在使用中,则bind()将失败,并且WSAGetLastError()将返回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. 还要注意,如果IP地址不同,则两个processen仍可以绑定到同一端口,例如,一个进程绑定到localhost ,另一个进程绑定到LAN网络地址。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM