Get computer IP address - LAN & Internet using C#
There are two ways to get your IP address!
First is for LAN IP, which indicates your computer address in local network,
while the second way is to get your INTERNET IP, which is stored in your router.
First, you will need is to import two namespaces:
using System.Net;
using System.IO;
Get your LAN IP address
This solution was programmed using built in functions in .NET Framework, and this is not a problem.
/// <summary>
/// Get computer LAN address like 192.168.1.3
/// </summary>
/// <returns></returns>
private string GetComputer_LanIP()
{
string strHostName = System.Net.Dns.GetHostName();
IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);
foreach (IPAddress ipAddress in ipEntry.AddressList)
{
if (ipAddress.AddressFamily.ToString() == "InterNetwork")
{
return ipAddress.ToString();
}
}
return "-";
}
Get your INTERNET IP address
Because, there isn't any built in function in .NET Framework, to get your Internet IP address when connected through router, we must use external service from DynDNS.org.
/// <summary>
/// Get computer INTERNET address like 93.136.91.7
/// </summary>
/// <returns></returns>
private string GetComputer_InternetIP()
{
// check IP using DynDNS's service
WebRequest request = WebRequest.Create("http://checkip.dyndns.org");
WebResponse response = request.GetResponse();
StreamReader stream = new StreamReader(response.GetResponseStream());
// IMPORTANT: set Proxy to null, to drastically INCREASE the speed of request
request.Proxy = null;
// read complete response
string ipAddress = stream.ReadToEnd();
// replace everything and keep only IP
return ipAddress.
Replace("<html><head><title>Current IP Check</title></head><body>Current IP Address: ", string.Empty).
Replace("</body></html>", string.Empty);
}