1. 程式人生 > 其它 >C#網路操作相關的類

C#網路操作相關的類

using System;
using System.Text;
using System.Net.Sockets;
using System.Net.Mail;
using System.Net;
 
namespace CloveoNetHelper
{
    /// <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 檢查設定的埠號是否正確,返回正確的埠號
        /// <summary>
        /// 檢查設定的埠號是否正確,並返回正確的埠號,無效埠號返回-1。
        /// </summary>
        /// <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;
        }
        #endregion
 
        #region 將字串形式的IP地址轉換成IPAddress物件
        /// <summary>
        /// 將字串形式的IP地址轉換成IPAddress物件
        /// </summary>
        /// <param name="ip">字串形式的IP地址</param>        
        public static IPAddress StringToIPAddress(string ip)
        {
            return IPAddress.Parse(ip);
        }
        #endregion
 
        #region 獲取本機的計算機名
        /// <summary>
        /// 獲取本機的計算機名
        /// </summary>
        public static string LocalHostName
        {
            get
            {
                return Dns.GetHostName();
            }
        }
        #endregion
 
        #region 獲取本機的區域網IP
        /// <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();
            }
        }
        #endregion
 
        #region 獲取本機在Internet網路的廣域網IP
        /// <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();
            }
        }
        #endregion
 
        #region 獲取遠端客戶機的IP地址
        /// <summary>
        /// 獲取遠端客戶機的IP地址
        /// </summary>
        /// <param name="clientSocket">客戶端的socket物件</param>        
        public static string GetClientIP(Socket clientSocket)
        {
            IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;
            return client.Address.ToString();
        }
        #endregion
 
        #region 建立一個IPEndPoint物件
        /// <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);
        }
        #endregion
 
        #region 建立一個TcpListener物件
        /// <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);
        }
        #endregion
 
        #region 建立一個基於TCP協議的Socket物件
        /// <summary>
        /// 建立一個基於TCP協議的Socket物件
        /// </summary>        
        public static Socket CreateTcpSocket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        }
        #endregion
 
        #region 建立一個基於UDP協議的Socket物件
        /// <summary>
        /// 建立一個基於UDP協議的Socket物件
        /// </summary>        
        public static Socket CreateUdpSocket()
        {
            return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        }
        #endregion
 
        #region 獲取本地終結點
 
        #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;
        }
        #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
 
        #endregion
 
        #region 繫結終結點
        /// <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);
            }
        }
        #endregion
 
        #region 指定Socket物件執行監聽
        /// <summary>
        /// 指定Socket物件執行監聽,預設允許的最大掛起連線數為100
        /// </summary>
        /// <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);
        }
 
        /// <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(NetHelper.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);
        }
        #endregion
 
        #region 連線到基於TCP協議的伺服器
        /// <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)
        {
            try
            {
                //連線伺服器
                socket.Connect(ip, port);
 
                //檢測連線狀態
                return socket.Poll(-1, SelectMode.SelectWrite);
            }
            catch (SocketException ex)
            {
                throw new Exception(ex.Message);
                //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
            }
        }
        #endregion
 
        #region 以同步方式傳送訊息
        /// <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, Encoding.Default);
 
            //傳送訊息
            socket.Send(buffer, buffer.Length, SocketFlags.None);
        }
        #endregion
 
        #region 以同步方式接收訊息
        /// <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, Encoding.Default);
        }
        #endregion
 
        #region 關閉基於Tcp協議的Socket物件
        /// <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();
            }
        }
        #endregion
 
        #region 傳送電子郵件
        /// <summary>
        /// 傳送電子郵件,所有SMTP配置資訊均在config配置檔案中system.net節設定.
        /// </summary>
        /// <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;
 
            try
            {
                //傳送電子郵件
                smtp.Send(email);
 
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        #endregion
    }
}