Link to home
Start Free TrialLog in
Avatar of thisguirong
thisguirong

asked on

How to use Delphi to get my Actual IP instead of Local IP?

Hi,

   i'm writing a simple client/server application which can transfer text, using Clientsocket and serversocket. I need to know my IP address before the program could connect, thats where the problem comes. Below is the code to get my LocalIP:

uses WinSock;
Function GetLocalIP: string;
var
wsaData: TWSAData;
P : PHostEnt;
S : array [0..128] of char;
begin
WSAStartup(MAKEWORD(1,1), wsaData);
GetHostName(@s, 128);
P:= GetHostByName(@s);
Result:= iNet_ntoa(PInAddr(p^.h_addr_list^)^);
WSACleanup;
end

The code detect my IP as "169.53.153.156".
However, the program wont connect. On further search for my IP,
WhatismyIP.com states that mY actual IP is "220.255.135.199".

There are tips on how to connect to WhatismyIP.com and get my actual IP using Tbrowser components. But i dont wish to connect to websites.

Anyone knows how to code in Delphi to get my actual IP? it should be a function, and by just clicking on a button, the actual IP will be shown.
Avatar of Mike Littlewood
Mike Littlewood
Flag of United Kingdom of Great Britain and Northern Ireland image

Are you trying to use TClientSocket and TServerSocket components to try and connect across the internet rather than a local network?
Here is a small function, which will take your REAL IP address. It is different, because you may be behind proxy. However, if you use you application from LAN network, you will need "169.53.153.156"...

uses
  idHTTP;

function GetMyRealIP : String;
var
  HTTP    : TidHTTP;
  text    : String;
  lc_pos  : Integer;
begin
  HTTP := TidHTTP.Create(nil);
  try
    text := HTTP.Get('http://whatismyip.com/');
  finally
    HTTP.Free;
  end;
  lc_pos := Pos('WhatIsMyIP.com</title>', text);
  text   := Copy(text, 1, lc_pos-1);
  lc_pos := Pos('Your IP is', text);
  text   := Copy(text, lc_pos + 10, length(text) - lc_pos + 1);
  Result := Trim(text);
end;
Avatar of BlackTigerX
BlackTigerX

actually the 169 is just a (Microsoft) generic ip meaning there is no network connection
ASKER CERTIFIED SOLUTION
Avatar of PeterIngham
PeterIngham

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial