怎么样取得本机的IP地址?(50分)

  • 主题发起人 主题发起人 kmwap
  • 开始时间 开始时间
K

kmwap

Unregistered / Unconfirmed
GUEST, unregistred user!
如题。[:)]
 
function TfrmBillWriteAncestor.LocalIP:string;//获得本机的ip地址
type
TaPInAddr = array [0..10] of PInAddr;
PaPInAddr = ^TaPInAddr;
var
phe : PHostEnt;
pptr : PaPInAddr;
Buffer : array [0..63] of char;
I : Integer;
GInitData : TWSADATA;
BEGIN
WSAStartup($101, GInitData);
Result := '';
GetHostName(Buffer, SizeOf(Buffer));
phe :=GetHostByName(buffer);
IF phe = nil THEN Exit;
pptr := PaPInAddr(Phe^.h_addr_list);
I := 0;
while pptr^ <> nil do BEGIN
result:=StrPas(inet_ntoa(pptr^^));
Inc(I);
END;
WSACleanup;
END;

在interface
uses 加入winsock单元.
 
uses winsock;
...

function GetIPAddress: string;
var
phoste:PHostEnt;
Buffer:array[0..100] of char;
WSAData:TWSADATA;
begin
result:='';
if WSASTartup($0101, WSAData) <> 0 then exit;
GetHostName(Buffer,Sizeof(Buffer));
phoste:=GetHostByName(buffer);
if phoste = nil then
begin
result:='127.0.0.1';
end
else
result:=StrPas(inet_ntoa(PInAddr(phoste^.h_addr_list^)^));
WSACleanup;
end;

 
uses Winsock;
...

function getIPs: TStrings;

type

TaPInAddr = Array[0..10] of PInAddr;

PaPInAddr = ^TaPInAddr;

var

phe: PHostEnt;

pptr: PaPInAddr;

Buffer: Array[0..63] of Char;

I: Integer;

GInitData: TWSAData;

begin

WSAStartup($101

GInitData);

Result:=TStringList.Create;

Result.Clear;

GetHostName(Buffer

SizeOf(Buffer));

phe := GetHostByName(buffer);

if phe = nil then

begin

Exit;

end;

pPtr := PaPInAddr(phe^.h_addr_list);

I := 0;

while pPtr^ <> nil do

begin

Result.Add(inet_ntoa(pptr^^));

Inc(I);

end;

WSACleanup;

end;



procedure TForm1.Button1Click(Sender: TObject);

begin

memo1.Lines:=GetIps;

end;
 
这样的问题还要问么?应该查查历史贴的。
 
procedure TForm1.Button4Click(Sender: TObject);{查找本机的ip地址}
var
ch: ARRAY[1..32] OF Char;
i: Integer;
WSData: TWSAData;
MyHost: PHostEnt;
a, b: string;
begin
if WSAstartup(2,wsdata)<>0 then
begin
Edit1.Text := 'can''t start Winsock: Error ' + IntToStr(WSAGetLastError);
Halt(2);
end;
try
IF getHostName(@ch[1],32)<>0 then
begin
Edit1.Text := 'getHostName failed';
Halt(3);
end;
except
Edit1.Text := 'getHostName failed';
halt(3);
end;
MyHost:=GetHostByName(@ch[1]);
if MyHost=NIL then
begin
Edit1.text := (' +GetHostName('+StrPas(@ch[1])+'), failed : Error'+IntToStr(WSAGetLastError));
Halt(4);
end
else
begin
a := '本机IP地址为 :';
for i:=1 to 4 do
begin
b := intToStr(Ord(MyHost.h_addr^[i-1]));
if i<4 then
b := b + '.';
a := a + b;
end;
end;
Edit1.Text := a;
end;
 
后退
顶部