Pages

Monday, December 26, 2011

How to check if TCP Port is Open

When we create an application that open port using winsock, we need to anticipate that user may execute our application twice in order no port conflict error. So we need to check whether that port is already opened at OnCreate event of the form. Below is the function to check that :
uses
  Winsock;

function PortIsOpen(dwPort : Word; ipAddressStr:AnsiString) : boolean;
var
  client : sockaddr_in;
  sock   : Integer;
  ret    : Integer;
  wsdata : WSAData;
begin
 Result:=False;
 ret := WSAStartup($0002, wsdata);
  if ret<>0 then exit;
  try
    client.sin_family      := AF_INET;  
    client.sin_port        := htons(dwPort); 
    client.sin_addr.s_addr := inet_addr(PAnsiChar(ipAddressStr)); 
    sock  :=socket(AF_INET, SOCK_STREAM, 0);    
    Result:=connect(sock,client,SizeOf(client))=0;
  finally
  WSACleanup;
  end;
end;
 
To use that function, write down this code in OnCreate form event
procedure TForm1.FormCreate(Sender: TObject);
begin
if PortIsOpen(1521,'127.0.0.1') then
   showmessage('Port is already opened');
end;

No comments:

Post a Comment

Don't Forget To Join Our Community
×
Widget