在使用Socks编程时,有时需要判断某个端口是否被占用,也就是是否被其它程序使用。
uses Winsock;
function IsPortUsed(const aPort: Integer): Boolean;
var
_vSock : TSocket;
_vWSAData : TWSAData;
_vAddrIn : TSockAddrIn;
begin
Result := False;
if WSAStartup(MAKEWORD(2, 2), _vWSAData) = 0 then
begin
_vSock := Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
try
if _vSock <> SOCKET_ERROR then
begin
_vAddrIn.sin_family := AF_INET;
_vAddrIn.sin_addr.S_addr := htonl(INADDR_ANY);
_vAddrIn.sin_port := htons(APort);
if Bind(_vSock, _vAddrIn, SizeOf(_vAddrIn)) <> 0 then
if WSAGetLastError = WSAEADDRINUSE then
Result := True;
end;
finally
CloseSocket(_vSock);
WSACleanup();
end;
end;
end;
阅读(3486) | 评论(2) | 转发(0) |