2010. június 20., vasárnap

Delphi .NET: Get computer IP address


Problem/Question/Abstract:

How to get the list of the computer IP addresses

Answer:

One of the many namespaces in the Base Class Framework is the System.Net namespace. It provides a simple programming interface to many of the protocols found on the network today. One of the classes of the namespace is DNS which provides simple domain name resolution functionality.

{$APPTYPE CONSOLE}
program getip;

uses
  System,
  System.Net,
  Borland.Delphi.SysUtils;

var
  strMachineName: string;
  ipHost: IPHostEntry;
  ipAddr: array of IPAddress;
  count: Integer;
begin

  //Get the Host Name
  strMachineName := Dns.GetHostName();
  Console.WriteLine('Host Name: ' + strMachineName);

  //Get the Host by Name
  ipHost := Dns.GetHostByName(strMachineName);

  //You can also query the DNS database for info on a
  //website like users.chello.be
  //In that case replace the above line as:
  //ipHost := Dns.GetHostByName('users.chello.be')

  //Get the list of addresses associated with the host in an array
  ipAddr := ipHost.AddressList;

  //Enumerate the IP Addresses
  for count := 0 to length(ipAddr) - 1 do

    Console.Write(Format('IP Addresses %d: %s ', [count, ipAddr[count].ToString]));
end.

Nincsenek megjegyzések:

Megjegyzés küldése