当前位置:网站首页>C network related operations
C network related operations
2022-04-23 17:56:00 【It technology ape】

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
/// <summary>
/// Network operation related classes
/// </summary>
public class NetHelper
{
#region Check the settings for IP Is the address correct , Return to the right IP Address
/// <summary>
/// Check the settings for IP Is the address correct , And return the correct IP Address , Invalid IP The address to return "-1".
/// </summary>
/// <param name="ip"> Set up IP Address </param>
//public static string GetValidIP(string ip)
//{
// if (PageValidate.IsIP(ip))
// {
// return ip;
// }
// else
// {
// return "-1";
// }
//}
#endregion
#region Check that the port number is set correctly , Return the correct port number
/// <summary>
/// Check that the port number is set correctly , And return the correct port number , Invalid port number returned -1.
/// </summary>
/// <param name="port"> Set the port number </param>
public static int GetValidPort(string port)
{
// Declare the correct port number returned
int validPort = -1;
// Minimum valid port number
const int MINPORT = 0;
// Maximum valid port number
const int MAXPORT = 65535;
// Check port number
try
{
// If the incoming port number is empty, an exception will be thrown
if (port == "")
{
throw new Exception(" The port number cannot be empty !");
}
// Detection port range
if ((Convert.ToInt32(port) < MINPORT) || (Convert.ToInt32(port) > MAXPORT))
{
throw new Exception(" Invalid port number range !");
}
// Assign a value to the port number
validPort = Convert.ToInt32(port);
}
catch (Exception ex)
{
string errMessage = ex.Message;
}
return validPort;
}
#endregion
#region In the form of string IP Address converted to IPAddress object
/// <summary>
/// In the form of string IP Address converted to IPAddress object
/// </summary>
/// <param name="ip"> In string form IP Address </param>
public static IPAddress StringToIPAddress(string ip)
{
return IPAddress.Parse(ip);
}
#endregion
#region Get the computer name of this computer
/// <summary>
/// Get the computer name of this computer
/// </summary>
public static string LocalHostName
{
get
{
return Dns.GetHostName();
}
}
#endregion
#region Get the local area network of this machine IP
/// <summary>
/// Get the local area network of this machine IP
/// </summary>
public static string LANIP
{
get
{
// Get native IP list ,IP The first item on the list is Lan IP, The second is wan IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
// If this machine IP The list is empty. , Returns an empty string
if (addressList.Length < 1)
{
return "";
}
// Return to the local area network IP
return addressList[0].ToString();
}
}
#endregion
#region Get the local in Internet Network wide area network IP
/// <summary>
/// Get the local in Internet Network wide area network IP
/// </summary>
public static string WANIP
{
get
{
// Get native IP list ,IP The first item on the list is Lan IP, The second is wan IP
IPAddress[] addressList = Dns.GetHostEntry(Dns.GetHostName()).AddressList;
// If this machine IP The list is smaller than 2, Returns an empty string
if (addressList.Length < 2)
{
return "";
}
// Return to the local wan IP
return addressList[1].ToString();
}
}
#endregion
#region Get the name of the remote client IP Address
/// <summary>
/// Get the name of the remote client IP Address
/// </summary>
/// <param name="clientSocket"> Client's socket object </param>
public static string GetClientIP(Socket clientSocket)
{
IPEndPoint client = (IPEndPoint)clientSocket.RemoteEndPoint;
return client.Address.ToString();
}
#endregion
#region Create a IPEndPoint object
/// <summary>
/// Create a IPEndPoint object
/// </summary>
/// <param name="ip">IP Address </param>
/// <param name="port"> Port number </param>
public static IPEndPoint CreateIPEndPoint(string ip, int port)
{
IPAddress ipAddress = StringToIPAddress(ip);
return new IPEndPoint(ipAddress, port);
}
#endregion
#region Create a TcpListener object
/// <summary>
/// Create an automatic assignment IP And the port of TcpListener object
/// </summary>
public static TcpListener CreateTcpListener()
{
// Create an automatically assigned network node
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 0);
return new TcpListener(localEndPoint);
}
/// <summary>
/// Create a TcpListener object
/// </summary>
/// <param name="ip">IP Address </param>
/// <param name="port"> port </param>
public static TcpListener CreateTcpListener(string ip, int port)
{
// Create a network node
IPAddress ipAddress = StringToIPAddress(ip);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
return new TcpListener(localEndPoint);
}
#endregion
#region Create one based on TCP Agreed Socket object
/// <summary>
/// Create one based on TCP Agreed Socket object
/// </summary>
public static Socket CreateTcpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
#endregion
#region Create one based on UDP Agreed Socket object
/// <summary>
/// Create one based on UDP Agreed Socket object
/// </summary>
public static Socket CreateUdpSocket()
{
return new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
}
#endregion
#region Get local endpoint
#region obtain TcpListener Object's local endpoint
/// <summary>
/// obtain TcpListener Object's local endpoint
/// </summary>
/// <param name="tcpListener">TcpListener object </param>
public static IPEndPoint GetLocalPoint(TcpListener tcpListener)
{
return (IPEndPoint)tcpListener.LocalEndpoint;
}
/// <summary>
/// obtain TcpListener Object's local endpoint IP Address
/// </summary>
/// <param name="tcpListener">TcpListener object </param>
public static string GetLocalPoint_IP(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// obtain TcpListener The port number of the local endpoint of the object
/// </summary>
/// <param name="tcpListener">TcpListener object </param>
public static int GetLocalPoint_Port(TcpListener tcpListener)
{
IPEndPoint localEndPoint = (IPEndPoint)tcpListener.LocalEndpoint;
return localEndPoint.Port;
}
#endregion
#region obtain Socket Object's local endpoint
/// <summary>
/// obtain Socket Object's local endpoint
/// </summary>
/// <param name="socket">Socket object </param>
public static IPEndPoint GetLocalPoint(Socket socket)
{
return (IPEndPoint)socket.LocalEndPoint;
}
/// <summary>
/// obtain Socket Object's local endpoint IP Address
/// </summary>
/// <param name="socket">Socket object </param>
public static string GetLocalPoint_IP(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Address.ToString();
}
/// <summary>
/// obtain Socket The port number of the local endpoint of the object
/// </summary>
/// <param name="socket">Socket object </param>
public static int GetLocalPoint_Port(Socket socket)
{
IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint;
return localEndPoint.Port;
}
#endregion
#endregion
#region Binding endpoints
/// <summary>
/// Binding endpoints
/// </summary>
/// <param name="socket">Socket object </param>
/// <param name="endPoint"> The endpoint to bind </param>
public static void BindEndPoint(Socket socket, IPEndPoint endPoint)
{
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
/// <summary>
/// Binding endpoints
/// </summary>
/// <param name="socket">Socket object </param>
/// <param name="ip"> The server IP Address </param>
/// <param name="port"> Server port </param>
public static void BindEndPoint(Socket socket, string ip, int port)
{
// Create endpoint
IPEndPoint endPoint = CreateIPEndPoint(ip, port);
// Binding endpoints
if (!socket.IsBound)
{
socket.Bind(endPoint);
}
}
#endregion
#region Appoint Socket Object to perform listening
/// <summary>
/// Appoint Socket Object to perform listening , By default, the maximum number of pending connections allowed is 100
/// </summary>
/// <param name="socket"> Perform listening Socket object </param>
/// <param name="port"> Port number monitored </param>
public static void StartListen(Socket socket, int port)
{
// Create local endpoint
IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);
// Bind to local endpoint
BindEndPoint(socket, localPoint);
// Start listening
socket.Listen(100);
}
/// <summary>
/// Appoint Socket Object to perform listening
/// </summary>
/// <param name="socket"> Perform listening Socket object </param>
/// <param name="port"> Port number monitored </param>
/// <param name="maxConnection"> Maximum number of pending connections allowed </param>
public static void StartListen(Socket socket, int port, int maxConnection)
{
// Create local endpoint
IPEndPoint localPoint = CreateIPEndPoint(NetHelper.LocalHostName, port);
// Bind to local endpoint
BindEndPoint(socket, localPoint);
// Start listening
socket.Listen(maxConnection);
}
/// <summary>
/// Appoint Socket Object to perform listening
/// </summary>
/// <param name="socket"> Perform listening Socket object </param>
/// <param name="ip"> Monitoring IP Address </param>
/// <param name="port"> Port number monitored </param>
/// <param name="maxConnection"> Maximum number of pending connections allowed </param>
public static void StartListen(Socket socket, string ip, int port, int maxConnection)
{
// Bind to local endpoint
BindEndPoint(socket, ip, port);
// Start listening
socket.Listen(maxConnection);
}
#endregion
#region Connect to based on TCP Protocol server
/// <summary>
/// Connect to based on TCP Protocol server , Connection successful return true, Otherwise return to false
/// </summary>
/// <param name="socket">Socket object </param>
/// <param name="ip"> The server IP Address </param>
/// <param name="port"> Server port number </param>
public static bool Connect(Socket socket, string ip, int port)
{
try
{
// Connect to server
socket.Connect(ip, port);
// Check connection status
return socket.Poll(-1, SelectMode.SelectWrite);
}
catch (SocketException ex)
{
throw new Exception(ex.Message);
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
}
}
#endregion
#region Send messages synchronously
/// <summary>
/// To the specified in a synchronized manner Socket Object to send a message
/// </summary>
/// <param name="socket">socket object </param>
/// <param name="msg"> Message sent </param>
public static void SendMsg(Socket socket, byte[] msg)
{
// Send a message
socket.Send(msg, msg.Length, SocketFlags.None);
}
/// <summary>
/// Use UTF8 The encoding format is synchronized to the specified Socket Object to send a message
/// </summary>
/// <param name="socket">socket object </param>
/// <param name="msg"> Message sent </param>
public static void SendMsg(Socket socket, string msg)
{
// Convert string messages into character arrays
byte[] buffer = System.Text.Encoding.Default.GetBytes(msg);
// Send a message
socket.Send(buffer, buffer.Length, SocketFlags.None);
}
#endregion
#region Receive messages synchronously
/// <summary>
/// Receive messages synchronously
/// </summary>
/// <param name="socket">socket object </param>
/// <param name="buffer"> Buffer for receiving messages </param>
public static void ReceiveMsg(Socket socket, byte[] buffer)
{
socket.Receive(buffer);
}
/// <summary>
/// Receive messages synchronously , And converted to UTF8 String in encoded format , Use 5000 Bytes of the default buffer receive .
/// </summary>
/// <param name="socket">socket object </param>
public static string ReceiveMsg(Socket socket)
{
// Define the receive buffer
byte[] buffer = new byte[5000];
// receive data , Gets the number of bytes received
int receiveCount = socket.Receive(buffer);
// Define temporary buffer
byte[] tempBuffer = new byte[receiveCount];
// Write the received data to the temporary buffer
Buffer.BlockCopy(buffer, 0, tempBuffer, 0, receiveCount);
// Convert to string , And return it
return System.Text.Encoding.Default.GetString(tempBuffer);
}
#endregion
#region Close based on Tcp Agreed Socket object
/// <summary>
/// Close based on Tcp Agreed Socket object
/// </summary>
/// <param name="socket"> To close Socket object </param>
public static void Close(Socket socket)
{
try
{
// prohibit Socket Object to receive and send data
socket.Shutdown(SocketShutdown.Both);
}
catch (SocketException ex)
{
throw ex;
}
finally
{
// close Socket object
socket.Close();
}
}
#endregion
#region Send email
/// <summary>
/// Send email , all SMTP The configuration information is in config In profile system.net Section settings .
/// </summary>
/// <param name="receiveEmail"> E-mail address </param>
/// <param name="msgSubject"> The title of the email </param>
/// <param name="msgBody"> The body of the email </param>
/// <param name="IsEnableSSL"> Open or not SSL</param>
public static bool SendEmail(string receiveEmail, string msgSubject, string msgBody, bool IsEnableSSL)
{
// Create email object
MailMessage email = new MailMessage();
// Set the email address of the recipient
email.To.Add(receiveEmail);
// Set the title of the message
email.Subject = msgSubject;
// Set the body of the message
email.Body = msgBody;
// Set mail to HTML Format
email.IsBodyHtml = true;
// establish SMTP client , Will automatically get... From the configuration file SMTP server information
SmtpClient smtp = new SmtpClient();
// Turn on SSL
smtp.EnableSsl = IsEnableSSL;
try
{
// Send email
smtp.Send(email);
return true;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
版权声明
本文为[It technology ape]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231753552319.html
边栏推荐
- Commonly used functions -- spineros:: and spineros::)
- Vite configure proxy proxy to solve cross domain
- Uniapp custom search box adaptation applet alignment capsule
- 122. 买卖股票的最佳时机 II-一次遍历
- Laser slam theory and practice of dark blue College Chapter 3 laser radar distortion removal exercise
- Land cover / use data product download
- In JS, t, = > Analysis of
- How to read literature
- Sword finger offer 22 The penultimate node in the linked list - speed pointer
- Auto.js 自定义对话框
猜你喜欢

JS get link? The following parameter name or value, according to the URL? Judge the parameters after

MySQL进阶学习之SQL优化【插入,主键,排序,分组,分页,计数】

2022年茶艺师(初级)考试模拟100题及模拟考试

C1小笔记【任务训练篇一】

2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition

Eigen learning summary

Uniapp custom search box adaptation applet alignment capsule

Summary of floating point double precision, single precision and half precision knowledge

干货 | 快速抽取缩略图是怎么练成的?

Go file operation
随机推荐
Leak detection and vacancy filling (VII)
239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
Tell the truth of TS
31. 下一个排列
高德地图搜索、拖拽 查询地址
470. 用 Rand7() 实现 Rand10()
102. 二叉树的层序遍历
Anchor location - how to set the distance between the anchor and the top of the page. The anchor is located and offset from the top
20222 return to the workplace
Gaode map search, drag and drop query address
【Appium】通过设计关键字驱动文件来编写脚本
2022 Jiangxi Photovoltaic Exhibition, China Distributed Photovoltaic Exhibition, Nanchang Solar Energy Utilization Exhibition
48. Rotate image
Transfer learning of five categories of pictures based on VGg
Commonly used functions -- spineros:: and spineros::)
MySQL进阶之索引【分类,性能分析,使用,设计原则】
386. Dictionary order (medium) - iteration - full arrangement
Write a regular
vite配置proxy代理解决跨域
JS high frequency interview questions