Site icon Embarcadero RAD Studio, Delphi, & C++Builder Blogs

What is my IP address?

the future of starts demands massive productivity

Author: Pawe Gowacki

There are many situation when it would handy to know the IP address of a device where our app is running. Maybe you want to identify who is running your app? By IP address it is also possible to calculate the approximate location of a device. If you connect to Internet through a router, there are big chances that it implements “Network Address Translation” (NAT), to make it harder for remote machines to establish a direct connection to a machine within a local network.

Recently I have come across a very simple and useful REST API that makes it possible to get the IP address and the geographical location of a client that invokes it. In this way we could find out under which IP address the Internet “sees” us.

If you send an HTTP GET request to http://ip-api.com/json, you will receive a JSON document with information about your IP address, longitude and latitude, country, city, zip code, ISP provider name, timezone and region.

In order to make this service easily accessible in code I have put together a little Delphi “TMyIP” class that provides one class function “GetInfo” that takes “TIPInfo” record “out” parameter and returns a boolean value that indicates if the parameter contains valid information. The actual HTTP GET request is made using the native “THTTPClient” class from “System.Net.HttpClient” unit. The JSON processing is done using “TJSONTextReader” class.

Below is the full source code of the “uMyIP” unit that contains the “TMyIP” class.

[crayon-67715eee50098255301655/]

Let’s quickly test this class. Start Delphi and create a new “Multi-Device Application” project. Choose “Blank Application” template and save the main form as “uFormMyIP” and the whole project as “MyIP”. You can optionally change the “Name” property of the form to “FormMyIP”. Add a new unit to the project and save it as “uMyIP”. Copy the above code, select the source code of the empty unit and paste the code to replace the entire content. Now add the new “uMyIP” unit to the uses clause of the form. Drop a button on the form and align it to “Top”. Change its “Text” property to “Check IP”. Drop “TListView” control onto the form, align it to “Client” and change its “Name” property to “lstvwInfo”. Double-click on the button and add the following code to the “OnClick” event handler to invoke the “TMyIP.GetInfo” and display the data in the list view.

[crayon-67715eee500a0203557814/]

Save all and run the project. When you click on the button you should see how the world sees You!

The complete source code of this simple demo can be downloaded from here. Enjoy!

Next, learn about a service called IPApi, which is one of the market-leading solutions for all your IP Intelligence requirements in one place.
Exit mobile version