c# get local ipv4 address code example
Example 1: c# get pc ip address
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!");
}
Example 2: c# ip address translate localhost
IPAddress address = Dns.GetHostAddresses("localhost").Where(x => x.AddressFamily == AddressFamily.InterNetwork).First();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(address, port));
Example 3: c# get ip address
var httpClient = new HttpClient();
var ip = await httpClient.GetStringAsync("https://api.ipify.org");
Console.WriteLine($"My public IP address is: {ip}");