The Road to Delphi

Delphi – Free Pascal – Oxygene

Checking if a TCP port is Open using Delphi and Winsocks

9 Comments

Many times we need to know if a TCP port is open or not, here I leave a function to perform this task using winsock.

Code tested in Delphi 7, 2007 and 2010.


uses
  Winsock;

function PortTCP_IsOpen(dwPort : Word; ipAddressStr:AnsiString) : boolean;
var
  client : sockaddr_in;
  sock   : Integer;

  ret    : Integer;
  wsdata : WSAData;
begin
 Result:=False;
 ret := WSAStartup($0002, wsdata); //initiates use of the Winsock DLL
  if ret<>0 then exit;
  try
    client.sin_family      := AF_INET;  //Set the protocol to use , in this case (IPv4)
    client.sin_port        := htons(dwPort); //convert to TCP/IP network byte order (big-endian)
    client.sin_addr.s_addr := inet_addr(PAnsiChar(ipAddressStr));  //convert to IN_ADDR  structure
    sock  :=socket(AF_INET, SOCK_STREAM, 0);    //creates a socket
    Result:=connect(sock,client,SizeOf(client))=0;  //establishes a connection to a specified socket
  finally
  WSACleanup;
  end;
end;

see this sample of usage

begin
 if PortTCP_IsOpen(3306,'127.0.0.1') then 
  DoMyStuff();
end;

Author: Rodrigo

Just another Delphi guy.

9 thoughts on “Checking if a TCP port is Open using Delphi and Winsocks

  1. Hi,

    Your title is “testing if open port” so if only “testing” I understand that purpose is not to stay connected, so may be you should add a disconnect if connect is successfull.

    regards.

  2. This is certainly shorter and easier to understand:

    function TForm7.PortIsOpen(const APort: Integer; const AAddress: string):
        Boolean;
    var
      LTcpClient: TIdTCPClient;
    begin
      LTcpClient := TIdTCPClient.Create(nil);
      try
        try
          LTcpClient.Host := AAddress;      //which server to test
          LTcpClient.Port := APort;         //which port to test
          LTcpClient.ConnectTimeout := 200; //assume a port to be clodes if it does not respond within 200ms (some ports will immediately reject, others are using a "stealth" mechnism)
          LTcpClient.Connect;               //try to connect
          result := true;                   //port is open
        except
          result := false;
        end;
      finally
        freeAndNil(LTcpClient);
      end;
    end;
    
    procedure TForm7.Button1Click(Sender: TObject);
    begin
      if PortIsOpen(1234, '127.0.0.1') then
        ShowMessage('OPEN')
      else
        ShowMessage('NOT OPEN');
    end;
    
    
  3. Rodrigo, thanks for this very useful post. What I also particular like about your solution, is that does not use any 3-rd party component, making it usable in any (future) Delphi version.

  4. hi many thanks for your post.
    do you know any solution for testing internet connection availability in delphi?
    it means that internet is available or not , disconnect?
    thanks

  5. This is great, but only one problem. How the heck to I shrink the timeout from 20 seconds down to 2 seconds ???

  6. Interesting. Okay, I’ll definitely check that out. I appreciate the answer.

  7. Sir Rodrigo, how to check if a proxy is a proxy server and a port is opened or close with Delphi (Seattle)?
    My goal is to check list proxies to know are they active or not, and are their port close / open.
    As you can see, like the site http://ping (dot) eu did great the job.

    I couldn’t find anywhere a tutorial how to start with, include in stackoverflow.
    Is it possible to achieve this using indyHttp? or something else?
    Your help would be highly aprreciated.

    Regards from your fans here, github and StackOverFlow.

Leave a comment