I implemented a simple IP address banning system in one of my Web Services.

In the Web Services code, this is what I had to do.

  1. First, I use the GetSOAPWebModule function to retrieve the SOAP Web Module.
  2. I then retrieve the IP address.
  3. I create an instance of the TIdNetworkCalculator.
  4. Parse the IP string. The IP string may consist only of xxx.xxx.xxx.xxx or, it may consist of xxx.xxx.xxx.xxx, yyy.yyy.yyy.yyy.
  5. Check the IP against the banned addresses.
  6. If the banned address appears in the IP, then raise a SOAP fault.
  7. PS: I'm not using “Your IP address is banned“ because I don't want to tip those guys off!

var
  WebModule: TWebModule;
  Request: TWebRequest;
  TempIP, IP: string;
  IPNetwork: TIdNetworkCalculator;
  Banned1, Banned2: Boolean;
begin
  WebModule := GetSOAPWebModule;
  Request := WebModule.Request;
  IP := Request.GetFieldByName('HTTP_X_FORWARDED_FOR');
  if IP = '' then
    IP := Request.RemoteAddr;
  IPNetwork := TIdNetworkCalculator.Create(nil);
  try
   while Length(IP)>0 do
      begin
        TempIP := Fetch(IP, ', ');
        IPNetwork.NetworkAddress.AsString := '202.12.94.0';
        IPNetwork.NetworkMaskLength := 23;
        Banned1 := IPNetwork.IsAddressInNetwork(TempIP);

        IPNetwork.NetworkAddress.AsString := '172.16.0.0';
        IPNetwork.NetworkMaskLength := 12;
        Banned2 := IPNetwork.IsAddressInNetwork(TempIP);
        if Banned1 or Banned2 then
          raise ERemotableException.Create('Your domain address is banned.');
      end;
  finally
    IPNetwork.Free;
  end;
end;