2005. február 4., péntek

Determine your LOCAL IP


Problem/Question/Abstract:

Determine your LOCAL IP

Answer:

Another piece of code to determine your machine's local IP number - the function GetLocalIP returns it as a string.


function LWToIP(LW: LongWord): string;
begin
  Result := IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
  LW := LW shr 8;
  Result := Result + '.' + IntToStr(LW and $FF);
end;

function TForm1.GetLocalIP: string;
var
  name, A: PChar;
  h: hostent;
  I: Integer;
begin
  GetMem(name, 255);
  try
    I := GetHostName(name, 255);
    if I <> 0 then
      I := wsagetlastError;
    if I <> 0 then
      StatusBar1.Panels[0].Text := 'Error: ' + IntToStr(I)
    else
    begin
      h := GetHostByName(name)^;
      if h.h_length <> 4 then
        Result := ''
      else
      begin
        A := h.h_addr_list^;
        I := 0;
        while (A^ <> #0) and (CompareStr(A, h.h_name) <> 0) do
        begin
          inc(I, 4);
          Inc(A, 4)
        end;
        if I < 4 then
        begin
          Result := h.h_name
        end
        else
        begin
          while I >= 4 do
          begin
            Dec(A, 4);
            Dec(I, 4);
            Result := Result + LWToIP(PLongWord(A)^) + ', ';
          end;
          Delete(Result, Length(Result) - 1, 2);
        end
      end
    end
  finally
    FreeMem(name)
  end
end;

Nincsenek megjegyzések:

Megjegyzés küldése