当前位置:网站首页>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
边栏推荐
- 394. 字符串解码-辅助栈
- 209. 长度最小的子数组-滑动窗口
- 2022 judgment questions and answers for operation of refrigeration and air conditioning equipment
- 92. 反转链表 II-字节跳动高频题
- 587. 安装栅栏 / 剑指 Offer II 014. 字符串中的变位词
- Go file operation
- Vite configure proxy proxy to solve cross domain
- Leak detection and vacancy filling (VII)
- 41. 缺失的第一个正数
- Amount input box, used for recharge and withdrawal
猜你喜欢
MySQL_01_简单数据检索
92. Reverse linked list II byte skipping high frequency question
Gaode map search, drag and drop query address
Welcome to the markdown editor
2022江西储能技术展会,中国电池展,动力电池展,燃料电池展
2021长城杯WP
Halo open source project learning (II): entity classes and data tables
Go语言JSON包使用
极致体验,揭晓抖音背后的音视频技术
92. 反转链表 II-字节跳动高频题
随机推荐
31. Next arrangement
92. 反转链表 II-字节跳动高频题
239. Maximum value of sliding window (difficult) - one-way queue, large top heap - byte skipping high frequency problem
Index: teach you index from zero basis to proficient use
2022 tea artist (primary) examination simulated 100 questions and simulated examination
Go语言JSON包使用
2022 Jiangxi Photovoltaic Exhibition, China distributed Photovoltaic Exhibition, Nanchang solar energy utilization Exhibition
Use of list - addition, deletion, modification and query
470. Rand10() is implemented with rand7()
102. Sequence traversal of binary tree
编译原理 求first集 follow集 select集预测分析表 判断符号串是否符合文法定义(有源码!!!)
undefined reference to `Nabo::NearestNeighbourSearch
MySQL 中的字符串函数
Dry goods | how to extract thumbnails quickly?
Theory and practice of laser slam in dark blue College - Chapter 2 (odometer calibration)
SystemVerilog(六)-变量
Auto.js 自定义对话框
Open source key component multi_ Button use, including test engineering
MySQL_01_简单数据检索
Cloud native Virtualization: building edge computing instances based on kubevirt