Search code examples
delphidelphi-7

How to get Hostname of each ip address in given input range


My question is how to get hostnames of all ip addresses which are betwwen given ip range. I know the function for getting hostnames from ip address but I just want to know how to get ip addresses from given range

Example:

  • input is given in two edixboxes in first '0.0.0.0' and in second '1.1.1.1' so I want all ip addresses between this range ...

I tried my best but it is too complex. Is there any function or command to get ip addresses between given range?

function IPAddrToName(IPAddr: string): string;
var
  SockAddrIn: TSockAddrIn; 
  HostEnt: PHostEnt;
  WSAData: TWSAData;
begin
  WSAStartup($101, WSAData);
  SockAddrIn.sin_addr.s_addr := inet_addr(PChar(IPAddr));
  HostEnt := GetHostByAddr(@SockAddrIn.sin_addr.S_addr, 4, AF_INET);
  if HostEnt<>nil then
  begin
    Result := StrPas(Hostent^.h_name)
  end
  else
  begin
    Result := '';
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption := IPAddrToName(Edit1.Text);
end;

Solution

  • Use inet_addr to convert the dotted text form of the IP address into an unsigned 32 bit integer. Do that for both addresses. And then loop from one to the other with a simple for loop.

    var
      ip, ip1, ip2: Cardinal;
    ....
    ip1 := ntohl(inet_addr(PChar(edit1.Text)));
    ip2 := ntohl(inet_addr(PChar(edit2.Text)));
    for ip := min(ip1,ip2) to max(ip1,ip2) do
      // use ip
    

    I skipped any validation. You would not. Note also that inet_addr returns a value with network byte order. For the loop to work we must switch to host byte order.

    This only really makes sense for ranges that span an entire subnet mask. For instance it makes sense to enumerate all addresses between 192.168.1.0 and 192.168.1.255. But it makes no sense at all to ask for all addresses between 1.0.0.0 and 1.1.1.1 as per the example in your question.

    So I think you'll need to reconsider and think about iterating over all addresses in a network.

    You also ask, in comments, how to convert from numeric form to dotted form. Use inet_ntoa for that.

    var 
      addr: in_addr;
      dottedAddr: string;
    ....
    addr.S_addr := htonl(ip);
    dottedAddr := inet_ntoa(addr);