?
Solved

Network IP Static / Dynamic ?

Posted on 2010-09-15
12
Medium Priority
?
588 Views
Last Modified: 2013-11-23
Hi,

How can I recognise that the LAN IP is set to Dynamic / Static
I use Delphi 2007

Regards
Allan

0
Comment
Question by:Allan_Fernandes
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
  • 2
  • +1
12 Comments
 
LVL 25

Accepted Solution

by:
epasquier earned 2000 total points
ID: 33689316
This object will get your TCP/IP Configuration.

Check the DHCPEnabled property of each Adapter (network card)
{
  IPINFO v0.1

  Implements some classes to obtain informations
  about the network configuration and network adapters.
  Based on the work of http://www.whirlwater.com/

  This materia is provied "as is"
  without any warranty of any kind.

  By Leonardo Perria - 2003
  leoperria@tiscali.it

  Very poor implementation at the moment....be patient.
  
// UPDATED BY E.PASQUIER - 2010 - epasquier@tmtsa.fr
// - Included Global Network Parameters in TIPInfo
// - provided default properties for TAdapter & TIPInfo
// - compatible with new Delphi generation (Unicode)
}

unit IPInfo;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls,Contnrs, IPHelperDef;

type

  TInfoIPAddress=class
  private
    FAddress:AnsiString;
    FNetmask:AnsiString;

  public
    constructor Create(Addr : PIPAddrString);
    destructor Destroy; override;
    property Address:AnsiString read FAddress;
    property Netmask:AnsiString read FNetmask;
    function asString() : AnsiString;
  end;


  TAdapter=class
  private
    FComboIndex: integer;
    FName: AnsiString;
    FDescription: AnsiString;
    FHWAddressLength : Integer;
    FHWAddress: AnsiString;
    FAIndex: integer;
    FAType: integer;  // see IPIfCons.H
    FDHCPEnabled: boolean;
    FCurrentIPAddress : TInfoIPAddress;
    FIPAddressList: TObjectList;
    FGatewayList : TObjectList;

    FDHCPServer : TInfoIPAddress;
    FHaveWINS : boolean;
    FPrimaryWINSServer : TInfoIPAddress;
    FSecondaryWINSServer : TInfoIPAddress;

//    LeaseObtained       : Integer;
//    LeaseExpires        : Integer;

    function GetIPAddress(index : integer) : TInfoIPAddress;
    function GetMaxIPAddresses() : integer;
    function GetGateway(index : integer) : TInfoIPAddress;
    function GetMaxGateways() : integer;

  public
    constructor Create(adapterInfo:PIPAdapterInfo);
    destructor Destroy; override;
    property Name: AnsiString read FName;
    property Description : AnsiString read FDescription;
    property ComboIndex : integer read FComboIndex;
    property HWAddressLength : Integer read FHWAddressLength;
    property HWAddress: AnsiString read FHWAddress;
    property AIndex: integer read FAIndex;
    property AType: integer read FAType;
    property DHCPEnabled: boolean read FDHCPEnabled;
    property CurrentIPAddress : TInfoIPAddress read FCurrentIPAddress;
    property MaxIPAddresses : integer read GetMaxIPAddresses;
    property IPAddresses[index : integer] : TInfoIPAddress read GetIPAddress; default; // IPAddresses is the default property of TAdapter
    // Adapter[0] <=equivalent=> Adapter.IPAddresses[0]
    property MaxGateways : integer read GetMaxGateways;
    property Gateways[index : integer] : TInfoIPAddress read GetGateway;
    property DHCPServer : TInfoIPAddress read FDHCPServer;
    property HaveWINS : boolean read FHaveWINS;
    property PrimaryWINSServer : TInfoIPAddress read FPrimaryWINSServer;
    property SecondaryWINSServer : TInfoIPAddress read FSecondaryWINSServer;

  end;

  TIPInfo=class(TObject)
  private
    FAdapters: TObjectList;
    FHostName:AnsiString;
    FDomainName:AnsiString;
    FCurrentDNSServer:AnsiString;
    FDNS:TStringList;
    FScopeId:AnsiString;
    FEnableRouting:Boolean;
    FEnableProxy:Boolean;
    FEnableDNS:Boolean;

    function getMaxAdapters(): integer;
    function GetAdapter(index:integer) : TAdapter;

    function GetDNSCount:integer;
    function GetDNS(i:integer):AnsiString;
  public
    Constructor Create;
    Destructor Destroy;override;
    property Adapters[index: Integer]: TAdapter read GetAdapter; default; // Adapters is the default property of TIPInfo
    // IPInfo[2] <=equivalent=> IPInfo.Adapters[2]
    property MaxAdapters:integer read getMaxAdapters;

    property HostName:AnsiString         read FHostName;
    property DomainName:AnsiString       read FDomainName;
    property CurrentDNSServer:AnsiString read FCurrentDNSServer;
    property DNSCount:integer        read GetDNSCount;
    property DNS[i:integer]:AnsiString   read GetDNS;
    property ScopeId:AnsiString          read FScopeId;
    property EnableRouting:Boolean   read FEnableRouting;
    property EnableProxy:Boolean     read FEnableProxy;
    property EnableDNS:Boolean       read FEnableDNS;
  end;


