1

在 Freepascal 中,如何循环访问一系列 IP 地址?

任何可以处理此问题的 ip 特定内容的单位?我试过一种叫做inetaux,但它有缺陷并且不起作用。

4

2 回答 2

1

由于 IP 地址只是一个拆分为 4 个字节的 32 位数字,因此您可以简单地迭代一个整数并使用实例absolute指令将此迭代器拆分为 4 个字节:

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;

或者您可以对按位移位运算符执行相同的操作,这需要做更多的工作。例如,与上面相同的示例如下所示:

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;
于 2013-03-16T13:06:23.287 回答
1

我以更 FPC 的风格重写了 TLama 的示例。请注意,这也应该是字节顺序安全的:

{$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;
于 2013-03-19T15:11:41.947 回答