检查TCP端口是否可用(未监听或未连接) [英] Check if TCP port is available (not listening or connected)

查看:760
本文介绍了检查TCP端口是否可用(未监听或未连接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码检查端口是否可用:

I use following code to check if a port is available or not:

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; 
}  

问题是端口是否打开但未连接,检查失败!如何轻松检查端口是否可用(未监听,未连接)?

The problem is if the port is opened but not connected the check failed! How can I easily examine that the port is available (not listening, not connected)?

例如端口21111(netstat的输出)->我的函数无法识别该端口不可用

e.g. port 21111 (output of netstat) -> my function doesn't recognize that the port is not free

TCP    0.0.0.0:21111          xxxxDUMMYxxxx:0       LISTENING

Thx

推荐答案

您有两个错误:第一个错误是在if语句中,您将赋值分配为result零.另一个是connect在连接失败时返回-1,如果成功连接则返回非负值.

You have two errors: The first is that in the if statement you assign zero to result. The other is that connect returns -1 on failure to connect, and a non-negative value if it manages to connect.

还有一个问题,如果您设法连接,就不会关闭该连接.

There is also a problem that if you manage to connect, you don't close that connection.

这篇关于检查TCP端口是否可用(未监听或未连接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