using System;
using System.Text;
using System.Net.Sockets;
using System.Net.Mail;
using System.Net;
namespace DotNet.Utilities
{
/// <summary>
/// 網絡操作相關的類
/// </summary>
public class NetHelper
{
#region 檢查設定的IP位址是否正确,傳回正确的IP位址
/// <summary>
/// 檢查設定的IP位址是否正确,并傳回正确的IP位址,無效IP位址傳回"-1"。
/// </summary>
/// <param name="ip">設定的IP位址</param>
//public static string GetValidIP(string ip)
//{
// if (PageValidate.IsIP(ip))
// {
// return ip;
// }
// else
// return "-1";
//}
#endregion
#region 檢查設定的端口号是否正确,傳回正确的端口号
/// 檢查設定的端口号是否正确,并傳回正确的端口号,無效端口号傳回-1。
/// <param name="port">設定的端口号</param>
public static int GetValidPort(string port)
{
//聲明傳回的正确端口号
int validPort = -1;
//最小有效端口号
const int MINPORT = 0;
//最大有效端口号
const int MAXPORT = 65535;
//檢測端口号
try
{
//傳入的端口号為空則抛出異常
if (port == "")
{
throw new Exception("端口号不能為空!");
}
//檢測端口範圍
if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT))
throw new Exception("端口号範圍無效!");
//為端口号指派
validPort = Convert.ToInt32(port);
}
catch (Exception ex)
string errMessage = ex.Message;
return validPort;
}
#region 将字元串形式的IP位址轉換成IPAddress對象
/// 将字元串形式的IP位址轉換成IPAddress對象
/// <param name="ip">字元串形式的IP位址</param>
public static IPAddress StringToIPAddress(string ip)
return IPAddress.Parse(ip);
#region 擷取本機的計算機名
/// 擷取本機的計算機名
public static string LocalHostName
get
return Dns.GetHostName();
#region 擷取本機的區域網路IP
/// 擷取本機的區域網路IP
/// </summary>
public static string LANIP
//擷取本機的IP清單,IP清單中的第一項是區域網路IP,第二項是廣域網IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
//如果本機IP清單為空,則傳回空字元串
if (addressList.Length < 1)
return "";
//傳回本機的區域網路IP
return addressList[0].ToString();
#region 擷取本機在Internet網絡的廣域網IP
/// 擷取本機在Internet網絡的廣域網IP
public static string WANIP
//如果本機IP清單小于2,則傳回空字元串
if (addressList.Length < 2)
//傳回本機的廣域網IP
return addressList[1].ToString();
#region 擷取遠端客戶機的IP位址
/// 擷取遠端客戶機的IP位址
/// <param name="clientSocket">用戶端的socket對象</param>
public static string GetClientIP(Socket clientSocket)
IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;
return client.Address.ToString();
#region 建立一個IPEndPoint對象
/// 建立一個IPEndPoint對象
/// <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);
#region 建立一個TcpListener對象
/// 建立一個自動配置設定IP和端口的TcpListener對象
public static TcpListener CreateTcpListener()
//建立一個自動配置設定的網絡節點
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0);
return new TcpListener(localEndPoint);
/// 建立一個TcpListener對象
/// <param name="port">端口</param>
public static TcpListener CreateTcpListener(string ip, int port)
//建立一個網絡節點
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
#region 建立一個基于TCP協定的Socket對象
/// 建立一個基于TCP協定的Socket對象
public static Socket CreateTcpSocket()
return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
#region 建立一個基于UDP協定的Socket對象
/// 建立一個基于UDP協定的Socket對象
public static Socket CreateUdpSocket()
return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
#region 擷取本地終結點
#region 擷取TcpListener對象的本地終結點
/// 擷取TcpListener對象的本地終結點
/// <param name="tcpListener">TcpListener對象</param>
public static IPEndPoint GetLocalPoint(TcpListener tcpListener)
return (IPEndPoint)tcpListener.LocalEndpoint;
/// 擷取TcpListener對象的本地終結點的IP位址
public static string GetLocalPoint_IP(TcpListener tcpListener)
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Address.ToString();
/// 擷取TcpListener對象的本地終結點的端口号
public static int GetLocalPoint_Port(TcpListener tcpListener)
return localEndPoint.Port;
#region 擷取Socket對象的本地終結點
/// 擷取Socket對象的本地終結點
/// <param name="socket">Socket對象</param>
public static IPEndPoint GetLocalPoint(Socket socket)
return (IPEndPoint)socket.LocalEndPoint;
/// 擷取Socket對象的本地終結點的IP位址
public static string GetLocalPoint_IP(Socket socket)
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
/// 擷取Socket對象的本地終結點的端口号
public static int GetLocalPoint_Port(Socket socket)
#region 綁定終結點
/// 綁定終結點
/// <param name="socket">Socket對象</param>
/// <param name="endPoint">要綁定的終結點</param>
public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
if (!socket.IsBound)
socket.Bind(endPoint);
/// <param name="ip">伺服器IP位址</param>
/// <param name="port">伺服器端口</param>
public static void BindEndPoint(Socket socket, string ip, int port)
//建立終結點
IPEndPoint endPoint = CreateIPEndPoint(ip, port);
//綁定終結點
#region 指定Socket對象執行監聽
/// 指定Socket對象執行監聽,預設允許的最大挂起連接配接數為100
/// <param name="socket">執行監聽的Socket對象</param>
/// <param name="port">監聽的端口号</param>
public static void StartListen(Socket socket, int port)
//建立本地終結點
IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);
//綁定到本地終結點
BindEndPoint(socket, localPoint);
//開始監聽
socket.Listen(100);
/// 指定Socket對象執行監聽
/// <param name="maxConnection">允許的最大挂起連接配接數</param>
public static void StartListen(Socket socket, int port, int maxConnection)
socket.Listen(maxConnection);
/// <param name="ip">監聽的IP位址</param>
public static void StartListen(Socket socket, string ip, int port, int maxConnection)
BindEndPoint(socket, ip, port);
#region 連接配接到基于TCP協定的伺服器
/// 連接配接到基于TCP協定的伺服器,連接配接成功傳回true,否則傳回false
/// <param name="port">伺服器端口号</param>
public static bool Connect(Socket socket, string ip, int port)
//連接配接伺服器
socket.Connect(ip, port);
//檢測連接配接狀态
return socket.Poll(-1, SelectMode.SelectWrite);
catch (SocketException ex)
throw new Exception(ex.Message);
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
#region 以同步方式發送消息
/// 以同步方式向指定的Socket對象發送消息
/// <param name="socket">socket對象</param>
/// <param name="msg">發送的消息</param>
public static void SendMsg(Socket socket, byte[] msg)
//發送消息
socket.Send(msg, msg.Length, SocketFlags.None);
/// 使用UTF8編碼格式以同步方式向指定的Socket對象發送消息
public static void SendMsg(Socket socket, string msg)
//将字元串消息轉換成字元數組
byte[] buffer = ConvertHelper.StringToBytes(msg, Encoding.Default);
socket.Send(buffer, buffer.Length, SocketFlags.None);
#region 以同步方式接收消息
/// 以同步方式接收消息
/// <param name="buffer">接收消息的緩沖區</param>
public static void ReceiveMsg(Socket socket, byte[] buffer)
socket.Receive(buffer);
/// 以同步方式接收消息,并轉換為UTF8編碼格式的字元串,使用5000位元組的預設緩沖區接收。
/// <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, Encoding.Default);
#region 關閉基于Tcp協定的Socket對象
/// 關閉基于Tcp協定的Socket對象
/// <param name="socket">要關閉的Socket對象</param>
public static void Close(Socket socket)
//禁止Socket對象接收和發送資料
socket.Shutdown(SocketShutdown.Both);
throw ex;
finally
//關閉Socket對象
socket.Close();
#region 發送電子郵件
/// 發送電子郵件,所有SMTP配置資訊均在config配置檔案中system.net節設定.
/// <param name="receiveEmail">接收電子郵件的位址</param>
/// <param name="msgSubject">電子郵件的标題</param>
/// <param name="msgBody">電子郵件的正文</param>
/// <param name="IsEnableSSL">是否開啟SSL</param>
public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL)
//建立電子郵件對象
MailMessage email = new MailMessage();
//設定接收人的電子郵件位址
email.To.Add(receiveEmail);
//設定郵件的标題
email.Subject = msgSubject;
//設定郵件的正文
email.Body = msgBody;
//設定郵件為HTML格式
email.IsBodyHtml = true;
//建立SMTP用戶端,将自動從配置檔案中擷取SMTP伺服器資訊
SmtpClient smtp = new SmtpClient();
//開啟SSL
smtp.EnableSsl = IsEnableSSL;
//發送電子郵件
smtp.Send(email);
return true;
}
}
本文轉自蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366639,如需轉載請自行聯系原作者