DelphiFAQ Home Search:
General :: Programming :: Delphi :: Network
Network (local network and Internet) programming under Windows with Delphi.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Determine your LOCAL IP

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

Note:
If you run through NAT (network address translation) then your public address can only be told by someone else like:
http://www.myip.dk/

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;
 
You don't like the formatting? Check out SourceCoder then!
Generated 4:01:24 on Feb 25, 2017