Created
April 28, 2014 09:01
-
-
Save jpluimers/11366143 to your computer and use it in GitHub Desktop.
A small example in C# that uses the .NET framework class library. Now that IP addresses are not restricted IPv4 any more (which used to be 4 bytes that would fit in a long), but also can be IPv6 (which are 8 groups of 2 bytes totalling 16 bytes – coincidence or not the same size of a GUID), it is not a good idea to use the Address property of an…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
namespace ObsoleteConsoleApplication | |
{ | |
class Program | |
{ | |
private static IPAddress GetLocalIPAddress() | |
{ | |
if (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) | |
{ | |
return null; | |
} | |
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); | |
return host | |
.AddressList | |
.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork); | |
} | |
static void Main(string[] args) | |
{ | |
IPAddress localIpAddress = GetLocalIPAddress(); | |
long ipv4 = localIpAddress.Address; // Warning 1 'System.Net.IPAddress.Address' is obsolete: 'This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202' | |
Console.WriteLine("ipv4={0}", ipv4); | |
Console.WriteLine("local IP address '{0}'", localIpAddress); | |
} | |
/* from the FCL source: | |
* | |
[Obsolete("This property has been deprecated. It is address family dependent. Please use IPAddress.Equals method to perform comparisons. http://go.microsoft.com/fwlink/?linkid=14202")] | |
public long Address { get; set; } | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment