Delphi 获取本机 HostName IP Address


本文整理自网络,侵删。

 
unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;





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

    // MAC Address



  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

uses    Types, WinSock, Nb30;


// IP Address

function WinSockVersion: Word;
begin
  Result := MakeWord(1, 1);
end;

function HostName: string;
var
  WSAData: TWSAData;
  Buffer: array[0..MAX_PATH] of AnsiChar;
begin
  Result := '';
  if WSAStartup(WinSockVersion, WSAData) = 0 then
  try
    if WinSock.GetHostName(Buffer, SizeOf(Buffer)) = 0 then
      Result := string(Buffer);
  finally
    WSACleanup;
  end;
end;

function IpAddress(const HostName: string): string;
var
  WSAData: TWSAData;
  HostEnt: PHostEnt;
begin
  Result := '';
  if WSAStartup(WinSockVersion, WSAData) = 0 then
  try
    HostEnt := GetHostByName(PAnsiChar(AnsiString(HostName)));
    if HostEnt <> nil then
      Result := string(inet_ntoa(PInAddr(HostEnt.h_addr_list^)^));
  finally
    WSACleanup;
  end;
end;

function IpAddresses(const HostName: string): TStringDynArray;
type
  PPInAddr = ^PInAddr;
var
  WSAData: TWSAData;
  HostEnt: PHostEnt;
  InAddrPtrPtr: PPInAddr;
begin
  Result := nil;
  if WSAStartup(WinSockVersion, WSAData) = 0 then
  try
    HostEnt := GetHostByName(PAnsiChar(AnsiString(HostName)));
    if HostEnt <> nil then
    begin
      InAddrPtrPtr := PPInAddr(HostEnt.h_addr_list);
      while InAddrPtrPtr^ <> nil do
      begin
        SetLength(Result, Length(Result) + 1);
        Result[Length(Result) - 1] := string(inet_ntoa(InAddrPtrPtr^^));
        Inc(InAddrPtrPtr);
      end;
    end;
  finally
    WSACleanup;
  end;
end;





procedure TForm1.Button1Click(Sender: TObject);
var
  Addresses: TStringDynArray;
  i:integer;
begin
 Memo1.Lines.Add(HostName);
 Memo1.Lines.Add(IpAddress(HostName));

Addresses:= IpAddresses(HostName);
  for I := 0 to Length(Addresses) - 1 do
 Memo1.Lines.Add('IP Address: ' + Addresses[I]);
end;

end.

相关阅读 >>

Delphi 多重循环

Delphi 顺序查找与二分查找

Delphi gridpanel percent百分比设置

Delphi 字符串中末位是双字节字符的处理(避免最后一位为乱码)

Delphi中paramstr的用法

Delphi 一个call应该如何写?

Delphi中使用activex的一些心得

Delphi word转pdf两种方法

Delphi idhttp多线程下载

Delphi idhttp基本使用方法

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...