implementation

constructor TInfoIPAddress.Create(Addr : PIPAddrString);
begin
  if Addr<>nil then begin
    FAddress:=Addr^.IPAddress;
    FNetmask:=Addr^.IPMask;
  end
  else begin
    FAddress:='';
    FNetmask:='';
  end;
end;

function TInfoIPAddress.asString() : AnsiString;
begin
  if (FAddress='') and (FNetmask='') then
    Result:=''
  else
    Result:=FAddress+'/'+FNetmask;
end;

destructor TInfoIPAddress.Destroy;
begin
  inherited;
end;


constructor TAdapter.Create(adapterInfo:PIPAdapterInfo);

  Function MACToStr(ByteArr : PByte; Len : Integer) : AnsiString;
  Begin
    Result := '';
    While (Len > 0) do Begin
      Result := Result+IntToHex(ByteArr^,2)+':';
      ByteArr := Pointer(Integer(ByteArr)+SizeOf(Byte));
      Dec(Len);
    End;
    SetLength(Result,Length(Result)-1); { remove last dash }
  End;

  procedure PopulateAddressList(Addr : PIPAddrString; List: TObjectList);
  begin
    List.Clear;
    While (Addr <> nil) do Begin
      List.Add(TInfoIPAddress.Create(Addr));
      Addr := Addr^.Next;
    End;
  end;

  { TODO: Implementare i LeaseTime

  Function TimeTToDateTimeStr(TimeT : Integer) : AnsiString;
  Const UnixDateDelta = 25569;
  Var
    DT  : TDateTime;
    TZ  : TTimeZoneInformation;
    Res : DWord;

  Begin
    If (TimeT = 0) Then Result := ''
    Else Begin

      DT := UnixDateDelta+(TimeT / (24*60*60));

      Res := GetTimeZoneInformation(TZ);
      If (Res = TIME_ZONE_ID_INVALID) Then RaiseLastOSError;
      If (Res = TIME_ZONE_ID_STANDARD) Then Begin
        DT := DT-((TZ.Bias+TZ.StandardBias) / (24*60));
        Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.StandardName);
      End
      Else Begin
        DT := DT-((TZ.Bias+TZ.DaylightBias) / (24*60));
        Result := DateTimeToStr(DT)+' '+WideCharToString(TZ.DaylightName);
      End;
    End;
  End;
  }

