5

Possible Duplicate:
Delphi, How to get all local IPs?

What's the easiest & quickest method for obtaining a local IP address of the machine in Delphi 2009 without using 3rd-party components? Thanks.

Community
  • 1
  • 1
Darius
  • 524
  • 1
  • 5
  • 11
  • Voting to close as duplicate of http://stackoverflow.com/questions/576538/delphi-how-to-get-all-local-ips – mghie Jul 17 '09 at 13:14
  • This is clearly not a duplicate question as it specifies "without using 3rd-party components". The linked question does not, and none of the answers use Delphi Winsock. The accepted answer here answers this specific question. – Guy Gordon Jan 15 '20 at 13:32

1 Answers1

15

From: http://www.scalabium.com/faq/dct0037.htm

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

Function GetIPAddress():String;
type
  pu_long = ^u_long;
var
  varTWSAData : TWSAData;
  varPHostEnt : PHostEnt;
  varTInAddr : TInAddr;
  namebuf : Array[0..255] of char;
begin
  If WSAStartup($101,varTWSAData) <> 0 Then
  Result := 'No. IP Address'
  Else Begin
    gethostname(namebuf,sizeof(namebuf));
    varPHostEnt := gethostbyname(namebuf);
    varTInAddr.S_addr := u_long(pu_long(varPHostEnt^.h_addr_list^)^);
    Result := 'IP Address: '+inet_ntoa(varTInAddr);
  End;
  WSACleanup;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  Label1.Caption := GetIPAddress;
end;

end.
Gabriel
  • 20,797
  • 27
  • 159
  • 293
reva
  • 1,477
  • 2
  • 14
  • 23
  • 5
    After changing type of namebuf to array of ansichar compiles. Thanks! – Darius Jul 17 '09 at 13:18
  • 1
    You should have indicated in your original question that you were using Delphi 2009, then. Remember that things can sometimes change depending on what version of Delphi you're using. – Ken White Jul 17 '09 at 15:48
  • @Kishor: The function itself only requires the Winsock unit, in D7 anyway. Those others are just the common units added to a form unit. – Todd Jul 17 '09 at 17:39
  • 1
    Ken, he *did* indicate he was using Delphi 2009. – Rob Kennedy Jul 17 '09 at 20:34
  • I had to modify namebuf to ansichar and when I closed my software it shows me EAccessViolation. I'm using Delphi 10.3 – Wellington Telles Cunha Jul 12 '21 at 18:35