How can I know when is sunrise at the location of an IP address in C#?

To determine the sunrise time of an IP address using IP2Location.io in C#, you can use the IP2Location.io API to retrieve geolocation and related data.

  1. We'll assume that you have already installed C# and we won't cover that here. You will also need a paid subscription to the Plus plan or higher. Subscribe now!
  2. Using Visual Studio, create a new Console App for C#. Or, in the command line, run the below command inside an empty folder to create the project.
    Bash
    
    dotnet new console
    			
  3. Next, install the Newtonsoft.Json package using Visual Studio. Or, in the command line, run the below command inside the project folder.
    Bash
    
    dotnet add package Newtonsoft.Json
    			
  4. Edit the Program.cs file and replace the code with the below codes.
    C#
    
    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Net;
    
    HttpClient client = new();
    string ip = "8.8.8.8";
    string key = "YOUR_API_KEY";
    
    try
    {
    	HttpResponseMessage response = await client.GetAsync($"https://api.ip2location.io/?key={key}&ip={ip}&format=json");
    	if (response.StatusCode == HttpStatusCode.OK)
    	{
    		string rawjson = await response.Content.ReadAsStringAsync();
    		JObject? results = JsonConvert.DeserializeObject<JObject>(rawjson);
    		if (results != null)
    		{
    			if (results["time_zone_info"] != null)
    			{
    				Console.WriteLine($"The sunrise time for IP {ip} is {results["time_zone_info"]["sunrise"]}.");
    			}
    			else
    			{
    				throw new Exception("ERROR: The sunrise field requires a paid subscription to the Plus plan or higher.");
    			}
    		}
    		else
    		{
    			throw new Exception("ERROR: Invalid JSON in response.");
    		}
    	}
    	else if ((response.StatusCode == HttpStatusCode.Unauthorized) || (response.StatusCode == HttpStatusCode.BadRequest))
    	{
    		string rawjson = await response.Content.ReadAsStringAsync();
    		if (rawjson.Contains("error_message"))
    		{
    			JObject? results = JsonConvert.DeserializeObject<JObject>(rawjson);
    			throw new Exception($"ERROR: {results?["error"]?["error_message"]?.ToString()}");
    		}
    		throw new Exception(rawjson);
    	}
    }
    catch (HttpRequestException ex)
    {
    	throw new Exception(ex.Message);
    }
    			
  5. In the command line, run the below command.
    Bash
    
    dotnet run
    			

This script will output the sunrise time 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