How to Bind a TServerSocket to a specific IP address

本秂侑毒 提交于 2019-12-24 05:52:00

问题


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.


回答1:


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;


来源:https://stackoverflow.com/questions/40094158/how-to-bind-a-tserversocket-to-a-specific-ip-address

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!