begin
  FIPAddressList:=TObjectList.Create(True);
  FGatewayList:=TObjectList.Create(True);
  FName:=adapterInfo^.AdapterName;
  FDescription:=adapterInfo^.Description;
  FHWAddressLength:=adapterInfo^.AddressLength;
  FHWAddress:=MACToStr(@adapterInfo^.Address,adapterInfo^.AddressLength);
  FAIndex:=adapterInfo^.Index;
  FAType:=adapterInfo^._Type;
  if adapterInfo^.DHCPEnabled<>0 then FDHCPEnabled:=True else FDHCPEnabled:=False;
  FCurrentIPAddress:=TInfoIPAddress.Create(adapterInfo.CurrentIPAddress);
  PopulateAddressList(@adapterInfo^.IPAddressList,FIPAddressList);
  PopulateAddressList(@adapterInfo^.GatewayList,FGatewayList);
  FDHCPServer :=TInfoIPAddress.Create(@adapterInfo.DHCPServer);
  if adapterInfo^.HaveWINS then FHaveWINS:=True else FHaveWINS:=False;
  FPrimaryWINSServer:=TInfoIPAddress.Create(@adapterInfo.PrimaryWINSServer);
  FSecondaryWINSServer:=TInfoIPAddress.Create(@adapterInfo.SecondaryWINSServer);
end;

function TAdapter.GetIPAddress(index : integer) : TInfoIPAddress;
begin
  Result:=FIPAddressList.Items[index] as TInfoIPAddress;
end;

function TAdapter.GetMaxIPAddresses() : integer;
begin
  Result:=FIPAddressList.Count;
end;

function TAdapter.GetGateway(index : integer) : TInfoIPAddress;
begin
  Result:=FGatewayList.Items[index] as TInfoIPAddress;
end;

function TAdapter.GetMaxGateways() : integer;
begin
  Result:=FGatewayList.Count;
end;

destructor TAdapter.Destroy;
begin
  FCurrentIPAddress.Free;
  FIPAddressList.Free;
  FGatewayList.Free;
end;

constructor TIPInfo.Create;
Var
  AI,Work : PIPAdapterInfo;
  Size    : Integer;
  Res     : Integer;
  adapter : TAdapter;
  FI   : PFixedInfo;
  DNS  : PIPAddrString;
begin

  // Lista di adattatori
  FAdapters:=TObjectList.Create(True);
  Size := 5120;
  GetMem(AI,Size);
  Res := GetAdaptersInfo(AI,Size);
  If (Res <> ERROR_SUCCESS) Then Begin
    SetLastError(Res);
    RaiseLastOSError;
  End;
  Work := AI;
  while Assigned(Work) do
   begin
    adapter:=TAdapter.Create(Work);
    FAdapters.Add(adapter);
    Work := Work^.Next;
   end;
  FreeMem(AI);

// GetNetworkParameters
  FDNS:=TStringList.Create;
  Size := 1024;
  GetMem(FI,Size);
  Res := GetNetworkParams(FI,Size);
  If Res = ERROR_SUCCESS Then
   Begin
    FHostName:=FI^.HostName;
    FDomainName:=FI^.DomainName;

    If (FI^.CurrentDNSServer <> nil)
     Then FCurrentDNSServer:=FI^.CurrentDNSServer^.IPAddress
     Else FCurrentDNSServer:='(none)';
    DNS := @FI^.DNSServerList;
    While Assigned(DNS) do
     begin
      FDNS.Add(AnsiString(DNS^.IPAddress));
      DNS := DNS^.Next;
     end;
    FScopeId:=FI^.ScopeId;
    FEnableRouting:=FI^.EnableRouting>0;
    FEnableProxy:=FI^.EnableProxy>0;
    FEnableDNS:=FI^.EnableDNS>0;
   End;
  FreeMem(FI);

  inherited;
end;

destructor TIPInfo.Destroy;
begin
  FAdapters.Free;
  FDNS.Free;
  inherited;
end;

function TIPInfo.GetAdapter(index:integer) : TAdapter;
begin
  Result:=FAdapters.Items[index] as TAdapter;
end;

function TIPInfo.getMaxAdapters(): integer;
begin
  Result:=FAdapters.Count;
