网络操作类

 

 

网络操作相关的类

1.检查设置的IP地址是否正确,返回正确的IP地址

2.检查设置的端口号是否正确,返回正确的端口号

3.将字符串形式的IP地址转换成IPAddress对象

4.获取本机的计算机名

5.获取本机的局域网IP

6.获取本机在Internet网络的广域网IP

7.获取远程客户机的IP地址

8.创建一个IPEndPoint对象

9.创建一个TcpListener对象

10.创建一个基于TCP协议的Socket对象

11.创建一个基于UDP协议的Socket对象

12.获取本地终结点

13.绑定终结点

14.指定Socket对象执行监听

15.连接到基于TCP协议的服务器

16.以同步方式发送消息

17.以同步方式接收消息

18.关闭基于Tcp协议的Socket对象

19.发送电子邮件

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

 

posted @ 2023-01-30 15:21  StarsOverTheSea  阅读(19)  评论(0)    收藏  举报