介绍
本文章介绍了通过Delphi XE5 实现获取本地的IP地址,在使用代码之前,需要引用winsock单元,目前测试了获取IP4没问题,但是并没有测试获取IP6是否有问题,大家可以试试,有结果的可以告诉我下,谢啦
主要的获取IP地址的代码是:
function MYComputerName: string; var FStr: PChar; FSize: Cardinal; begin FSize := 255; GetMem(FStr, FSize); Winapi.Windows.GetComputerName(FStr, FSize); Result := FStr; FreeMem(FStr); end; function GetLocalIpList(var IpList: TStringList): Integer; type TaPInAddr = array[0..10] of PInAddr; PaPInAddr = ^TaPInAddr; var HostName: array[0..MAX_PATH] of AnsiChar; NameLen: Integer; WSData: TWSAData; lpHostEnt: PHostEnt; I: Integer; pptr: PaPInAddr; begin Result := 0; if WSAStartup(MakeWord(2, 0), WSData) <> 0 then Exit; try NameLen := sizeof(HostName); fillchar(HostName, NameLen, 0); NameLen := GetHostName(HostName, NameLen); if NameLen = SOCKET_ERROR then Exit; lpHostEnt := GetHostByName(HostName); if lpHostEnt = nil then Exit; I := 0; pPtr := PaPInAddr(lpHostEnt^.h_addr_list); IpList.Clear; while pPtr^[I] <> nil do begin IpList.ADD(inet_ntoa(pptr^[I]^)); Inc(I); end; Result := IpList.Count; finally WSACleanup; end; end;
关键字词: