获取本机ip地址,其实方法有很多了,现在用windows api 在delphi下实现如下;
1. 在uses 里引用 winsock 单元。
2. 源码如下:
[delphi] view plain copy print ? function GetLocalIP:string; type TaPInAddr = array [0..10] of PInAddr; //用于存储活动的ip地址列表 PaPInAddr = ^TaPInAddr; var phe : PHostEnt; pptr : PaPInAddr; Buffer : array [0..63] of char; //store hostname I : Integer; GInitData : TWSADATA; wVersion:word; begin wVersion:=MAKEWORD(1,1); //winsock dll version Result :=''; if WSAStartup(wVersion, GInitData)=0 then //初始化windows socket begin if GetHostName(Buffer, SizeOf(Buffer))=0 then //计算机名称 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; //关闭、清理windows socket end; end; 3.该源码的不足的地方是如果机器上有2张及以上网卡,得到的是最后一个。
