C#使用套接字发送信息

本文详细介绍了C#编程中使用套接字发送消息、UDP通信、Windows Form窗口程序的实践,包括服务器端与客户端编程,单线程与多线程端口扫描技术,并附带抓包技巧。适合初学者和进阶者深入理解网络编程技术。
摘要由CSDN通过智能技术生成

前言

提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。


提示:以下是本篇文章正文内容,下面案例可供参考

一、输出helloworld

1.项目创建

在这里插入图片描述
在这里插入图片描述

2.代码实现

在main函数中添加如下代码
在这里插入图片描述

for (int i = 0; i < 50; i++)
            {
                Console.WriteLine("Hello World!");
            }

3.运行

在这里插入图片描述

二、UDP套接字发送消息

1. 服务器端编程

创建新的控制台程序

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

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

            //得到本机IP,设置TCP端口号         
            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 Remote = (EndPoint)(sender);
            recv = newsock.ReceiveFrom(data, ref Remote);//接收客户端发送的消息
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));

            //客户机连接成功后,发送信息
            string welcome = "你好 ! ";

            //字符串与字节数组相互转换
            data = Encoding.UTF8.GetBytes(welcome);

            //发送信息
            newsock.SendTo(data, data.Length, SocketFlags.None, Remote);
            while (true)
            {
                data = new byte[1024];
                //接收信息
                recv = newsock.ReceiveFrom(data, ref Remote);
                Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
                //newsock.SendTo(data, recv, SocketFlags.None, Remote);
            }
        }
       
    }
}


2.客户端编程

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

namespace UDPclick
{
    internal class Program
    {
        static void Main(string[] args)
        {
            byte[] data = new byte[1024];
            string input, stringData;

            //构建TCP 服务器
            Console.WriteLine("This is a Client, host name is {0}", Dns.GetHostName());

            //设置服务IP(这个IP地址是服务器的IP),设置TCP端口号
            IPEndPoint ip = new IPEndPoint(IPAddress.Parse("10.61.35.85"), 8001);

            //定义网络类型,数据连接类型和网络协议UDP
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            string welcome = "你好! ";
            data = Encoding.UTF8.GetBytes(welcome);
            server.SendTo(data, data.Length, SocketFlags.None, ip);
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;

            data = new byte[1024];
            //对于不存在的IP地址,加入此行代码后,可以在指定时间内解除阻塞模式限制
            int recv = server.ReceiveFrom(data, ref Remote);
            Console.WriteLine("Message received from {0}: ", Remote.ToString());
            Console.WriteLine(Encoding.UTF8.GetString(data, 0, recv));
            int i = 0;
            while (true)
            {
                string s = "hello cqjtu!重交物联2019级" + i;
                Console.WriteLine(s);
                server.SendTo(Encoding.UTF8.GetBytes(s), Remote);
                if (i == 50)
                {
                    break;
                }
                i++;
            }
            Console.WriteLine("Stopping Client.");
            server.Close();
        }
        
    }
}

3.运行结果

在这里插入图片描述

三、VS编写简单Form窗口程序

1.创建客户端Windows窗体应用

在这里插入图片描述

(1)窗体设计

在右侧工具栏中拖进来两个textBox和两个Button
在这里插入图片描述

如果需要改变textBox的高度,则需要在其属性中将Multiline设置为true

(2)代码实现

在Form1.cs中写入

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

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void button1_Click(object sender, EventArgs e)
        {

            socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint point = new IPEndPoint(IPAddress.Parse("10.61.35.85"), 8001);
            socketSend.Connect(point);
            showMsg("连接成功!");
            Thread th = new Thread(Receive);
            th.IsBackground = true;
            th.Start();
        }
        //客户端接收服务器发送的消息
        void Receive()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    Invoke(new Action(() => {//在线程里修改界面
                        showMsg(socketSend.RemoteEndPoint + ":" + str);
                    }));
                }
            }
            catch
            { }
        }
        void showMsg(string s)
        {
            textBox1.AppendText(s + "\r\n");
        }
        //客户端向服务器发送消息


        private void button2_Click(object sender, EventArgs e)
        {
            string str = textBox2.Text;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }
    }
}

