實現效果
本輔助類主要是用來方便實現網絡相關操作,可以對IP或者域名進行相互解析,基於Socket的TCP/UDP相關操作,檢測本機是否聯網等相關的網絡操作。
實現步驟
在代碼引用相關的代碼實現動態調用。
實現代碼
輔助類具體的接口定義
/// 獲取本地機器IP地址
public static string GetLocalIP()
/// 檢查設置的IP地址是否正確,並返回正確的IP地址,無效IP地址返回"-1"。
public static string GetValidIP(string ip)
/// 檢查設置的端口號是否正確,並返回正確的端口號,無效端口號返回-1。
public static int GetValidPort(string port)
/// 將字符串形式的IP地址轉換成IPAddress對象
public static IPAddress StringToIPAddress(string ip)
/// 獲取本機的計算機名
public static string LocalHostName
/// 獲取本機的局域網IP
public static string LANIP
/// 獲取本機在Internet網絡的廣域網IP
public static string WANIP
/// 獲取遠程客戶機的IP地址
public static string GetClientIP(Socket clientSocket)
/// 創建一個IPEndPoint對象
public static IPEndPoint CreateIPEndPoint(string ip, int port)
/// 創建一個自動分配IP和端口的TcpListener對象
public static TcpListener CreateTcpListener()
/// 創建一個TcpListener對象
public static TcpListener CreateTcpListener(string ip, int port)
/// 創建一個基於TCP協議的Socket對象
public static Socket CreateTcpSocket()
/// 創建一個基於UDP協議的Socket對象
public static Socket CreateUdpSocket()
/// 獲取TcpListener對象的本地終結點
public static IPEndPoint GetLocalPoint(TcpListener tcpListener)
/// 獲取TcpListener對象的本地終結點的IP地址
public static string GetLocalPoint_IP(TcpListener tcpListener)
/// 獲取TcpListener對象的本地終結點的端口號
public static int GetLocalPoint_Port(TcpListener tcpListener)
/// 獲取Socket對象的本地終結點
public static IPEndPoint GetLocalPoint(Socket socket)
/// 獲取Socket對象的本地終結點的IP地址
public static string GetLocalPoint_IP(Socket socket)
/// 獲取Socket對象的本地終結點的端口號
public static int GetLocalPoint_Port(Socket socket)
/// 綁定終結點
public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
/// 綁定終結點
public static void BindEndPoint(Socket socket, string ip, int port)
/// 指定Socket對象執行監聽,默認允許的最大掛起連接數爲100
public static void StartListen(Socket socket, int port)
/// 指定Socket對象執行監聽
public static void StartListen(Socket socket, int port, int maxConnection)
/// 指定Socket對象執行監聽
public static void StartListen(Socket socket, string ip, int port, int maxConnection)
/// 連接到基於TCP協議的服務器,連接成功返回true,否則返回false
public static bool Connect(Socket socket, string ip, int port)
/// 以同步方式向指定的Socket對象發送消息
public static void SendMsg(Socket socket, byte[] msg)
/// 使用UTF8編碼格式以同步方式向指定的Socket對象發送消息
public static void SendMsg(Socket socket, string msg)
/// 以同步方式接收消息
public static void ReceiveMsg(Socket socket, byte[] buffer)
/// 以同步方式接收消息,並轉換爲UTF8編碼格式的字符串,使用5000字節的默認緩衝區接收。
public static string ReceiveMsg(Socket socket)
/// 關閉基於Tcp協議的Socket對象
public static void Close(Socket socket)
/// 檢測本機是否聯網
public static bool IsConnectedInternet()
/// 檢測本機是否聯網的連接屬性
public static InternetConnectionStatesType CurrentState
/// 檢測本機是否聯網(互聯網)
public static bool IsOnline()
/// 轉換主機域名DNS到IP地址
public static string ConvertDnsToIp(string hostname)
/// 轉換主機IP地址到DNS域名
public static string ConvertIpToDns(string ipAddress)
/// 根據IP端點獲取主機名稱
public static string GetHostName(IPEndPoint ipEndPoint)
/// 根據主機IP地址對象獲取主機名稱
public static string GetHostName(IPAddress ip)
/// 根據主機IP獲取主機名稱
public static string GetHostName(string hostIP)
/// 得到一臺機器的EndPoint端點
public static EndPoint GetNetworkAddressEndPoing(IPHostEntry entry)
/// 主機名是否存在
public static bool IsHostAvailable(string host)
/// 在主機名解析到一個IP主機實體
public static IPHostEntry ResolveHost(string host)
網絡輔助類使用例子代碼
private void btnNetWork_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("本機IP:{0} ", NetworkUtil.GetLocalIP());
sb.AppendFormat("檢測本機是否聯網:{0} ", NetworkUtil.IsConnectedInternet());
sb.AppendFormat("www.baidu.com域名IP:{0} ", NetworkUtil.ConvertDnsToIp("www.baidu.com"));
sb.AppendFormat("本機LocalHostName:{0} ", NetworkUtil.LocalHostName);
sb.AppendFormat("本機局域網IP:{0} ", NetworkUtil.LANIP);
sb.AppendFormat("本機廣域網IP:{0} ", NetworkUtil.WANIP);
Socket socket = NetworkUtil.CreateTcpSocket();
Socket udpsocket = NetworkUtil.CreateUdpSocket();
TcpListener listen = NetworkUtil.CreateTcpListener("127.0.0.1", 9900);
listen.Start(100);
MessageUtil.ShowTips(sb.ToString());
}
附上源碼
/// <summary>
/// 網絡相關操作輔助類
/// </summary>
public class NetworkUtil
{
/// <summary>
/// 獲取MAC地址
/// </summary>
/// <returns></returns>
public static string GetMacAddress()
{
string mac = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
mac = mo["MacAddress"].ToString();
break;
}
}
return mac;
}
/// <summary>
/// 獲取以太網卡的物理地址
/// </summary>
/// <returns></returns>
public static string GetMacAddress2()
{
NetworkInterface[] aclLocalNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
string result = "";
// 判斷所有網卡的mac地址
foreach (NetworkInterface adapter in aclLocalNetworkInterfaces)
{
// 網卡是以太網網卡
if (!IsEthernet(adapter))
{
continue;
}
// 將mac地址組織爲00:11:22:33:44:55的格式
result = GetMacAddr(adapter);
}
return result;
}
// 獲取mac地址
private static string GetMacAddr(NetworkInterface adapter)
{
String strMacAddr = "";
PhysicalAddress clMacAddr = adapter.GetPhysicalAddress();
byte[] abMacAddr = clMacAddr.GetAddressBytes();
for (int i = 0; i < abMacAddr.Length; i++)
{
strMacAddr = strMacAddr + abMacAddr[i].ToString("X2");
// 在每個字節間插入冒號
if (abMacAddr.Length - 1 != i)
{
strMacAddr = strMacAddr + ":";
}
}
return strMacAddr;
}
// 網卡是以太網網卡
private static bool IsEthernet(NetworkInterface adapter)
{
if (NetworkInterfaceType.Ethernet == adapter.NetworkInterfaceType)
{
return true;
}
return false;
}
/// <summary>
/// 獲取網卡列表
/// </summary>
/// <returns></returns>
public static List<KeyValuePair<string, string>> GetNetCardList()
{
List<KeyValuePair<string, string>> cardList = new List<KeyValuePair<string, string>>();
try
{
RegistryKey regNetCards = Registry.LocalMachine.OpenSubKey(Win32Utils.REG_NET_CARDS_KEY);
if (regNetCards != null)
{
string[] names = regNetCards.GetSubKeyNames();
RegistryKey subKey = null;
foreach (string name in names)
{
subKey = regNetCards.OpenSubKey(name);
if (subKey != null)
{
object o = subKey.GetValue("ServiceName");
object Description = subKey.GetValue("Description");
if (o != null)
{
KeyValuePair<string, string> p = new KeyValuePair<string, string>(o.ToString(), Description.ToString());
cardList.Add(p);
}
}
}
}
}
catch { }
return cardList;
}
/// <summary>
/// 獲取未經修改過的MAC地址(真實的特理地址)
/// </summary>
/// <param name="cardId">網卡ID</param>
/// <returns></returns>
public static string GetPhysicalAddr(string cardId)
{
string macAddress = string.Empty;
uint device = 0;
try
{
string driveName = "\\\\.\\" + cardId;
device = Win32Utils.CreateFile(driveName,
Win32Utils.GENERIC_READ | Win32Utils.GENERIC_WRITE,
Win32Utils.FILE_SHARE_READ | Win32Utils.FILE_SHARE_WRITE,
0, Win32Utils.OPEN_EXISTING, 0, 0);
if (device != Win32Utils.INVALID_HANDLE_VALUE)
{
byte[] outBuff = new byte[6];
uint bytRv = 0;
int intBuff = Win32Utils.PERMANENT_ADDRESS;
if (0 != Win32Utils.DeviceIoControl(device, Win32Utils.IOCTL_NDIS_QUERY_GLOBAL_STATS,
ref intBuff, 4, outBuff, 6, ref bytRv, 0))
{
string temp = string.Empty;
foreach (byte b in outBuff)
{
temp = Convert.ToString(b, 16).PadLeft(2, '0');
macAddress += temp;
temp = string.Empty;
}
}
}
}
finally
{
if (device != 0)
{
Win32Utils.CloseHandle(device);
}
}
return macAddress;
}
/// <summary>
/// 獲取IP地址
/// </summary>
public static string GetIPAddress()
{
string st = "";
ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection moc = mc.GetInstances();
foreach (ManagementObject mo in moc)
{
if ((bool)mo["IPEnabled"] == true)
{
//st=mo["IpAddress"].ToString();
System.Array ar;
ar = (System.Array)(mo.Properties["IpAddress"].Value);
st = ar.GetValue(0).ToString();
break;
}
}
moc = null;
mc = null;
return st;
}
/// <summary>
/// 獲取本地機器IP地址
/// </summary>
/// <returns></returns>
public static string GetLocalIP()
{
//string strHostIP = string.Empty;
//IPHostEntry oIPHost = Dns.GetHostEntry(Environment.MachineName);
//if (oIPHost.AddressList.Length > 0)
//{
// strHostIP = oIPHost.AddressList[0].ToString();
//}
//return strHostIP;
return GetIPAddress();
}
/// <summary>
/// 檢查設置的IP地址是否正確,並返回正確的IP地址,無效IP地址返回"-1"。
/// </summary>
/// <param name="ip">設置的IP地址</param>
/// <returns>非法IP 則返回 -1 </returns>
public static string GetValidIP(string ip)
{
if (ValidateUtil.IsValidIP(ip))
{
return ip;
}
else
{
return "-1";
}
}
/// <summary>
/// 檢查設置的端口號是否正確,並返回正確的端口號,無效端口號返回-1。
/// </summary>
/// <param name="port">設置的端口號</param>
public static int GetValidPort(string port)
{
//聲明返回的正確端口號
int validPort = -1;
validPort = ConvertHelper.ConvertTo<int>(port);
//最小有效端口號
const int MINPORT = 0;
//最大有效端口號
const int MAXPORT = 65535;
if (validPort <= MINPORT || validPort > MAXPORT)
{
throw new ArgumentException("參數port端口號範圍無效!");
}
return validPort;
}
/// <summary>
/// 將字符串形式的IP地址轉換成IPAddress對象
/// </summary>
/// <param name="ip">字符串形式的IP地址</param>
public static IPAddress StringToIPAddress(string ip)
{
return IPAddress.Parse(ip);
}
/// <summary>
/// 檢測指定的IP地址是否在兩個IP段中
/// </summary>
/// <param name="ip">指定的IP地址</param>
/// <param name="begip">起始ip</param>
/// <param name="endip">結束ip</param>
/// <returns></returns>
public static bool IsInIp(string ip, string begip, string endip)
{
int[] inip, begipint, endipint = new int[4];
inip = GetIp(ip);
begipint = GetIp(begip);
endipint = GetIp(endip);
for (int i = 0; i < 4; i++)
{
if (inip[i] < begipint[i] || inip[i] > endipint[i])
{
return false;
}
else if (inip[i] > begipint[i] || inip[i] < endipint[i])
{
return true;
}
}
return true;
}
/// <summary>
/// 將ip地址轉成整形數組
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
protected static int[] GetIp(string ip)
{
int[] retip = new int[4];
int i, count;
char c;
for (i = 0, count = 0; i < ip.Length; i++)
{
c = ip[i];
if (c != '.')
{
retip[count] = retip[count] * 10 + int.Parse(c.ToString());
}
else
{
count++;
}
}
return retip;
}
/// <summary>
/// 獲取本機的計算機名
/// </summary>
public static string LocalHostName
{
get
{
return Dns.GetHostName();
}
}
/// <summary>
/// 獲取本機的局域網IP
/// </summary>
public static string LANIP
{
get
{
//獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
//如果本機IP列表爲空,則返回空字符串
if (addressList.Length < 1)
{
return "";
}
//返回本機的局域網IP
return addressList[0].ToString();
}
}
/// <summary>
/// 獲取本機在Internet網絡的廣域網IP
/// </summary>
public static string WANIP
{
get
{
//獲取本機的IP列表,IP列表中的第一項是局域網IP,第二項是廣域網IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
//如果本機IP列表小於2,則返回空字符串
if (addressList.Length < 2)
{
return "";
}
//返回本機的廣域網IP
return addressList[1].ToString();
}
}
/// <summary>
/// 獲取遠程客戶機的IP地址
/// </summary>
/// <param name="clientSocket">客戶端的socket對象</param>
public static string GetClientIP(Socket clientSocket)
{
IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;
return client.Address.ToString();
}
/// <summary>
/// 創建一個IPEndPoint對象
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="port">端口號</param>
public static IPEndPoint CreateIPEndPoint(string ip, int port)
{
IPAddress ipAddress = StringToIPAddress(ip);
return new IPEndPoint(ipAddress, port);
}
/// <summary>
/// 創建一個自動分配IP和端口的TcpListener對象
/// </summary>
public static TcpListener CreateTcpListener()
{
//創建一個自動分配的網絡節點
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0);
return new TcpListener(localEndPoint);
}
/// <summary>
/// 創建一個TcpListener對象
/// </summary>
/// <param name="ip">IP地址</param>
/// <param name="port">端口</param>
public static TcpListener CreateTcpListener(string ip, int port)
{
//創建一個網絡節點
IPAddress ipAddress = StringToIPAddress(ip);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
return new TcpListener(localEndPoint);
}
/// <summary>
/// 創建一個基於TCP協議的Socket對象
/// </summary>
public static Socket CreateTcpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
/// <summary>
/// 創建一個基於UDP協議的Socket對象
/// </summary>
public static Socket CreateUdpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
#region 獲取TcpListener對象的本地終結點
/// <summary>
/// 獲取TcpListener對象的本地終結點
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static IPEndPoint GetLocalPoint(TcpListener tcpListener)
{
return (IPEndPoint)tcpListener.LocalEndpoint;
}
/// <summary>
/// 獲取TcpListener對象的本地終結點的IP地址
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static string GetLocalPoint_IP(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// 獲取TcpListener對象的本地終結點的端口號
/// </summary>
/// <param name="tcpListener">TcpListener對象</param>
public static int GetLocalPoint_Port(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Port;
}
/// <summary>
/// 獲取本機已被使用的網絡端點
/// </summary>
public IList<IPEndPoint> GetUsedIPEndPoint()
{
//獲取一個對象,該對象提供有關本地計算機的網絡連接和通信統計數據的信息。
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
//獲取有關本地計算機上的 Internet 協議版本 4 (IPV4) 傳輸控制協議 (TCP) 偵聽器的終結點信息。
IPEndPoint[] ipEndPointTCP = ipGlobalProperties.GetActiveTcpListeners();
//獲取有關本地計算機上的 Internet 協議版本 4 (IPv4) 用戶數據報協議 (UDP) 偵聽器的信息。
IPEndPoint[] ipEndPointUDP = ipGlobalProperties.GetActiveUdpListeners();
//獲取有關本地計算機上的 Internet 協議版本 4 (IPV4) 傳輸控制協議 (TCP) 連接的信息。
TcpConnectionInformation[] tcpConnectionInformation = ipGlobalProperties.GetActiveTcpConnections();
IList<IPEndPoint> allIPEndPoint = new List<IPEndPoint>();
foreach (IPEndPoint iep in ipEndPointTCP) allIPEndPoint.Add(iep);
foreach (IPEndPoint iep in ipEndPointUDP) allIPEndPoint.Add(iep);
foreach (TcpConnectionInformation tci in tcpConnectionInformation) allIPEndPoint.Add(tci.LocalEndPoint);
return allIPEndPoint;
}
/// <summary>
/// 判斷指定的網絡端點(只判斷端口)是否被使用
/// </summary>
public bool IsUsedIPEndPoint(int port)
{
foreach (IPEndPoint iep in GetUsedIPEndPoint())
{
if (iep.Port == port)
{
return true;
}
}
return false;
}
/// <summary>
/// 判斷指定的網絡端點(判斷IP和端口)是否被使用
/// </summary>
public bool IsUsedIPEndPoint(string ip, int port)
{
foreach (IPEndPoint iep in GetUsedIPEndPoint())
{
if (iep.Address.ToString() == ip && iep.Port == port)
{
return true;
}
}
return false;
}
#endregion
#region 獲取Socket對象的本地終結點
/// <summary>
/// 獲取Socket對象的本地終結點
/// </summary>
/// <param name="socket">Socket對象</param>
public static IPEndPoint GetLocalPoint(Socket socket)
{
return (IPEndPoint)socket.LocalEndPoint;
}
/// <summary>
/// 獲取Socket對象的本地終結點的IP地址
/// </summary>
/// <param name="socket">Socket對象</param>
public static string GetLocalPoint_IP(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// 獲取Socket對象的本地終結點的端口號
/// </summary>
/// <param name="socket">Socket對象</param>
public static int GetLocalPoint_Port(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Port;
}
#endregion
/// <summary>
/// 綁定終結點
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="endPoint">要綁定的終結點</param>
public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
{
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
/// <summary>
/// 綁定終結點
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="ip">服務器IP地址</param>
/// <param name="port">服務器端口</param>
public static void BindEndPoint(Socket socket, string ip, int port)
{
//創建終結點
IPEndPoint endPoint = CreateIPEndPoint(ip, port);
//綁定終結點
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
/// <summary>
/// 指定Socket對象執行監聽,默認允許的最大掛起連接數爲100
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="port">監聽的端口號</param>
public static void StartListen(Socket socket, int port)
{
//創建本地終結點
IPEndPoint localPoint = CreateIPEndPoint(NetworkUtil.LocalHostName, port);
//綁定到本地終結點
BindEndPoint(socket, localPoint);
//開始監聽
socket.Listen(100);
}
/// <summary>
/// 指定Socket對象執行監聽
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="port">監聽的端口號</param>
/// <param name="maxConnection">允許的最大掛起連接數</param>
public static void StartListen(Socket socket, int port, int maxConnection)
{
//創建本地終結點
IPEndPoint localPoint = CreateIPEndPoint(NetworkUtil.LocalHostName, port);
//綁定到本地終結點
BindEndPoint(socket, localPoint);
//開始監聽
socket.Listen(maxConnection);
}
/// <summary>
/// 指定Socket對象執行監聽
/// </summary>
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="ip">監聽的IP地址</param>
/// <param name="port">監聽的端口號</param>
/// <param name="maxConnection">允許的最大掛起連接數</param>
public static void StartListen(Socket socket, string ip, int port, int maxConnection)
{
//綁定到本地終結點
BindEndPoint(socket, ip, port);
//開始監聽
socket.Listen(maxConnection);
}
/// <summary>
/// 連接到基於TCP協議的服務器,連接成功返回true,否則返回false
/// </summary>
/// <param name="socket">Socket對象</param>
/// <param name="ip">服務器IP地址</param>
/// <param name="port">服務器端口號</param>
public static bool Connect(Socket socket, string ip, int port)
{
//連接服務器
socket.Connect(ip, port);
//檢測連接狀態
return socket.Poll(-1, SelectMode.SelectWrite);
}
/// <summary>
/// 以同步方式向指定的Socket對象發送消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="msg">發送的消息</param>
public static void SendMsg(Socket socket, byte[] msg)
{
//發送消息
socket.Send(msg, msg.Length, SocketFlags.None);
}
/// <summary>
/// 使用UTF8編碼格式以同步方式向指定的Socket對象發送消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="msg">發送的消息</param>
public static void SendMsg(Socket socket, string msg)
{
//將字符串消息轉換成字符數組
byte[] buffer = ConvertHelper.StringToBytes(msg);
//發送消息
socket.Send(buffer, buffer.Length, SocketFlags.None);
}
/// <summary>
/// 以同步方式接收消息
/// </summary>
/// <param name="socket">socket對象</param>
/// <param name="buffer">接收消息的緩衝區</param>
public static void ReceiveMsg(Socket socket, byte[] buffer)
{
socket.Receive(buffer);
}
/// <summary>
/// 以同步方式接收消息,並轉換爲UTF8編碼格式的字符串,使用5000字節的默認緩衝區接收。
/// </summary>
/// <param name="socket">socket對象</param>
public static string ReceiveMsg(Socket socket)
{
//定義接收緩衝區
byte[] buffer = new byte[5000];
//接收數據,獲取接收到的字節數
int receiveCount = socket.Receive(buffer);
//定義臨時緩衝區
byte[] tempBuffer = new byte[receiveCount];
//將接收到的數據寫入臨時緩衝區
Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount);
//轉換成字符串,並將其返回
return ConvertHelper.BytesToString(tempBuffer);
}
/// <summary>
/// 關閉基於Tcp協議的Socket對象
/// </summary>
/// <param name="socket">要關閉的Socket對象</param>
public static void Close(Socket socket)
{
try
{
//禁止Socket對象接收和發送數據
socket.Shutdown(SocketShutdown.Both);
}
catch (SocketException ex)
{
throw ex;
}
finally
{
//關閉Socket對象
socket.Close();
}
}
/// <summary>
/// 檢測本機是否聯網(互聯網)
/// </summary>
/// <param name="connectionDescription"></param>
/// <param name="reservedValue"></param>
/// <returns></returns>
[DllImport("wininet")]
private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
/// <summary>
/// 檢測本機是否聯網
/// </summary>
/// <returns></returns>
public static bool IsConnectedInternet()
{
int i = 0;
if (InternetGetConnectedState(out i, 0))
{
//已聯網
return true;
}
else
{
//未聯網
return false;
}
}
[DllImport("WININET", CharSet = CharSet.Auto)]
private static extern bool InternetGetConnectedState(ref InternetConnectionStatesType lpdwFlags, int dwReserved);
/// <summary>
/// 檢測本機是否聯網的連接屬性
/// </summary>
public static InternetConnectionStatesType CurrentState
{
get
{
InternetConnectionStatesType state = 0;
InternetGetConnectedState(ref state, 0);
return state;
}
}
/// <summary>
/// 檢測本機是否聯網(互聯網)
/// </summary>
/// <returns></returns>
public static bool IsOnline()
{
InternetConnectionStatesType connectionStatus = CurrentState;
return (!IsFlagged((int)InternetConnectionStatesType.Offline, (int)connectionStatus));
}
internal static bool IsFlagged(int flaggedEnum, int flaggedValue)
{
if ((flaggedEnum & flaggedValue) != 0)
return true;
else
return false;
}
/// <summary>
/// 轉換主機域名DNS到IP地址
/// </summary>
/// <param name="hostname">主機域名DNS</param>
/// <returns></returns>
public static string ConvertDnsToIp(string hostname)
{
IPHostEntry ipHostEntry = Dns.GetHostByName(hostname);
if (ipHostEntry != null)
{
return ipHostEntry.AddressList[0].ToString();
}
return null;
}
/// <summary>
/// 轉換主機IP地址到DNS域名
/// </summary>
/// <param name="ipAddress">主機IP地址</param>
/// <returns></returns>
public static string ConvertIpToDns(string ipAddress)
{
IPHostEntry ipHostEntry = Dns.Resolve(ipAddress);
if (ipHostEntry != null)
{
return ipHostEntry.HostName;
}
return null;
}
/// <summary>
/// 根據IP端點獲取主機名稱
/// </summary>
/// <param name="ipEndPoint">IP端點</param>
/// <returns></returns>
public static string GetHostName(IPEndPoint ipEndPoint)
{
return GetHostName(ipEndPoint.Address);
}
/// <summary>
/// 根據主機IP地址對象獲取主機名稱
/// </summary>
/// <param name="ip">主機IP地址對象</param>
/// <returns></returns>
public static string GetHostName(IPAddress ip)
{
return GetHostName(ip.ToString());
}
/// <summary>
/// 根據主機IP獲取主機名稱
/// </summary>
/// <param name="hostIP">主機IP</param>
/// <returns></returns>
public static string GetHostName(string hostIP)
{
try
{
return Dns.Resolve(hostIP).HostName;
}
catch
{
}
return null;
}
/// <summary>
/// 得到一臺機器的EndPoint端點
/// </summary>
/// <param name="entry">主機實體</param>
/// <returns></returns>
public static EndPoint GetNetworkAddressEndPoing(IPHostEntry entry)
{
return (new IPEndPoint(entry.AddressList[0], 0)) as EndPoint;
}
/// <summary>
/// 主機名是否存在
/// </summary>
/// <param name="host">主機名</param>
/// <returns></returns>
public static bool IsHostAvailable(string host)
{
return (ResolveHost(host) != null);
}
/// <summary>
/// 在主機名解析到一個IP主機實體
/// </summary>
/// <param name="host">主機名</param>
/// <returns></returns>
public static IPHostEntry ResolveHost(string host)
{
try { return Dns.Resolve(host); }
catch { }
return null;
}
}
/// <summary>
/// Internet連接狀態枚舉
/// </summary>
[Flags]
public enum InternetConnectionStatesType : int
{
ModemConnection = 0x1,
LANConnection = 0x2,
ProxyConnection = 0x4,
RASInstalled = 0x10,
Offline = 0x20,
ConnectionConfigured = 0x40
}
#region Win32Utils
internal class Win32Utils
{
public const string REG_NET_CARDS_KEY = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards";
public const uint GENERIC_READ = 0x80000000;
public const uint GENERIC_WRITE = 0x40000000;
public const uint FILE_SHARE_READ = 0x00000001;
public const uint FILE_SHARE_WRITE = 0x00000002;
public const uint OPEN_EXISTING = 3;
public const uint INVALID_HANDLE_VALUE = 0xffffffff;
public const uint IOCTL_NDIS_QUERY_GLOBAL_STATS = 0x00170002;
public const int PERMANENT_ADDRESS = 0x01010101;
[DllImport("kernel32.dll")]
public static extern int CloseHandle(uint hObject);
[DllImport("kernel32.dll")]
public static extern int DeviceIoControl(uint hDevice,
uint dwIoControlCode,
ref int lpInBuffer,
int nInBufferSize,
byte[] lpOutBuffer,
int nOutBufferSize,
ref uint lpbytesReturned,
int lpOverlapped);
[DllImport("kernel32.dll")]
public static extern uint CreateFile(string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
int lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
int hTemplateFile);
}
#endregion