function tform1.getip:string; var Ginidata:Twsadata; p:phostent; s:array[0..128]of char; p2:pchar; output:array[0..100]of char; begin Wsastartup(2,Ginidata); gethostname(@s,128); p:=gethostbyname(@s); p2:=inet_ntoa(pinaddr(p^.h_addr_list^)^); strpcopy(output,'ip addr:'+format('%s',[p2])); wsacleanup; result:=string(output); end;
用google搜一下,到处都是方法,铺天盖地的
procedure TForm1.Button1Click(sender:TObject); begin showmessage(TcpServer1.LocalHostAddr); end;
procedure TForm1.Button1Click(sender:TObject); begin showmessage(TcpServer1.LocalHostAddr); end; 接分快乐
取本机ip还是有一些内容值得讨论的,因为可能存在由于多个网卡或者虚拟网卡的关于存在多个ip地址,取到的可能是一个列表,用以下这个方式在某种情况下可能和楼上几个取得的有所不通,比如断开网络的时候有些能取到169.xxx.xxx.xxx 有些能取道127.0.0.1//取本机ip地址 function LocalIP : string; 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^[I] <> nil do begin result:=StrPas(inet_ntoa(pptr^[I]^)); Inc(I); end; WSACleanup;
var Ginidata:Twsadata;
p:phostent;
s:array[0..128]of char;
p2:pchar;
output:array[0..100]of char;
begin
Wsastartup(2,Ginidata);
gethostname(@s,128);
p:=gethostbyname(@s);
p2:=inet_ntoa(pinaddr(p^.h_addr_list^)^);
strpcopy(output,'ip addr:'+format('%s',[p2]));
wsacleanup;
result:=string(output);
end;
begin
showmessage(TcpServer1.LocalHostAddr);
end;
begin
showmessage(TcpServer1.LocalHostAddr);
end;
接分快乐
function LocalIP : string;
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^[I] <> nil do
begin
result:=StrPas(inet_ntoa(pptr^[I]^));
Inc(I);
end;
WSACleanup;
end;