How can I determine the usage type of an IP address in D?

To determine the usage type of an IP address using IP2Location.io in D, you can use the IP2Location.io API to retrieve geolocation and related data. The usage type field specifies how the IP is being used. For usage types supported, please see API documentation for more info.

  1. We'll assume that you have already installed D and we won't cover that here. You will also need a paid subscription to the Starter plan or higher. Subscribe now!
  2. Save the below code into a file called test.d on your computer.
    D
    
    import std.stdio;
    import std.uri;
    import std.net.curl;
    import std.json;
    import std.conv;
    
    void main()
    {
        auto key = "YOUR_API_KEY";
        auto ip = "8.8.8.8";
        ushort code;
        auto reason = "";
    
        auto url = "https://api.ip2location.io/?format=json&key=" ~ key ~ "&ip=" ~ ip;
        string content = "";
        auto client = HTTP(url); // using "HTTP" instead of just "get" due to the need to read the page content when HTTP Status <> 200
        client.onReceive = (ubyte[] data) {
            content = content ~ to!string(cast(char[])(data));
            return data.length;
        };
        client.onReceiveStatusLine = (HTTP.StatusLine status) {
            code = status.code;
            reason = status.reason;
        };
        client.perform();
    
        if (code == 200)
        {
            JSONValue result = parseJSON(content);
            if ("usage_type" in result)
            {
                writefln("The usage type for IP %s is %s.", ip, result["usage_type"].str);
            }
            else
            {
                writeln(
                        "ERROR: The usage_type field requires a paid subscription to the Starter plan or higher.");
            }
        }
        else if ((code == 400) || (code == 401))
        {
            JSONValue result = parseJSON(content);
            if ("error" in result)
            {
                writefln("ERROR: %s", result["error"]["error_message"].str);
            }
            else
            {
                writefln("ERROR: %s", reason);
            }
        }
        else
        {
            writeln("ERROR: Unable to call API.");
        }
    }
    			
  3. In the command line, run the below commands to compile and run the test code.
    Bash
    
    dmd test.d
    ./test
    			

This script will output the usage type of specified IP address. Make sure to replace 8.8.8.8 with the IP address you want and replace YOUR_API_KEY to your own API key.

Other Languages

Unlock Location Insights For Free

Empower your applications with accurate IP geolocation information now.

Try It for Free