2.创建服务器端窗体应用

(1)窗体实现

在这里插入图片描述

(2)代码实现

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

namespace muti_thread_server
{
    public partial class Form1 : Form
    {
        string str="没有改变";
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //点击开始侦听的时候,服务器创建一个负责监听IP地址跟端口号的Socket
                Socket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;
                //创建端口对象
                IPEndPoint point = new IPEndPoint(ip, 8001);
                //绑定
                socketwatch.Bind(point);

                showMsg("监听成功!");
                socketwatch.Listen(10);
                //创建一个线程
                Thread th = new Thread(listen);
                th.IsBackground = true;
                th.Start(socketwatch);

            }
            catch
            {
                showMsg("监听失败");
            }

        }
        Socket socketSend;
        //等待客户端的连接
        void listen(Object o)
        {
            try
            {
                
                Socket socketwatch = o as Socket;
                int i = 0;
                while (true)
                {
                    //等待客户端的连接
                    socketSend = socketwatch.Accept();

                    str = socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!";
                    Invoke(new Action(() => {//在线程里修改界面
                        showMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                    }));
                    Thread th = new Thread(Receive);
                    th.IsBackground = true;
                    th.Start(socketSend);
                }
            }
            catch
            {            }
        }
        //接收客户端发送的信息
        void Receive(Object o)
        {
            try
            {
                Socket socketSend = o as Socket;
                while (true)
                {
                    byte[] buffer = new byte[1024 * 1024 * 2];
                    int r = socketSend.Receive(buffer);
                    if (r == 0)
                    {
                        break;
                    }
                    string str = Encoding.UTF8.GetString(buffer, 0, r);
                    Invoke(new Action(() => {//在线程里修改界面
                        showMsg(socketSend.RemoteEndPoint + ":" + str);
                    }));
                }
            }
            catch
            {            }
        }
        void showMsg(string str)
        {
            textBox1.AppendText(str + "\r\n");
        }
        //服务器给客户端发送消息

        private void button2_Click_1(object sender, EventArgs e)
        {
            string str = textBox2.Text;
            Console.WriteLine(str);
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }
    }
}


3.运行结果

在这里插入图片描述

四、端口扫描

1.单线程端口扫描

(1)界面设计

在这里插入图片描述

(2)代码实现

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

namespace WindowsFormsApp3
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //自定义变量
        private int port;//记录当前扫描的端口号
        private string Address;//记录扫描的系统地址
        private bool[] done = new bool[65536];//记录端口的开放状态
        private int start;//记录扫描的起始端口
        private int end;//记录扫描的结束端口
        private bool OK;
        private void button1_Click(object sender, EventArgs e)
        {
           // label2.Text = textBox3.Text;
           // label3.Text = textBox4.Text;
            progressBar1.Minimum = Int32.Parse(textBox3.Text);
            progressBar1.Maximum = Int32.Parse(textBox4.Text);
            listBox1.Items.Clear();
            listBox1.Items.Add("端口扫描器v1.0.");
            listBox1.Items.Add("");
            PortScan();
        }
        private void PortScan()
        {
            start = Int32.Parse(textBox3.Text);
            end = Int32.Parse(textBox4.Text);
            //判断输入端口是否合法
            if ((start >= 0 && start <= 65536) && (end >= 0 && end <= 65536) && (start <= end))
            {
                listBox1.Items.Add("开始扫描:这个过程可能需要等待几分钟!");
                Address = textBox2.Text;
                for (int i = start; i <= end; i++)
                {
                    port = i;
                    Scan();
                    progressBar1.Value = i;
                  //  label3.Text = i.ToString();
                }
                while (!OK)
                {
                    OK = true;
                    for (int i = start; i <= end; i++)
                    {
                        if (!done[i])
                        {
                            OK = false;
                            break;
                        }
                    }
                }
                listBox1.Items.Add("扫描结束!");
            }
            else
            {
                MessageBox.Show("输入错误,端口范围为[0,65536]");
            }
        }
        //连接端口
        private void Scan()
        {
            int portnow = port;
            done[portnow] = true;
            TcpClient objTCP = null;
            try
            {
                objTCP = new TcpClient(Address, portnow);
                listBox1.Items.Add("端口" + portnow.ToString() + "开放");
            }
            catch
            {

            }

        }

      
    }
}


