向聊天客户端添加安全性

如何解决向聊天客户端添加安全性

这是我的基本聊天程序,允许用户添加自己的IP并接收IP,以及用于通信的自定义端口。

在Windows窗体设计中,我有:

文本框--- textLocalIp

文本框--- textLocalPort

文本框--- textFriendIp

文本框--- textFriendPort

文本框--- textMessage

列表框--- listMessage

按钮---开始

按钮---发送

所以这是一个非常基本的客户端,但是我需要的帮助是使其安全/更加安全,因为当前的安全性还不好。

也许就像具有不同IP的隧道,这样您就不必知道接收方的IP,只需知道接收方提供的IP,然后再将其发送给接收方即可。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


using System.Net;
using System.Net.Sockets;



namespace Client
{
    public partial class Form1 : Form
    {
        Socket sck;
        EndPoint epLocal,epRemote;

        public Form1()
        {
            InitializeComponent();

            sck = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            sck.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress,true);

            textLocalIp.Text = GetLocalIP();
            textFriendIp.Text = GetLocalIP();

        }

        private string GetLocalIP()
        {
            IPHostEntry host;
            host = Dns.GetHostEntry(Dns.GetHostName());

            foreach (IPAddress ip in host.AddressList)
            {
                if (ip.AddressFamily == AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }

            return "127.0.0.1";

        }


        private void MessageCallBack(IAsyncResult aResult)
        {
            try
            {
                int size = sck.EndReceiveFrom(aResult,ref epRemote);
                if (size > 0)
                {
                    byte[] recievedData = new byte[1464];

                    recievedData = (byte[])aResult.AsyncState;

                    ASCIIEncoding eEncoding = new ASCIIEncoding();
                    string receivedMessage = eEncoding.GetString(recievedData);
                    listMessage.Items.Add("Sender: "+receivedMessage);

                }

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer,buffer.Length,SocketFlags.None,ref epRemote,new AsyncCallback(MessageCallBack),buffer);

            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.ToString());
            }

        }

 private void button1_Click(object sender,EventArgs e)
        {
            try
            {
                System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                byte[] msg = new byte[1500];
                msg = enc.GetBytes(textMessage.Text);

                sck.Send(msg);

                listMessage.Items.Add("Local:" + textMessage.Text);
                textMessage.Clear();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());

            }
        }

        private void start_Click(object sender,EventArgs e)
        {
            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(textLocalIp.Text),Convert.ToInt32(textLocalPort.Text));
                sck.Bind(epLocal);

                epRemote = new IPEndPoint(IPAddress.Parse(textFriendIp.Text),Convert.ToInt32(textFriendPort.Text));
                sck.Connect(epRemote);

                byte[] buffer = new byte[1500];
                sck.BeginReceiveFrom(buffer,buffer);

                start.Text = "Connected";
                start.Enabled = false;
                send.Enabled = true;
                textMessage.Focus();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

解决方法

使用通道实现套接字通信安全性更加困难。因此,我建议您对IP和传输内容进行加密。

对于IP加密,可以将TextBox的Passwordchar属性设置为*。

对于传输内容,您可以使用加密算法对其进行加密。

以下代码实现了服务器与多个客户端之间的通信,您可以在此基础上执行加密。

服务器:

 namespace Server
{
class Program
{
    private static byte[] result = new byte[1024];
    private static int myProt = 8885; 
    static Socket serverSocket;
    static void Main(string[] args)
    {
                   
        serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        serverSocket.Bind(new IPEndPoint(IPAddress.Any,myProt)); 
        serverSocket.Listen(10); //Set up to 10 queued connection requests
        Console.WriteLine("Start listening {0} successfully",serverSocket.LocalEndPoint.ToString());      
        Thread myThread = new Thread(ListenClientConnect);
        myThread.Start();
        Console.ReadLine();
    }
    /// <summary>
    /// Listen for Client connections
    /// </summary>
    private static void ListenClientConnect()
    {
        while (true)
        {
            Socket clientSocket = serverSocket.Accept();
            clientSocket.Send(Encoding.ASCII.GetBytes("Server Say Hello"));
            Thread receiveThread = new Thread(ReceiveMessage);
            receiveThread.Start(clientSocket);
        }
    }

    /// <summary>
    /// receive data
    /// </summary>
    /// <param name="clientSocket"></param>
    private static void ReceiveMessage(object clientSocket)
    {
        Socket myClientSocket = (Socket)clientSocket;
        while (true)
        {
            try
            {
                
                int receiveNumber = myClientSocket.Receive(result);
                Console.WriteLine("Receive client {0} message {1}",myClientSocket.RemoteEndPoint.ToString(),Encoding.ASCII.GetString(result,receiveNumber));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                myClientSocket.Shutdown(SocketShutdown.Both);
                myClientSocket.Close();
                break;
            }
        }
    }
}
}

客户:

namespace Client
{
class Program
{
    private static byte[] result = new byte[1024];
    static void Main(string[] args)
    {
        
        IPAddress ip = IPAddress.Parse("127.0.0.1");
        Socket clientSocket = new Socket(AddressFamily.InterNetwork,ProtocolType.Tcp);
        try
        {
            clientSocket.Connect(new IPEndPoint(ip,8885)); 
            Console.WriteLine("Successfully connected to the server");
        }
        catch
        {
            Console.WriteLine("Failed to connect to the server,please press Enter to exit!");
            return;
        }
        //Receive data through clientSocket
        int receiveLength = clientSocket.Receive(result);
        Console.WriteLine("Server:{0}",receiveLength));
        //Send data through clientSocket
        for (int i = 0; i <3; i++)
        {
            try
            {
                Thread.Sleep(1000); 
                string sendMessage = "client send Message Hellp" + DateTime.Now;
                clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));
                Console.WriteLine("Client:{0}" + sendMessage);
            }
            catch
            {
                clientSocket.Shutdown(SocketShutdown.Both);
                clientSocket.Close();
                break;
            }
        }
        Console.WriteLine("After sending,press Enter to exit");
        Console.ReadLine();
    }
}
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-