(二)NetHelper
【转】http://blog.csdn.net/dingxiaowei2013/article/details/8113454
1 using System; 2 using System.Text; 3 using System.NET.Sockets; 4 using System.Net.Mail; 5 using System.Net; 6 namespace DotNet.Utilities 7 { 8 /// <summary> 9 /// 网络操作相关的类 10 /// </summary> 11 public class NetHelper 12 { 13 #region 检查设置的IP地址是否正确,返回正确的IP地址 14 /// <summary> 15 /// 检查设置的IP地址是否正确,并返回正确的IP地址,无效IP地址返回"-1"。 16 /// </summary> 17 /// <param name="ip">设置的IP地址</param> 18 //public static string GetValidIP(string ip) 19 //{ 20 // if (PageValidate.IsIP(ip)) 21 // { 22 // return ip; 23 // } 24 // else 25 // { 26 // return "-1"; 27 // } 28 //} 29 #endregion 30 #region 检查设置的端口号是否正确,返回正确的端口号 31 /// <summary> 32 /// 检查设置的端口号是否正确,并返回正确的端口号,无效端口号返回-1。 33 /// </summary> 34 /// <param name="port">设置的端口号</param> 35 public static int GetValidPort(string port) 36 { 37 //声明返回的正确端口号 38 int validPort = -1; 39 //最小有效端口号 40 const int MINPORT = 0; 41 //最大有效端口号 42 const int MAXPORT = 65535; 43 //检测端口号 44 try 45 { 46 //传入的端口号为空则抛出异常 47 if (port == "") 48 { 49 throw new Exception("端口号不能为空!"); 50 } 51 //检测端口范围 52 if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT)) 53 { 54 throw new Exception("端口号范围无效!"); 55 } 56 //为端口号赋值 57 validPort = Convert.ToInt32(port); 58 } 59 catch (Exception ex) 60 { 61 string errMessage = ex.Message; 62 } 63 return validPort; 64 } 65 #endregion 66 #region 将字符串形式的IP地址转换成IPAddress对象 67 /// <summary> 68 /// 将字符串形式的IP地址转换成IPAddress对象 69 /// </summary> 70 /// <param name="ip">字符串形式的IP地址</param> 71 public static IPAddress StringToIPAddress(string ip) 72 { 73 return IPAddress.Parse(ip); 74 } 75 #endregion 76 #region 获取本机的计算机名 77 /// <summary> 78 /// 获取本机的计算机名 79 /// </summary> 80 public static string LocalHostName 81 { 82 get 83 { 84 return Dns.GetHostName(); 85 } 86 } 87 #endregion 88 #region 获取本机的局域网IP 89 /// <summary> 90 /// 获取本机的局域网IP 91 /// </summary> 92 public static string LANIP 93 { 94 get 95 { 96 //获取本机的IP列表,IP列表中的第一项是局域网IP,第二项是广域网IP 97 IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; 98 //如果本机IP列表为空,则返回空字符串 99 if (addressList.Length < 1) 100 { 101 return ""; 102 } 103 //返回本机的局域网IP 104 return addressList[0].ToString(); 105 } 106 } 107 #endregion 108 #region 获取本机在Internet网络的广域网IP 109 /// <summary> 110 /// 获取本机在Internet网络的广域网IP 111 /// </summary> 112 public static string WANIP 113 { 114 get 115 { 116 //获取本机的IP列表,IP列表中的第一项是局域网IP,第二项是广域网IP 117 IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList; 118 //如果本机IP列表小于2,则返回空字符串 119 if (addressList.Length < 2) 120 { 121 return ""; 122 } 123 //返回本机的广域网IP 124 return addressList[1].ToString(); 125 } 126 } 127 #endregion 128 #region 获取远程客户机的IP地址 129 /// <summary> 130 /// 获取远程客户机的IP地址 131 /// </summary> 132 /// <param name="clientSocket">客户端的socket对象</param> 133 public static string GetClientIP(Socket clientSocket) 134 { 135 IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint; 136 return client.Address.ToString(); 137 } 138 #endregion 139 #region 创建一个IPEndPoint对象 140 /// <summary> 141 /// 创建一个IPEndPoint对象 142 /// </summary> 143 /// <param name="ip">IP地址</param> 144 /// <param name="port">端口号</param> 145 public static IPEndPoint CreateIPEndPoint(string ip, int port) 146 { 147 IPAddress ipAddress = StringToIPAddress(ip); 148 return new IPEndPoint(ipAddress, port); 149 } 150 #endregion 151 #region 创建一个TcpListener对象 152 /// <summary> 153 /// 创建一个自动分配IP和端口的TcpListener对象 154 /// </summary> 155 public static TcpListener CreateTcpListener() 156 { 157 //创建一个自动分配的网络节点 158 IPAddress ipAddress = IPAddress.Any; 159 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0); 160 return new TcpListener(localEndPoint); 161 } 162 /// <summary> 163 /// 创建一个TcpListener对象 164 /// </summary> 165 /// <param name="ip">IP地址</param> 166 /// <param name="port">端口</param> 167 public static TcpListener CreateTcpListener(string ip, int port) 168 { 169 //创建一个网络节点 170 IPAddress ipAddress = StringToIPAddress(ip); 171 IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); 172 return new TcpListener(localEndPoint); 173 } 174 #endregion 175 #region 创建一个基于TCP协议的Socket对象 176 /// <summary> 177 /// 创建一个基于TCP协议的Socket对象 178 /// </summary> 179 public static Socket CreateTcpSocket() 180 { 181 return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 182 } 183 #endregion 184 #region 创建一个基于UDP协议的Socket对象 185 /// <summary> 186 /// 创建一个基于UDP协议的Socket对象 187 /// </summary> 188 public static Socket CreateUdpSocket() 189 { 190 return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 191 } 192 #endregion 193 #region 获取本地终结点 194 #region 获取TcpListener对象的本地终结点 195 /// <summary> 196 /// 获取TcpListener对象的本地终结点 197 /// </summary> 198 /// <param name="tcpListener">TcpListener对象</param> 199 public static IPEndPoint GetLocalPoint(TcpListener tcpListener) 200 { 201 return (IPEndPoint)tcpListener.LocalEndpoint; 202 } 203 /// <summary> 204 /// 获取TcpListener对象的本地终结点的IP地址 205 /// </summary> 206 /// <param name="tcpListener">TcpListener对象</param> 207 public static string GetLocalPoint_IP(TcpListener tcpListener) 208 { 209 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; 210 return localEndPoint.Address.ToString(); 211 } 212 /// <summary> 213 /// 获取TcpListener对象的本地终结点的端口号 214 /// </summary> 215 /// <param name="tcpListener">TcpListener对象</param> 216 public static int GetLocalPoint_Port(TcpListener tcpListener) 217 { 218 IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint; 219 return localEndPoint.Port; 220 } 221 #endregion 222 #region 获取Socket对象的本地终结点 223 /// <summary> 224 /// 获取Socket对象的本地终结点 225 /// </summary> 226 /// <param name="socket">Socket对象</param> 227 public static IPEndPoint GetLocalPoint(Socket socket) 228 { 229 return (IPEndPoint)socket.LocalEndPoint; 230 } 231 /// <summary> 232 /// 获取Socket对象的本地终结点的IP地址 233 /// </summary> 234 /// <param name="socket">Socket对象</param> 235 public static string GetLocalPoint_IP(Socket socket) 236 { 237 IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; 238 return localEndPoint.Address.ToString(); 239 } 240 /// <summary> 241 /// 获取Socket对象的本地终结点的端口号 242 /// </summary> 243 /// <param name="socket">Socket对象</param> 244 public static int GetLocalPoint_Port(Socket socket) 245 { 246 IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; 247 return localEndPoint.Port; 248 } 249 #endregion 250 #endregion 251 #region 绑定终结点 252 /// <summary> 253 /// 绑定终结点 254 /// </summary> 255 /// <param name="socket">Socket对象</param> 256 /// <param name="endPoint">要绑定的终结点</param> 257 public static void BindEndPoint(Socket socket, IPEndPoint endPoint) 258 { 259 if (!socket.IsBound) 260 { 261 socket.Bind(endPoint); 262 } 263 } 264 /// <summary> 265 /// 绑定终结点 266 /// </summary> 267 /// <param name="socket">Socket对象</param> 268 /// <param name="ip">服务器IP地址</param> 269 /// <param name="port">服务器端口</param> 270 public static void BindEndPoint(Socket socket, string ip, int port) 271 { 272 //创建终结点 273 IPEndPoint endPoint = CreateIPEndPoint(ip, port); 274 //绑定终结点 275 if (!socket.IsBound) 276 { 277 socket.Bind(endPoint); 278 } 279 } 280 #endregion 281 #region 指定Socket对象执行监听 282 /// <summary> 283 /// 指定Socket对象执行监听,默认允许的最大挂起连接数为100 284 /// </summary> 285 /// <param name="socket">执行监听的Socket对象</param> 286 /// <param name="port">监听的端口号</param> 287 public static void StartListen(Socket socket, int port) 288 { 289 //创建本地终结点 290 IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port); 291 //绑定到本地终结点 292 BindEndPoint(socket, localPoint); 293 //开始监听 294 socket.Listen(100); 295 } 296 /// <summary> 297 /// 指定Socket对象执行监听 298 /// </summary> 299 /// <param name="socket">执行监听的Socket对象</param> 300 /// <param name="port">监听的端口号</param> 301 /// <param name="maxConnection">允许的最大挂起连接数</param> 302 public static void StartListen(Socket socket, int port, int maxConnection) 303 { 304 //创建本地终结点 305 IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port); 306 //绑定到本地终结点 307 BindEndPoint(socket, localPoint); 308 //开始监听 309 socket.Listen(maxConnection); 310 } 311 /// <summary> 312 /// 指定Socket对象执行监听 313 /// </summary> 314 /// <param name="socket">执行监听的Socket对象</param> 315 /// <param name="ip">监听的IP地址</param> 316 /// <param name="port">监听的端口号</param> 317 /// <param name="maxConnection">允许的最大挂起连接数</param> 318 public static void StartListen(Socket socket, string ip, int port, int maxConnection) 319 { 320 //绑定到本地终结点 321 BindEndPoint(socket, ip, port); 322 //开始监听 323 socket.Listen(maxConnection); 324 } 325 #endregion 326 #region 连接到基于TCP协议的服务器 327 /// <summary> 328 /// 连接到基于TCP协议的服务器,连接成功返回true,否则返回false 329 /// </summary> 330 /// <param name="socket">Socket对象</param> 331 /// <param name="ip">服务器IP地址</param> 332 /// <param name="port">服务器端口号</param> 333 public static bool Connect(Socket socket, string ip, int port) 334 { 335 try 336 { 337 //连接服务器 338 socket.Connect(ip, port); 339 //检测连接状态 340 return socket.Poll(-1, SelectMode.SelectWrite); 341 } 342 catch (SocketException ex) 343 { 344 throw new Exception(ex.Message); 345 //LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message); 346 } 347 } 348 #endregion 349 #region 以同步方式发送消息 350 /// <summary> 351 /// 以同步方式向指定的Socket对象发送消息 352 /// </summary> 353 /// <param name="socket">socket对象</param> 354 /// <param name="msg">发送的消息</param> 355 public static void SendMsg(Socket socket, byte[] msg) 356 { 357 //发送消息 358 socket.Send(msg, msg.Length, SocketFlags.None); 359 } 360 /// <summary> 361 /// 使用UTF8编码格式以同步方式向指定的Socket对象发送消息 362 /// </summary> 363 /// <param name="socket">socket对象</param> 364 /// <param name="msg">发送的消息</param> 365 public static void SendMsg(Socket socket, string msg) 366 { 367 //将字符串消息转换成字符数组 368 byte[] buffer = ConvertHelper.StringToBytes(msg, Encoding.Default); 369 //发送消息 370 socket.Send(buffer, buffer.Length, SocketFlags.None); 371 } 372 #endregion 373 #region 以同步方式接收消息 374 /// <summary> 375 /// 以同步方式接收消息 376 /// </summary> 377 /// <param name="socket">socket对象</param> 378 /// <param name="buffer">接收消息的缓冲区</param> 379 public static void ReceiveMsg(Socket socket, byte[] buffer) 380 { 381 socket.Receive(buffer); 382 } 383 /// <summary> 384 /// 以同步方式接收消息,并转换为UTF8编码格式的字符串,使用5000字节的默认缓冲区接收。 385 /// </summary> 386 /// <param name="socket">socket对象</param> 387 public static string ReceiveMsg(Socket socket) 388 { 389 //定义接收缓冲区 390 byte[] buffer = new byte[5000]; 391 //接收数据,获取接收到的字节数 392 int receiveCount = socket.Receive(buffer); 393 //定义临时缓冲区 394 byte[] tempBuffer = new byte[receiveCount]; 395 //将接收到的数据写入临时缓冲区 396 Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount); 397 //转换成字符串,并将其返回 398 return ConvertHelper.BytesToString(tempBuffer, Encoding.Default); 399 } 400 #endregion 401 #region 关闭基于Tcp协议的Socket对象 402 /// <summary> 403 /// 关闭基于Tcp协议的Socket对象 404 /// </summary> 405 /// <param name="socket">要关闭的Socket对象</param> 406 public static void Close(Socket socket) 407 { 408 try 409 { 410 //禁止Socket对象接收和发送数据 411 socket.Shutdown(SocketShutdown.Both); 412 } 413 catch (SocketException ex) 414 { 415 throw ex; 416 } 417 finally 418 { 419 //关闭Socket对象 420 socket.Close(); 421 } 422 } 423 #endregion 424 #region 发送电子邮件 425 /// <summary> 426 /// 发送电子邮件,所有SMTP配置信息均在config配置文件中system.net节设置. 427 /// </summary> 428 /// <param name="receiveEmail">接收电子邮件的地址</param> 429 /// <param name="msgSubject">电子邮件的标题</param> 430 /// <param name="msgBody">电子邮件的正文</param> 431 /// <param name="IsEnableSSL">是否开启SSL</param> 432 public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL) 433 { 434 //创建电子邮件对象 435 MailMessage email = new MailMessage(); 436 //设置接收人的电子邮件地址 437 email.To.Add(receiveEmail); 438 //设置邮件的标题 439 email.Subject = msgSubject; 440 //设置邮件的正文 441 email.Body = msgBody; 442 //设置邮件为HTML格式 443 email.IsBodyHtml = true; 444 //创建SMTP客户端,将自动从配置文件中获取SMTP服务器信息 445 SmtpClient smtp = new SmtpClient(); 446 //开启SSL 447 smtp.EnableSsl = IsEnableSSL; 448 try 449 { 450 //发送电子邮件 451 smtp.Send(email); 452 return true; 453 } 454 catch (Exception ex) 455 { 456 throw ex; 457 } 458 } 459 #endregion 460 } 461 }