Monday
Dec092013
C# to get your local IP address when online.
Carl Franklin | Posted on Monday, December 9, 2013 at 01:50PM
This quick function returns your local IP address or an empty string if not connected or no ip address is found. Requires a "using System.Net;" statement.
/// <summary>
/// returns the first local IP address that's connected to the network
/// only if it's connected to the network.
/// </summary>
/// <returns></returns>
private string getLocalIPAddress()
{
string ret = "";
// Are we connected to the network?
if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
{
// get a list of local addresses
var addrs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in addrs)
{
// is this an IPv4 address?
if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// that's the one
ret = ip.ToString();
break;
}
}
}
return ret;
}
Comments Off