delphi 中获取计算机名和IP

function GetComputerName:String; //获取计算机名称
var
  wVersionRequested : WORD;
  wsaData : TWSAData;
  p : PHostEnt; s : array[0..128] of char;
begin
  try
    wVersionRequested := MAKEWORD(1, 1); //创建 WinSock
    WSAStartup(wVersionRequested, wsaData); //创建 WinSock
    GetHostName(@s,128);
    p:=GetHostByName(@s);
    Result:=p^.h_Name;
  finally
    WSACleanup; //释放 WinSock
  end;
end;

function GetHostIP:String; //获取IP
var
   wVersionRequested : WORD;
   wsaData : TWSAData;
   p : PHostEnt; s : array[0..128] of char; p2 : pchar;
begin
   try
      wVersionRequested := MAKEWORD(1, 1); //创建 WinSock
      WSAStartup(wVersionRequested, wsaData); //创建 WinSock
      GetHostName(@s,128);
      p:=GetHostByName(@s);
      p2 := iNet_ntoa(PInAddr(p^.h_addr_list^)^);
      Result:= P2;
   finally
      WSACleanup; //释放 WinSock
   end;
end;


 

    获取本机IP,可以获得内网IP或外网IP的函数,在Uses中加入WinSock:

Function GetLocalIp(InternetIP:boolean):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;
    IP: String;
begin
    Screen.Cursor := crHourGlass;
    try
      WSAStartup($101, GInitData);
      IP:='0.0.0.0';
      GetHostName(Buffer, SizeOf(Buffer));
      phe := GetHostByName(buffer);
      if phe = nil then
      begin
        ShowMessage(IP);
        Result:=IP;
        Exit;
      end;
      pPtr := PaPInAddr(phe^.h_addr_list);
      if InternetIP then
        begin
          I := 0;
          while pPtr^[I] <> nil do
            begin
              IP := inet_ntoa(pptr^[I]^);
              Inc(I);
            end;
        end
      else
        IP := inet_ntoa(pptr^[0]^);
      WSACleanup;
      Result:=IP;//如果上网则为上网ip否则是网卡ip
    finally
      Screen.Cursor := crDefault;
    end;
end;


 

你可能感兴趣的:(String,function,list,Integer,buffer,Delphi)