During web development Software Engineer require local IP on the network where the application will run. For this network programming, problem is faced where the IP is not static, rather dynamically assigned through DHCP. Following C# code snippet returns the local IP Address if connected the local network.
If the computer is disconnected from the network, returns null
. Software Developer may change the code with respect to their requirement.
public string LocalIPAddress()
{
//check if connected to the local network
if(!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
return null;
IPHostEntry host;
string localIP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
break;
}
}
return localIP;
}
The code above works well with the other ASP.Net and .Net Framework supported programming languages like VB.Net.
Posted Status in Programming