end;

function TIPInfo.GetDNSCount:integer;
begin
 Result:=FDNS.Count;
end;

function TIPInfo.GetDNS(i:integer):AnsiString;
begin
 Result:=FDNS[i];
end;

end.

Open in new window

0
 
LVL 5

Expert Comment

by:briangochnauer
ID: 33692833
You can't ask windows "What's you IP" because the network consists of multiple interfaces.
So it becomes quite complicated, in windows there are at least two NICs (network interface) these includes the "Local loopback adapter" and a 'real' NIC. Windows API returns both.
You can not ignore the loopback adapter. (Wish i could too)

Attached is a simple program that does what you need.

I've used this code for more than 10years on many projects without failure (>20k machines).

The method is;
To ask Windows to return the best interface to get to a paticular  IP address, the IP address does not have to actually exist, because internally windows will calculate from the routing table for all NICs which one it will try to use without  actually contacting that address.

The alternative method is to enumerate the NICs and determine which YOU think is best from the description of the NIC and query the IP addresses of the NIC.
Yes a NIC can have more than ONE IP Address, although this code ignores that possibility.

Project11.zip
0
 
LVL 5

Expert Comment

by:briangochnauer
ID: 33693724
Sorry didn't actually answer your question completely  on last post;
Here it is;  Attached is the code that gets whether DHCP enabled.
Project11.zip
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 14

Expert Comment

by:systan
ID: 33694973
hi
I know you just want to know if it is dhcp enabled or not,  so here's the complete OPTIMIZED code;
Just drop 1 button to test if it is dhcp or not.
unit Unit1;
interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;

type
  TForm1 = class(TForm)
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;


const IpHlpDLL = 'IPHLPAPI.DLL';
type
PTIP_ADAPTER_INFO = ^TIP_ADAPTER_INFO;
TIP_ADAPTER_INFO = packed record
  Next: PTIP_ADAPTER_INFO;
  ComboIndex: DWORD;
  AdapterName: array[1..260] of char;
  Description: array[1..132] of char;
  AddressLength: UINT;
  Address: array[1..8] of byte;
  Index: DWORD;
  aType: UINT;
  DHCPEnabled: UINT;
end;
type
TAdaptorInfo = record
  aType: UINT;
  DHCPEnabled: UINT;
  IPAddressTot: integer ;
end ;
TAdaptorRows = array of TAdaptorInfo ;
function isDHCP(const AdapterNum:byte): boolean;

var
Form1: TForm1;
IpHlpModule: THandle;
GetAdaptersInfo: function ( pAdapterInfo: PTIP_ADAPTER_INFO; pOutBufLen: PULONG ): DWORD; stdcall;

implementation
{$R *.dfm}

function LoadIpHlp: Boolean;
begin
Result := True;
if IpHlpModule <> 0 then Exit;
IpHlpModule := LoadLibrary (IpHlpDLL);
if IpHlpModule = 0 then
begin
Result := false;
exit ;
end ;
GetAdaptersInfo := GetProcAddress (IpHlpModule, 'GetAdaptersInfo');
end;

function isDHCP(const AdapterNum:byte): boolean;
var
  AdpRows       : TAdaptorRows;
  BufLen        : DWORD;
  AdapterInfo   : PTIP_ADAPTER_INFO;
  PBuf          : PCHAR ;
  res,AdpTot    : integer ;
  sult          : UINT;
