C# 获取内网或公网IPAddress

内网IPAddress

public static string InternalNetworkIpAddress
{
    get
    {
        var iPAddresses =
            Dns
                .GetHostAddresses(Dns.GetHostName())
                .Where(ip =>
                    ip.GetAddressBytes().Length == 4
                )
                .Select(iPAddress =>
                    iPAddress
                );

        return string.Join(", ", iPAddresses);
    }
}

公网IPAddress

public static string ExternalNetworkIpAddress

{
    get
    {
        return GetExternalNetworkIpAddress();
    }
}

private static string GetExternalNetworkIpAddress()
{
    const string message = "获取失败";
    const string url = "http://1212.ip138.com/ic.asp";
    try
    {
        var webRequest = WebRequest.Create(url);
        webRequest.Timeout = 10000;
        var stream = webRequest.GetResponse().GetResponseStream();
        var streamReader = new StreamReader(stream);
        var readValue = streamReader.ReadToEnd();
        const string pattern = @"([\d]{1,3}\.){3}[\d]{1,3}";
        var match = Regex.Match(readValue, pattern);
        return match.Success ? match.Value : message;
    }
    catch (Exception)
    {
        return message;
    }
}

你可能感兴趣的:(C#)