There are various Windows API functions that can be used to retrieve several IP configuration settings. GetNetworkParams is one such function. A variation could be to pass a var parameter to return the IP address in and have the function return a Boolean indicating success or otherwise. GetNetworkParams retrieves various settings, so even though the following code is only returning the primary DNS server address part, you can use this pattern for other purposes as well.
The GetNetworkParams function is part of the IP Helper API set. Unfortunately, most Delphi versions don't provide declarations, so you will have to declare the function and the types it uses yourself, as shown in the following example.
const MAX_HOSTNAME_LEN = 128; MAX_DOMAIN_NAME_LEN = 128; MAX_SCOPE_ID_LEN = 256; type TIPAddressString = packed array[0..15] of AnsiChar; PIPAddrString = ^TIPAddrString; TIPAddrString = packed record Next : PIPAddrString; IPAddress : TIPAddressString; IPMask : TIPAddressString; Context : DWord; end; PFixedInfo = ^TFixedInfo; TFixedInfo = packed record HostName : packed array[0..(MAX_HOSTNAME_LEN+4)-1] of AnsiChar; DomainName : packed array[0..(MAX_DOMAIN_NAME_LEN+4)-1] of AnsiChar; CurrentDNSServer : PIPAddrString; DNSServerList : TIPAddrString; NodeType : LongWord; ScopeId : packed array[0..(MAX_SCOPE_ID_LEN+4)-1] of AnsiChar; EnableRouting : LongWord; EnableProxy : LongWord; EnableDNS : LongWord; end; function GetNetworkParams(pFixedInfo: PFixedInfo; var pOutBufLen: LongWord): DWord; stdcall; external 'iphlpapi.dll' Name 'GetNetworkParams'; function GetDefaultDNSServer: String; var ABufferLength: LongWord; AFixedInfo: PFixedInfo; begin AFixedInfo:=nil; ABufferLength:=0; {First call to retrieve the required buffersize} if GetNetworkParams(AFixedInfo, ABufferLength)=ERROR_BUFFER_OVERFLOW then begin GetMem(AFixedInfo, ABufferLength); try if GetNetworkParams(AFixedInfo, ABufferLength)=ERROR_SUCCESS then Result:=AFixedInfo^.DNSServerList.IPAddress; finally FreeMem(AFixedInfo); end; end; end;
Source: www.guidogybels.net.