TCP/UDP编程基础(C#发送消息,端口扫描)

一、概念相关

1.套接字

所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议栈进行交互的接口

表示方法

套接字Socket=(IP地址:端口号),套接字的表示方法是点分十进制的lP地址后面写上端口号,中间用冒号或逗号隔开。每一个传输层连接唯一地被通信两端的两个端点(即两个套接字)所确定。例如:如果IP地址是210.37.145.1,而端口号是23,那么得到套接字就是(210.37.145.1:23)

2.TCP&&UDP

TCP
传输控制协议(TCP,Transmission Control Protocol)是一种面向连接的、可靠的、基于字节流的传输层通信协议,由IETF的RFC 793 定义。
TCP旨在适应支持多网络应用的分层协议层次结构。 连接到不同但互连的计算机通信网络的主计算机中的成对进程之间依靠TCP提供可靠的通信服务。TCP假设它可以从较低级别的协议获得简单的,可能不可靠的数据报服务。 原则上,TCP应该能够在从硬线连接到分组交换或电路交换网络的各种通信系统之上操作。
UDP
UDP 是User Datagram Protocol的简称, 中文名是用户数据包协议,是OSI(Open System Interconnection,开放式系统互联) 参考模型中一种无连接的传输层协议,提供面向事务的简单不可靠信息传送服务,IETF RFC 768 是UDP的正式规范。UDP在IP报文的协议号是17。

UDP协议与TCP协议一样用于处理数据包,在OSI模型中,两者都位于传输层,处于IP协议的上一层。UDP有不提供数据包分组、组装和不能对数据包进行排序的缺点,也就是说,当报文发送之后,是无法得知其是否安全完整到达的。UDP用来支持那些需要在计算机之间传输数据的网络应用。包括网络视频会议系统在内的众多的客户/服务器模式的网络应用都需要使用UDP协议。UDP协议从问世至今已经被使用了很多年,虽然其最初的光彩已经被一些类似协议所掩盖,但即使在今天UDP仍然不失为一项非常实用和可行的网络传输层协议。

二、UDP通信

1.项目创建

①由于我是在同一台电脑上运行的,因此需要建立两个项目,分别作为服务端和客户端。

在这里插入图片描述
②命令行/控制台输出hello world,这一步很简单

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace myc
{
   
    internal class Program
    {
   
        static void Main(string[] args)
        {
   
            Console.WriteLine("Hello World!");
        }
    }
}

2.代码及运行结果

①服务器端代码,需要先运行这一部分的代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace KHD
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            int recv;
            byte[] data = new byte[1024];

            //得到本机IP,设置UDP端口号         
            IPEndPoint ip = new IPEndPoint(IPAddress.Any, 8001);
            Socket newsock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //绑定网络地址并监听
            newsock.Bind(ip);

            Console.WriteLine("This is a Server, host name is {0}", Dns.GetHostName());

            //等待客户机连接
            Console.WriteLine("Waiting for a client");

            //得到客户机IP
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是使用C#语言和Visual Studio开发环境实现基于TCP的通信程序并对通信进行安全性设置的代码示例,其中实现了用户验证和加密信息内容两项安全性设置。 Server端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketServer { class Program { static void Main(string[] args) { try { // 创建一个TCP/IP socket Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 绑定IP地址和端口号 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8888); serverSocket.Bind(ipEndPoint); // 开始监听 serverSocket.Listen(10); Console.WriteLine("Server is running..."); while (true) { // 接收客户端连接 Socket clientSocket = serverSocket.Accept(); // 用户验证 if (!AuthenticateUser(clientSocket)) { Console.WriteLine("User authentication failed, disconnecting..."); clientSocket.Close(); continue; } // 加密信息内容 string message = "Welcome to the server."; byte[] encryptedMessage = EncryptMessage(message); // 发送加密后的信息给客户端 clientSocket.Send(encryptedMessage); // 关闭连接 clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // 用户验证 static bool AuthenticateUser(Socket clientSocket) { // 从客户端接收用户名和密码 byte[] buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string credentials = Encoding.ASCII.GetString(buffer, 0, bytesReceived); // 验证用户名和密码是否正确 if (credentials == "username:password") { return true; } else { return false; } } // 加密信息内容 static byte[] EncryptMessage(string message) { // 使用AES算法加密信息 byte[] key = Encoding.ASCII.GetBytes("1234567890123456"); byte[] iv = Encoding.ASCII.GetBytes("1234567890123456"); byte[] messageBytes = Encoding.ASCII.GetBytes(message); using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; // 创建加密器 ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV); // 加密信息 byte[] encryptedMessage = encryptor.TransformFinalBlock(messageBytes, 0, messageBytes.Length); return encryptedMessage; } } } } ``` Client端代码: ```csharp using System; using System.Net; using System.Net.Sockets; using System.Text; namespace SocketClient { class Program { static void Main(string[] args) { try { // 创建一个TCP/IP socket Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // 连接到服务器 IPAddress ipAddress = IPAddress.Parse("127.0.0.1"); IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 8888); clientSocket.Connect(ipEndPoint); // 发送用户名和密码进行验证 string credentials = "username:password"; byte[] buffer = Encoding.ASCII.GetBytes(credentials); clientSocket.Send(buffer); // 接收加密后的信息 buffer = new byte[1024]; int bytesReceived = clientSocket.Receive(buffer); string encryptedMessage = Encoding.ASCII.GetString(buffer, 0, bytesReceived); // 解密信息 string message = DecryptMessage(encryptedMessage); Console.WriteLine(message); // 关闭连接 clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } // 解密信息内容 static string DecryptMessage(string encryptedMessage) { // 使用AES算法解密信息 byte[] key = Encoding.ASCII.GetBytes("1234567890123456"); byte[] iv = Encoding.ASCII.GetBytes("1234567890123456"); byte[] encryptedMessageBytes = Encoding.ASCII.GetBytes(encryptedMessage); using (Aes aes = Aes.Create()) { aes.Key = key; aes.IV = iv; // 创建解密器 ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV); // 解密信息 byte[] messageBytes = decryptor.TransformFinalBlock(encryptedMessageBytes, 0, encryptedMessageBytes.Length); string message = Encoding.ASCII.GetString(messageBytes); return message; } } } } ``` 在上述代码中,我们使用了C#中的AES算法对信息进行加密和解密。同时,我们还实现了用户验证功能,当用户名和密码不正确时,会断开连接。具体实现方法是在服务器端接收客户端发送的用户名和密码,验证成功后才会进行通信。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值