C# 多线程与线程扫描器

实现Get请求:

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

namespace ConsoleApplication1
{
    class Program
    {
        public static string HttpGetPage(string url,string coding)
        {
            string pageHtml = string.Empty;
            try
            {
                using(WebClient MyWebClient = new WebClient())
                {
                    Encoding encode = Encoding.GetEncoding(coding);
                    MyWebClient.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
                    MyWebClient.Credentials = CredentialCache.DefaultCredentials;
                    Byte[] pageData = MyWebClient.DownloadData(url);
                    pageHtml = encode.GetString(pageData);
                }
            }
            catch { }
            return pageHtml;
        }

        static void Main(string[] args)
        {
            var html = HttpGetPage("https://www.baidu.com","utf-8");

            Console.WriteLine(html);
            Console.ReadKey();
        }
    }
}

Post请求发送键值对:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {

        public static string HttpPost(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64)AppleWebKit/537.36";
            req.ContentType = "application/x-www-form-urlencoded";
            #region
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();

            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        static void Main(string[] args)
        {
            string url = "http://www.baidu.com/";
            Dictionary<string, string> dic = new Dictionary<string, string> { };
            dic.Add("username","lyshark");
            HttpPost(url, dic);

            Console.ReadKey();
        }
    }
}

获取本机IP地址

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;


namespace ConsoleApplication1
{
    class Program
    {
        public static List<string> GetLocalAddress(string netType)
        {
            string HostName = Dns.GetHostName();
            IPAddress[] address = Dns.GetHostAddresses(HostName);
            List<string> IpList = new List<string>();

            if(netType == string.Empty)
            {
                for (int i = 0; i < address.Length; i++)
                {
                    IpList.Add(address[i].ToString());
                }
            }
            else
            {
                for (int i = 0; i < address.Length; i++)
                {
                    if (address[i].AddressFamily.ToString() == netType)
                    {
                        IpList.Add(address[i].ToString());
                    }
                }
            }
            return IpList;
        }

        static void Main(string[] args)
        {
            // 获取IPV4地址
            List<string> ipv4 = GetLocalAddress("InterNetwork");
            foreach (string each in ipv4)
                Console.WriteLine(each);

            // 获取IPV6地址
            List<string> ipv6 = GetLocalAddress("InterNetworkV6");
            foreach (string each in ipv6)
                Console.WriteLine(each);

            Console.ReadKey();
        }
    }
}

线程操作基础

using System;
using System.Collections;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        // 定义一个无参线程函数
        public static void My_Thread()
        {
            Console.WriteLine("线程函数已运行");
        }

        static void Main(string[] args)
        {
            string strinfo = string.Empty;

            ThreadStart childref = new ThreadStart(My_Thread);
            Thread thread = new Thread(childref);
            thread.Start();

            Console.WriteLine("线程唯一标识符: " + thread.ManagedThreadId);
            Console.WriteLine("线程名称: " + thread.Name);
            Console.WriteLine("线程状态: " + thread.ThreadState.ToString());
            Console.WriteLine("线程优先级: " + thread.Priority.ToString());
            Console.WriteLine("是否为后台线程: " + thread.IsBackground);

            Thread.Sleep(1000);
            thread.Join();

            Console.ReadKey();
        }
    }
}

线程传递参数

using System;
using System.Collections;
using System.Threading;

namespace ConsoleApplication1
{
    public struct ThreadObj
    {
        public string name;
        public int age;

        public ThreadObj(string _name, int _age)
        {
            this.name = _name;
            this.age = _age;
        }
    }

    class Program
    {
        // 定义一个无参线程函数
        public static void My_Thread(object obj)
        {
            ThreadObj thread_path = (ThreadObj)obj;
            Console.WriteLine("姓名: {0} 年纪: {1}", thread_path.name, thread_path.age);
            Thread.Sleep(3000);
        }

        static void Main(string[] args)
        {
            for(int x=0;x<200;x++)
            {
                ThreadObj obj = new ThreadObj("admin", x);
                Thread thread = new Thread(My_Thread);
                thread.IsBackground = true;

                thread.Start(obj);
            }
            Console.ReadKey();
        }
    }
}

实现端口扫描

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

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // FTP, SSH, Telnet, SMTP, HTTP, POP3, RPC, SMB, SMTP, IMAP, POP3
            int[] Port = new int[] { 21, 22, 23, 25, 80, 110, 135, 445, 587, 993, 995 };

            foreach(int each in Port)
            {
                Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                try
                {
                    sock.Connect("192.168.1.10",each);
                    if(sock.Connected)
                    {
                        Console.WriteLine("端口开启:" + each);
                    }
                }
                catch
                {
                    Console.WriteLine("端口关闭:" + each);
                    sock.Close();
                }
            }
        }
    }
}

