Search code examples
delphiip-addressserversocket

How to Bind a TServerSocket to a specific IP address


Does any one know any way to bind a Delphi TServerSocket component to accept requests only on a specific local address?

The server has several IPs but it is requires that server application to accept requests on one IP only when its running.


Solution

  • TServerSocket does not directly expose the feature you are asking for, however it is doable with a little workaround.

    You need to derive a new class from TServerSocket in order to gain access to the protected TAbstractSocket.Address property. That is the value that TServerSocket binds to. Since the property is not normally accessible, it remains an empty string, which is the same as binding to 0.0.0.0 (aka INADDR_ANY, ie all local IPs).

    Once you can access the Address property, you can set it to whatever IP you want prior to activating the server, and the server will bind accordingly.

    For example:

    type
      TServerSocketAccess = class(TServerSocket)
      end;
    
    TServerSocketAccess(ServerSocket1).Address := '192.168.0.1';
    ServerSocket1.Active := True;