(3)运行结果

仅仅扫描10个端口,但运行速度很慢
在这里插入图片描述

2.多线程端口扫描

(1)窗体设计

在这里插入图片描述

(2)代码实现

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

namespace WindowsFormsApp4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        //自定义变量
        private int port;//记录当前扫描的端口号
        private string Address;//记录扫描的系统地址
        private bool[] done = new bool[65536];//记录端口是否已经扫描
        private int start;//记录扫描的起始端口
        private int end;//记录扫描的结束端口
        private bool OK;
        private Thread scanThread;
       
        private void label4_TextChanged(object sender, EventArgs e)
        {
            label4.Text = textBox2.Text;//设定进度条的起始端口
        }
        private void label6_TextChanged(object sender, EventArgs e)
        {
            label6.Text = textBox3.Text;//设置进度条的终止端口
        }

      
        private void PortScan()
        {
            start = Int32.Parse(textBox2.Text);
            end = Int32.Parse(textBox3.Text);
            //检查端口的合法性
            if ((start >= 0 && start <= 65536) && (end >= 0 && end <= 65536) && (start <= end))
            {

                Invoke(new Action(() => {//在线程里修改界面
                    listBox1.Items.Add("开始扫描:这个过程可能需要等待几分钟!");
                }));
                Address = textBox1.Text;
                for (int i = start; i <= end; i++)
                {
                    port = i;
                    //对该端口进行扫描的线程
                    scanThread = new Thread(Scan);
                    scanThread.Start();
                    //使线程睡眠
                    System.Threading.Thread.Sleep(100);

                    Invoke(new Action(() => {//在线程里修改界面
                        progressBar1.Value = i;
                        label5.Text = i.ToString();
                    }));
                }
                //未完成时情况
                while (!OK)
                {
                    OK = true;
                    for (int i = start; i <= end; i++)
                    {
                        if (!done[i])
                        {
                            OK = false;
                            break;
                        }
                    }
                }

                Invoke(new Action(() => {//在线程里修改界面
                    listBox1.Items.Add("扫描结束!");
                }));
                System.Threading.Thread.Sleep(1000);
            }
            else
            {
                Invoke(new Action(() => {//在线程里修改界面
                    MessageBox.Show("输入错误,端口范围为[0,65536]");
                }));

            }
        }
        private void Scan()
        {
            int portnow = port;
            //创建线程变量
            Thread Threadnow = scanThread;
            done[portnow] = true;
            //创建TcpClient对象,TcpClient用于TCP网络服务提供客户端连接
            TcpClient objTCP = null;
            //扫描端口,成功就写入信息
            try
            {
                objTCP = new TcpClient(Address, portnow);
                Invoke(new Action(() => {//在线程里修改界面
                    listBox1.Items.Add("端口" + portnow.ToString() + "开放!");
                }));
                objTCP.Close();
            }
            catch
            {

            }
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            label4_TextChanged(sender, e);
            label6_TextChanged(sender, e);
            //创建线程
            Thread procss = new Thread(new ThreadStart(PortScan));
            procss.Start();
            //设定进度条的范围
            progressBar1.Minimum = Int32.Parse(textBox2.Text);
            progressBar1.Maximum = Int32.Parse(textBox3.Text);
            //显示框的初始化
            listBox1.Items.Clear();
            listBox1.Items.Add("端口扫描器 v1.0");
            listBox1.Items.Add(" ");
        }

    }
}



(3)运行结果

本次查询190个端口,但速度很快
在这里插入图片描述

4.抓包

在这里插入图片描述

参考文章

https://blog.csdn.net/qq_45659777/article/details/121481726?spm=1001.2014.3001.5501
https://blog.csdn.net/junseven164/article/details/121469255?spm=1001.2014.3001.5501

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值