多线程端口扫描

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

namespace TimeoutPortScan
{
    class TimeoutPortScan
    {
        private IPAddress ip;
        private readonly int[] ports = new int[] { 21, 22, 23, 25, 53, 80, 110, 118, 135, 143, 156, 161, 
            443, 445, 465, 587, 666, 990, 991, 993, 995, 1080, 1433, 1434, 1984, 2049, 2483, 2484, 3128, 
            3306, 3389, 4662, 4672, 5222, 5223, 5269, 5432, 5500, 5800, 5900, 8000, 8008, 8080 };

        public bool Connect(IPEndPoint remoteEndPoint, int timeoutMSec)
        {
            Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            try
            {
                IAsyncResult result = scanSocket.BeginConnect(remoteEndPoint, null, null);
                bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(timeoutMSec), false);
                if (result.IsCompleted && scanSocket.Connected)
                {
                    scanSocket.EndConnect(result);
                    return true;
                }
                else
                    return false;
            }
            finally
            {
                scanSocket.Close();
            }
        }

        static void Main(string[] args)
        {
            TimeoutPortScan ps = new TimeoutPortScan();

            for (int x = 1; x < 255;x++ )
            {
                string addr = string.Format("192.168.1.{0}", x);
                IPAddress.TryParse(addr, out ps.ip);

                for (int num = 0; num < ps.ports.Length; num++)
                {
                    if (ps.Connect(new IPEndPoint(ps.ip, ps.ports[num]), 100))
                        Console.WriteLine("IP:{0} --> 端口: {1} --> 状态: Open", addr,ps.ports[num]);
                }
            }
        }
    }
}

异步端口扫描

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

namespace AsyncPortScan
{
    class AsyncPortScan
    {
        static void Main(string[] args)
        {
            IPAddress ip;
            int startPort, endPort;
            if (GetPortRange(args, out ip, out startPort, out endPort) == true)  // 提取命令行参数
                Scan(ip, startPort, endPort);   // 端口扫描
        }

        /// 从命令行参数中提取端口
        private static bool GetPortRange(string[] args, out IPAddress ip, out int startPort, out int endPort)
        {
            ip = null;
            startPort = endPort = 0;
            // 帮助命令
            if (args.Length != 0 && (args[0] == "/?" || args[0] == "/h" || args[0] == "/help"))
            {
                Console.WriteLine("scan 192.168.1.10 100 2000");
                return false;
            }

            if (args.Length == 3)
            {
                // 解析端口号成功
                if (IPAddress.TryParse(args[0], out ip) && int.TryParse(args[1], out startPort) && int.TryParse(args[2], out endPort))
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }
        /// 端口 扫描
        static void Scan(IPAddress ip, int startPort, int endPort)
        {
            Random rand = new Random((int)DateTime.Now.Ticks);
            for (int port = startPort; port < endPort; port++)
            {
                Socket scanSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                //寻找一个未使用的端口进行绑定
                do
                {
                    try
                    {
                        scanSocket.Bind(new IPEndPoint(IPAddress.Any, rand.Next(65535)));
                        break;
                    }
                    catch
                    {
                        //绑定失败
                    }
                } while (true);

                try
                {
                    scanSocket.BeginConnect(new IPEndPoint(ip, port), ScanCallBack, new ArrayList() { scanSocket, port });
                }
                catch
                {
                    continue;
                }
            }
        }

        /// BeginConnect的回调函数 异步Connect的结果
        static void ScanCallBack(IAsyncResult result)
        {
            // 解析 回调函数输入 参数
            ArrayList arrList = (ArrayList)result.AsyncState;
            Socket scanSocket = (Socket)arrList[0];
            int port = (int)arrList[1];
            // 判断端口是否开放
            if (result.IsCompleted && scanSocket.Connected)
            {
                Console.WriteLine("端口: {0,5} 状态: Open", port);
            }
            scanSocket.Close();
        }
    }
}

版权声明: 本博客,文章与代码均为学习时整理的笔记,博客中除去明确标注有参考文献的文章,其他文章【均为原创】作品,转载请务必【添加出处】,您添加出处是我创作的动力!

警告:如果您恶意转载本人文章,则您的整站文章,将会变为我的原创作品,请相互尊重!
原文地址:https://www.cnblogs.com/LyShark/p/13545315.html