用C++ builder编写查询端口被占用情况该如何下手[再次提问]
如题,上次一兄台提示用一个IdTCPServer组件,但是该组件发现端口被占用会弹出出错对话框,我不想出现这种状况。请问如何避免。另,还有其它轻量级的办法吗?我只是想查询端口是否被占用。
谢谢了!
[解决办法]
#define PORT_INUSE 1 // 端口被占用
#define PORT_FREE 2 // 端口未被占用
#define PORT_ERROR 3 // 出错
int TestPort(unsigned short usPort) {
// Create a SOCKET for listening for incoming connection requests
SOCKET ListenSocket;
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET)
return PORT_ERROR;
// The sockaddr_in structure specifies the address family,
// IP address, and port for the socket that is being bound.
sockaddr_in service;
service.sin_family = AF_INET;
service.sin_addr.s_addr = inet_addr("127.0.0.1");
service.sin_port = htons(usPort);
// Bind the socket.
int idResult;
if ( bind(ListenSocket, (SOCKADDR*)&service, sizeof(service)) == 0 )
idResult = PORT_FREE;
else if ( WSAGetLastError() == WSAEADDRINUSE )
idResult = PORT_INUSE;
else
idResult = PORT_ERROR;
closesocket(ListenSocket);
return idResult;
}