如何获取本机ip地址(50分)

  • 主题发起人 主题发起人 zxzxzczc
  • 开始时间 开始时间
Z

zxzxzczc

Unregistered / Unconfirmed
GUEST, unregistred user!
怎样写一个程序获取本机ip地址?
 
unit Unit1;

interface

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

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

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
var
wVersionRequested : WORD;
wsaData : TWSAData;
p : PHostEnt;
s : array[0..128] of char;
begin
{启动 WinSock}
wVersionRequested := MAKEWORD(1, 1);
WSAStartup(wVersionRequested, wsaData);
{计算机名}
GetHostName(@s, 128);
p := GetHostByName(@s);
{IP地址}
label1.caption:=iNet_ntoa(PInAddr(p^.h_addr_list^)^);

WSACleanup;
end;

end.
 
用这个函数就可以:
//取本机IP地址
function GetIP:String;
var
WSData: TWSAData;
Buffer: array[0..63] of Char;
HostEnt: PHostEnt;
PPInAddr: ^PInAddr;
IPString: String;
begin
IPString:='';
try
WSAStartUp($101, WSData);
GetHostName(Buffer, SizeOf(Buffer));
HostEnt:=GetHostByName(Buffer);
if Assigned(HostEnt) then
begin
PPInAddr:=@(PInAddr(HostEnt.H_Addr_List^));
while Assigned(PPInAddr^) do
begin
IPString:=StrPas(INet_NToA(PPInAddr^^));
Inc(PPInAddr);
end;
end;
Result := IPString;
finally
try
WSACleanUp;
except
end;
end;
end;
 
在我程序中copy来的,能用,但别忘了在uses部分加 WinSock单元
function GetLocalUserName():string; //获得本机登录用户
var strUser:PChar;
strSize:DWord;
begin
strSize:=100;
struser:=StrAlloc(100); //¸østruserÉêÇëÄÚ´æ¿Õ¼ä
getusername(strUser,strSize);//µ÷Óú¯Êý

Result:=struser;
end;
function GetLocalIP():string; //本机IP
p: PHostEnt;
s : array[0..128] of char;
p2 : pchar;
WSAData:TWSAData;
begin
try
WSAstartup(2,WSAData);
{»ñµÃ¼ÆËã»úÃû}
GetHostName(@s, 128);
p := GetHostByName(@s);
{»ñµÃ±¾»úµÄipµØÖ·}
p2 := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
result:=p2;
except
result:='';
end;
WSAcleanup;
end;
function GetLocalHostName():string;//本机主机名
var
s : array[0..128] of char;
WSAData:TWSAData;
i:integer;
strHostName:string;
begin
strHostName:='';
i:=0;
try
WSAstartup(2,WSAData);
{»ñµÃ¼ÆËã»úÃû}
GetHostName(@s, 128);
while s<>chr(0) do
begin
strHostName:=strHostName+s;
i:=i+1;
end;
result:=strHostName;
except
result:='';
end;
WSAcleanup;
end;
 
后退
顶部