begin
SetLength (AdpRows, 1) ;
BufLen := 0 ;
AdpTot:=0;
res := GetAdaptersInfo( Nil, @BufLen );
if (res <> ERROR_INSUFFICIENT_BUFFER) and (res = NO_ERROR) then exit ;
GetMem( pBuf, BufLen );
try
FillChar (pBuf^, BufLen, #0);
res := GetAdaptersInfo( PTIP_ADAPTER_INFO (PBuf), @BufLen );
if res = NO_ERROR then
begin
AdapterInfo := PTIP_ADAPTER_INFO (PBuf) ;
while ( AdapterInfo <> nil ) do
begin
AdpRows[AdpTot].IPAddressTot := 0 ;
AdpRows[AdpTot].DHCPEnabled := AdapterInfo^.DHCPEnabled;
sult:=AdpRows[AdapterNum].DHCPEnabled;
inc(AdpTot);
AdapterInfo := AdapterInfo^.Next;
end;
SetLength (AdpRows, AdpTot) ;
end ;
finally
FreeMem( pBuf );
end ;
if (sult=1) then result:=true else result:=false;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
AdpRows: TAdaptorRows ;
begin
if isDHCP(0) then showmessage('DHCP is enabled') else showmessage('DHCP is NOT enabled')
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
if NOT LoadIpHlp then ShowMessage( 'Internet Helper DLL Not Available');
end;


initialization
IpHlpModule := 0 ;

finalization
if IpHlpModule <> 0 then
begin
FreeLibrary (IpHlpModule) ;
IpHlpModule := 0 ;
end ;

end.

Open in new window

0
 
LVL 25

Expert Comment

by:epasquier
ID: 33695076
Excellent idea to use GetBestInterface. I added its support in IPInfo object.

With that, what you need is as simple as the code below, plus if you ever need more information about your IP config, it's all in a simple object to use.
function MainAdapterUseDHCP:Boolean;
Var
 IP:TIPInfo;
begin
 IP:=TIPInfo.Create;
 try
  Return:=IP.Adapters[BestAdapter].DHCPEnabled;
 finally
  IP.Free;
 end;
end;

Open in new window

IPInfo.zip
0
 
LVL 25

Expert Comment

by:epasquier
ID: 33695087
Oups, type error :

Return:=IP.Adapters[IP.BestAdapter].DHCPEnabled;
0
 
LVL 14

Expert Comment

by:systan
ID: 33697857
briangochnauer? epasquier?
I think I have the shortest code to get the dhcp if enabled.

procedure TForm1.Button1Click(Sender: TObject);
begin
if isDHCP(0) then showmessage('DHCP is enabled') else showmessage('DHCP is NOT enabled')
end;
0
 
LVL 25

Expert Comment

by:epasquier
ID: 33699122
and where does that function comes from ?
0
 
LVL 5

Expert Comment

by:briangochnauer
ID: 33701367
Cute systan,
Hiding the hundreds of lines it takes to get there. :)
But in today's world of wireless cards, VPNs, VMWare, NICs as well as the local loopback adapter all which create connection, there is little chance that checking the first NIC will be durable.
You have to do GetBestInterface.
I find it interesting that the author is not envolved in this converstion, just a bunch of 'experts' trying to top each other.
 
0
 
LVL 25

Expert Comment

by:epasquier
ID: 33702409
> I find it interesting that the author is not envolved in this converstion
I was thinking about the same thing. I've been glad to see your full IPHelper transcription unit and to improve the unit I use, but now this discussion seems over
0
 

Author Comment

by:Allan_Fernandes
ID: 33714258
Sorry to all of you.
I had some pressing issues due to which I had to keep this on hold.
Thanks for the co-operation.

Highest Regards
Allan Fernandes
0
 

Author Closing Comment

by:Allan_Fernandes
ID: 33714267
Since I know the IP with which I am connecting, this suffices my requirements totally

Thanks
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Have you ever had your Delphi form/application just hanging while waiting for data to load? This is the article to read if you want to learn some things about adding threads for data loading in the background. First, I'll setup a general applica…
Hello everybody This Article will show you how to validate number with TEdit control, What's the TEdit control? TEdit is a standard Windows edit control on a form, it allows to user to write, read and copy/paste single line of text. Usua…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
In this video, Percona Solution Engineer Dimitri Vanoverbeke discusses why you want to use at least three nodes in a database cluster. To discuss how Percona Consulting can help with your design and architecture needs for your database and infras…
Suggested Courses

718 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question