using System.Management;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Muchinfo.PC.Common.Helpers
{
public class IPHelper
{
///
/// 获取IP
///
/// 获取IP的站点
/// 开始字符串
/// 结束字符串
/// System.String.
public static string GetIP(string ipSite = "", string startString = "", string endString = "")
{
//WebRequest request = null;
try
{
//var uri = new Uri(ipSite);
//request = WebRequest.Create(uri);
//request.Timeout = 1000 * 5;
//var response = request.GetResponse();
//var stream = response.GetResponseStream();
//if (stream != null)
//{
// var reader = new StreamReader(stream, Encoding.Default);
// string result = reader.ReadToEnd();
// int start = result.IndexOf(startString, StringComparison.Ordinal) + startString.Length;
// int end = result.IndexOf(endString, start, System.StringComparison.Ordinal);
// var ip = result.Substring(start, end - start);
// response.Close();
// return ip.Trim();
//}
//response.Close();
return GetLocalIP();
}
catch
{
return GetLocalIP();
}
finally
{
//if (request != null) request.Abort();
}
}
///
/// 获取MAC地址
///
/// System.String.
public static string GetMACAddress()
{
var address = GetMACAddressByService();
if (string.IsNullOrWhiteSpace(address))
{
address = GetMACAddressByNetwork();
}
return address;
}
///
/// 获取MAC地址
///
/// System.String.
private static string GetMACAddressByService()
{
var str = string.Empty;
try
{
ManagementClass mc;
ManagementObjectCollection moc;
mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"]) return mo["MacAddress"].ToString();
}
}
catch
{
str = string.Empty;
}
return str;
}
///
/// 获取MAC地址
///
/// System.String.
public static string GetMACAddressByNetwork()
{
var nics = NetworkInterface.GetAllNetworkInterfaces();
//var macAddress = new StringBuilder();
foreach (NetworkInterface adapter in nics)
{
var mac = adapter.GetPhysicalAddress().ToString();
if (!string.IsNullOrEmpty(mac) && adapter.OperationalStatus == OperationalStatus.Up)
{
return mac;
//macAddress.Append(mac);
//macAddress.Append(",");
}
}
//return macAddress.ToString().TrimEnd(',');
return string.Empty;
}
///
/// 打开Web网址
///
/// 网址
public static void OpenWebAddress(string url)
{
System.Diagnostics.Process.Start(url);
}
///
/// 获取本地IP
///
/// System.String.
private static string GetLocalIP()
{
string strHostName = Dns.GetHostName();
var ipEntry = Dns.GetHostEntry(strHostName);
foreach (IPAddress ipAddress in ipEntry.AddressList)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
return ipAddress.ToString();
}
}
return "-";
}
}
}