windows api判断端口是否被占用
时间: 2024-01-20 14:03:19 浏览: 142
在Windows API中,可以使用`GetTcpTable()`函数和`GetUdpTable()`函数来获取当前系统中正在使用的TCP和UDP端口信息。通过遍历这些信息,可以判断指定的端口是否被占用。
以下是使用`GetTcpTable()`函数和`GetUdpTable()`函数判断指定端口是否被占用的示例代码:
```c++
#include <winsock2.h>
#include <iphlpapi.h>
#include <stdio.h>
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
bool IsPortInUse(USHORT port, bool isTCP)
{
PMIB_TCPTABLE pTcpTable;
PMIB_UDPTABLE pUdpTable;
DWORD dwSize = 0;
DWORD dwRetVal = 0;
bool bInUse = false;
if (isTCP)
{
pTcpTable = (PMIB_TCPTABLE)malloc(sizeof(MIB_TCPTABLE));
if (pTcpTable == NULL)
{
printf("Error allocating memory\n");
return false;
}
dwSize = sizeof(MIB_TCPTABLE);
dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE);
if (dwRetVal == ERROR_INSUFFICIENT_BUFFER)
{
free(pTcpTable);
pTcpTable = (PMIB_TCPTABLE)malloc(dwSize);
if (pTcpTable == NULL)
{
printf("Error allocating memory\n");
return false;
}
dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE);
}
if (dwRetVal != NO_ERROR)
{
printf("GetTcpTable failed with error %d\n", dwRetVal);
free(pTcpTable);
return false;
}
for (DWORD i = 0; i < pTcpTable->dwNumEntries; i++)
{
if (pTcpTable->table[i].dwLocalPort == htons(port))
{
bInUse = true;
break;
}
}
free(pTcpTable);
}
else
{
pUdpTable = (PMIB_UDPTABLE)malloc(sizeof(MIB_UDPTABLE));
if (pUdpTable == NULL)
{
printf("Error allocating memory\n");
return false;
}
dwSize = sizeof(MIB_UDPTABLE);
dwRetVal = GetUdpTable(pUdpTable, &dwSize, TRUE);
if (dwRetVal == ERROR_INSUFFICIENT_BUFFER)
{
free(pUdpTable);
pUdpTable = (PMIB_UDPTABLE)malloc(dwSize);
if (pUdpTable == NULL)
{
printf("Error allocating memory\n");
return false;
}
dwRetVal = GetUdpTable(pUdpTable, &dwSize, TRUE);
}
if (dwRetVal != NO_ERROR)
{
printf("GetUdpTable failed with error %d\n", dwRetVal);
free(pUdpTable);
return false;
}
for (DWORD i = 0; i < pUdpTable->dwNumEntries; i++)
{
if (pUdpTable->table[i].dwLocalPort == htons(port))
{
bInUse = true;
break;
}
}
free(pUdpTable);
}
return bInUse;
}
int main()
{
USHORT port = 80;
bool isTCP = true;
if (IsPortInUse(port, isTCP))
{
printf("Port %d is in use\n", port);
}
else
{
printf("Port %d is not in use\n", port);
}
return 0;
}
```
在上面的示例代码中,`IsPortInUse()`函数用于判断指定的端口是否被占用,其中`port`参数为指定的端口号,`isTCP`参数表示是否为TCP端口。如果端口被占用,该函数返回`true`,否则返回`false`。
阅读全文