xxxxxxxxxx
public static string GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
throw new Exception("No network adapters with an IPv4 address in the system!");
}
xxxxxxxxxx
using System.Net;
using System.Text.Json;
string GetPublicIpAddress()
{
using (var client = new WebClient())
{
string json = client.DownloadString("https://api.ipify.org?format=json");
var document = JsonDocument.Parse(json);
return document.RootElement.GetProperty("ip").GetString();
}
}
string ipAddress = GetPublicIpAddress();
Console.WriteLine("Public IP address: " + ipAddress);
The resulting output is a message indicating the public IP address of the computer. Note that the output may vary depending on the network configuration of the system, and that you should use appropriate error handling and validation when working with external APIs.
xxxxxxxxxx
Step 1: Start a new Console project in your Visual Studio.
Step 2: Add a namespace in your project as in the following:
Using System.Net;
Step 3: Before fetching the IP Address we need to know whose IP Address we really want. It's quite understood that we want our own PC. But, that must be specified in my code because computers are dumb.
So, we can fetch the machine Name (or Host Name) by the GetHostName() Method. And this is inside the Dns class.
Step 4: We are now ready to get the IP address of the Host.
For this we need to use the GetHostByName() method followed by AddressList array (first Index).
And, in GetHostByName's argument we "host name".
Then, our code looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net; //Include this namespace
namespace IpProto
{
class Program
{
static void Main(string[] args)
{
string hostName = Dns.GetHostName(); // Retrive the Name of HOST
Console.WriteLine(hostName);
// Get the IP
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
Console.WriteLine("My IP Address is :"+myIP);
Console.ReadKey();
}
}
}