当前位置:网站首页>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
边栏推荐
- MySQL 中的字符串函数
- Transfer learning of five categories of pictures based on VGg
- Add animation to the picture under V-for timing
- 土地覆盖/利用数据产品下载
- Index: teach you index from zero basis to proficient use
- Examination question bank and online simulation examination of the third batch (main person in charge) of special operation certificate of safety officer a certificate in Guangdong Province in 2022
- 2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
- 2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
- Halo 开源项目学习(二):实体类与数据表
- 2022年流动式起重机司机国家题库模拟考试平台操作
猜你喜欢
随机推荐
394. 字符串解码-辅助栈
Halo 开源项目学习(二):实体类与数据表
JS interview question: FN call. call. call. Call (FN2) parsing
Chrome浏览器的跨域设置----包含新老版本两种设置
102. Sequence traversal of binary tree
Gaode map search, drag and drop query address
92. Reverse linked list II byte skipping high frequency question
Logic regression principle and code implementation
Go对文件操作
Notes on common basic usage of eigen Library
Implementation of image recognition code based on VGg convolutional neural network
Go language JSON package usage
Arithmetic expression
油猴网站地址
Fashion classification case based on keras
C# 的数据流加密与解密
Some questions some questions some questions some questions
YOLOv4剪枝【附代码】
Ring back to origin problem - byte jumping high frequency problem
122. 买卖股票的最佳时机 II-一次遍历