Domanda

In Freepascal, how can I loop through a range of IP addresses?

Any units that do ip specific stuff that might handle this? I've tried one called inetaux, but it's flawed and doesn't work.

È stato utile?

Soluzione

As IP address is just a 32-bit number splitted into 4 bytes, you can simply iterate an integer and use for instance absolute directive to split this iterator into the 4 bytes:

type
  TIPAddress = array[0..3] of Byte;

procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  I: Integer;
  IPAddress: TIPAddress absolute I;
begin
  // loop in some range of IP addresses, here e.g. from 127.0.0.1 to 127.0.1.245
  for I := 2130706433 to 2130706933 do
  begin
    // now you can build from that byte array e.g. well known IP address string
    S := IntToStr(IPAddress[3]) + '.' + IntToStr(IPAddress[2]) + '.' +
      IntToStr(IPAddress[1]) + '.' + IntToStr(IPAddress[0]);
    // and do whatever you want with it...
  end;
end;

Or you can do the same with bitwise shift operator, which needs a little more work to do. For instance the same example as above would look like this:

type
  TIPAddress = array[0..3] of Byte;

procedure TForm1.Button1Click(Sender: TObject);
var
  S: string;
  I: Integer;
  IPAddress: TIPAddress;
begin
  // loop in some range of IP addresses, here e.g. from 127.0.0.1 to 127.0.1.245
  for I := 2130706433 to 2130706933 do
  begin
    // fill the array of bytes by bitwise shifting of the iterator
    IPAddress[0] := Byte(I);
    IPAddress[1] := Byte(I shr 8);
    IPAddress[2] := Byte(I shr 16);
    IPAddress[3] := Byte(I shr 24);
    // now you can build from that byte array e.g. well known IP address string
    S := IntToStr(IPAddress[3]) + '.' + IntToStr(IPAddress[2]) + '.' +
      IntToStr(IPAddress[1]) + '.' + IntToStr(IPAddress[0]);
    // and do whatever you want with it...
  end;
end;

Altri suggerimenti

I rewrote TLama's sample in a more FPC style. Note that this should be endianess safe too:

{$mode Delphi}

uses sockets;
procedure Button1Click(Sender: TObject);
var
  S: string;
  I: Integer;
  IPAddress: in_addr;
begin
  // loop in some range of IP addresses, here e.g. from 127.0.0.1 to 127.0.1.24
  for I := 2130706433 to 2130706933 do
  begin
    IPAddress.s_addr:=i;
    s:=HostAddrToStr(IPAddress);
     ....
  end;
end;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top