我使用以下代码检查端口是否可用:
bool ClassA::CheckPortTCP(short int dwPort , char *ipAddressStr)
{
struct sockaddr_in client;
int sock;
client.sin_family = AF_INET;
client.sin_port = htons(dwPort);
client.sin_addr.S_un.S_addr = inet_addr(ipAddressStr);
sock = (int) socket(AF_INET, SOCK_STREAM, 0);
int result = connect(sock, (struct sockaddr *) &client,sizeof(client));
// change to result == 0 -> failure in writing code too quick ;-)
if (result = 0) return true; // port is active and used
else return false;
}
问题是如果端口打开但未连接检查失败!如何轻松检查端口是否可用(未侦听,未连接)?
例如端口 21111(netstat 的输出)-> 我的函数无法识别该端口不是空闲的
TCP 0.0.0.0:21111 xxxxDUMMYxxxx:0 LISTENING
谢谢