C#基本网络操作

建档操作如ping,查询本机主机ip,同步异步查询局域网内主机,同步异步邮件发送等

 

1)ping

通过ping类测试网络

using System;
using System.Text;
using System.Net.NetworkInformation;

namespace PingExec
{
    class Program
    {
        static void Main(string[] args)
        {
            Ping ping = new Ping();
            PingOptions opt = new PingOptions();
            opt.DontFragment = true;

            string data = "aaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.Default.GetBytes(data);
            int timeout = 120;
            PingReply replay = ping.Send("192.168.1.101", timeout, buffer, opt);
            string result = "";

            if(replay.Status==IPStatus.Success)
            {
                result = "Address:{0}\r\nRoundTrip time:{1}\r\nTime to live:{2}\r\nDont fragment:{3}\r\n" +
                    "Buffer size:{4}";
                string str = string.Format(result, replay.Address.ToString(), replay.RoundtripTime, replay.Options.Ttl,
                    replay.Options.DontFragment, replay.Buffer.Length);
                Console.WriteLine(str);
            }
            Console.ReadKey();
        }
    }
}

2)查询本机ip与主机名

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

(一)通过Process类调用ipconfig.exe

        public static string GetIp()
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "ipconfig.exe";//设置程序名     
            cmd.StartInfo.Arguments = "/all";  //参数     
                                                   
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.StartInfo.CreateNoWindow = true;//不显示窗口(控制台程序是黑屏)     
  
            cmd.Start();
            string info = cmd.StandardOutput.ReadToEnd();
            cmd.WaitForExit();
            cmd.Close();
            return info;
        }

(二)通过DNS类获取

       static string GetLocalIp()
        {
            try
            {
                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
               // MessageBox.Show("获取本机IP出错:" + ex.Message);
                return "";
            }
        }
IpEntry.AddressList中包含所有ip,包括ip6,ip4(包括无线Ip4)

 3)搜索局域网内可ping通的主机

搜索网段范围内所有Ip并测试。

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

 

(一)非异步操作

       public static void SearchIP()
        {
            List<string> ipList = new List<string>();
            //获取本地机器名   
            string myHostName = Dns.GetHostName();
            //获取本机IP   
            string myHostIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString();
            Console.WriteLine(myHostIP);  
            //截取IP网段  
            string ipDuan = myHostIP.Remove(myHostIP.LastIndexOf('.'));
            //MessageBox.Show(ipDuan);  
            //枚举网段计算机  
            Ping myPing = new Ping();
            string pingData = "aaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(pingData);
            for (int i = 1; i <= 255; i++)
            {
                string pingIP = ipDuan + "." + i.ToString();
                PingReply pingReply = myPing.Send(pingIP, 120, buffer);
                if (pingReply.Status == IPStatus.Success)
                {
                    ipList.Add(pingIP);
                    //Console.Write("答复的主机地址:" + pingReply.Address.ToString() + "  ");
                    //Console.Write("往返时间:" + pingReply.RoundtripTime.ToString() + "  ");
                    //Console.Write("生存时间:" + pingReply.Options.Ttl.ToString() + "  ");
                    //Console.Write("是否控制数据包的分段:" + pingReply.Options.DontFragment.ToString() + "  ");
                    //Console.Write("缓冲区大小:" + pingReply.Buffer.Length.ToString() + "  ");
                    Console.WriteLine(pingIP);                    
                }
                Console.WriteLine("------------------" + i.ToString());
            }
        }

 

(二)异步操作

 

       public static void SearchIPAnsyc()
        {
            try
            {
                for (int i = 1; i <= 255; i++)
                {
                    Ping myPing = new Ping();
                    myPing.PingCompleted += new PingCompletedEventHandler(PingCompletedAction);

                    string pingIP = "192.168.1." + i.ToString();
                    myPing.SendAsync(pingIP, 2000, null);
                    Console.WriteLine("------------------" + i.ToString());
                }
            }
            catch
            {
                
            }
        }

        private static void PingCompletedAction(object sender, PingCompletedEventArgs e)    
        {
            List<string> ipList = new List<string>();
            if (e.Reply.Status == IPStatus.Success)    
            {  
                  ipList.Add(e.Reply.Address.ToString());
                  Console.Write(e.Reply.Address.ToString());
                Console.WriteLine("Ansyc-----------------------");
            }
           // Console.WriteLine("Ansyc-----------------------");
        } 

 

 4)通过 SmtpClient类发送电子邮件

using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Text;

首相通过MailMessage添加邮件发送信息,包括主题,内容,附件等。其中附件通过Attachment类添加。

MailMessage类主题

           string sendMail= "********@163.com";
            string sendPwd = "*********";

            MailAddress mailAddress = new MailAddress(sendMail);
            MailMessage mailMessage = new MailMessage();

            mailMessage.To.Add("*******@qq.com");//添加发送地址,可添加多个
            //mailMessage.CC.Add("00000@dd.com");//添加抄送地址
            mailMessage.From = mailAddress;
            mailMessage.Subject = "test";//主题
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.Body = "测试邮件";//正文            
            mailMessage.BodyEncoding = Encoding.Default;//正文的编码
            mailMessage.Priority = MailPriority.High;
            mailMessage.IsBodyHtml = true;

            //添加附件
            string[] attachments = new string[] { @"E:\C#\PingExec\NetHostSearch\bin\Debug\00.jpg" };
            try
            {
                if(attachments.Length>0)
                {
                    foreach(string attach in attachments)
                    {
                        Attachment attachment = new Attachment(attach);
                        mailMessage.Attachments.Add(attachment);
                        Console.WriteLine("Attach success");
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Attach failed"+ex.Message);
            }

 

定义发送协议

            //定义发送协议
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Credentials= new System.Net.NetworkCredential(sendMail, sendPwd);
            smtpClient.Host= "smtp.163.com";
smtpClient.Host对于不同的网址邮箱服务器不一样,比如扣扣邮箱则为"smtp.qq.com"

(一)同步发送

            try
            {
                smtpClient.Send(mailMessage);
                Console.WriteLine("Success");
            }
            catch (SmtpException ex)
            {
                Console.WriteLine("Failed:" + ex.Message);
            }
            mailMessage.Dispose();

(二)异步发送

 

            //异步发送  也可以用SendMailAsync 其返回值为task,既可以调用task的continWith方法
            smtpClient.SendCompleted += SendCompletedAction;
            smtpClient.SendAsync(mailMessage,null);            
            Console.ReadKey();

异步发送 结束后调用SendCompletedAction,其定义如下

        private static void SendCompletedAction(object sender, AsyncCompletedEventArgs e)
        {
            String token = (string)e.UserState;
            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
        }

 

发送邮件为了便于理解在此进行了分步分割,一下为完整代码,其中同步发送方法已注释:

using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Text;

namespace MailSendMgr
{ 
    class Program
    {
        static void Main(string[] args)
        {
            string sendMail= "***********@163.com";
            string sendPwd = "*************";

            MailAddress mailAddress = new MailAddress(sendMail);
            MailMessage mailMessage = new MailMessage();

            mailMessage.To.Add("************@qq.com");//添加发送地址,可添加多个
            //mailMessage.CC.Add("00000@dd.com");//添加抄送地址
            mailMessage.From = mailAddress;
            mailMessage.Subject = "test";//主题
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.Body = "测试邮件";//正文            
            mailMessage.BodyEncoding = Encoding.Default;//正文的编码
            mailMessage.Priority = MailPriority.High;
            mailMessage.IsBodyHtml = true;

            //添加附件
            string[] attachments = new string[] { @"E:\C#\PingExec\NetHostSearch\bin\Debug\00.jpg" };
            try
            {
                if(attachments.Length>0)
                {
                    foreach(string attach in attachments)
                    {
                        Attachment attachment = new Attachment(attach);
                        mailMessage.Attachments.Add(attachment);
                        Console.WriteLine("Attach success");
                    }
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Attach failed"+ex.Message);
            }

            //定义发送协议
            SmtpClient smtpClient = new SmtpClient();
            smtpClient.Credentials= new System.Net.NetworkCredential(sendMail, sendPwd);
            smtpClient.Host= "smtp.163.com";

            //发送
            //try
            //{
            //    smtpClient.Send(mailMessage);
            //    Console.WriteLine("Success");
            //}
            //catch (SmtpException ex)
            //{
            //    Console.WriteLine("Failed:" + ex.Message);
            //}
            //mailMessage.Dispose();

            //异步发送  也可以用SendMailAsync 其返回值为task,既可以调用task的continWith方法
            smtpClient.SendCompleted += SendCompletedAction;
            smtpClient.SendAsync(mailMessage,null);            
            Console.ReadKey();
        }

        private static void SendCompletedAction(object sender, AsyncCompletedEventArgs e)
        {
            String token = (string)e.UserState;
            if (e.Cancelled)
            {
                Console.WriteLine("[{0}] Send canceled.", token);
            }
            if (e.Error != null)
            {
                Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
            }
            else
            {
                Console.WriteLine("Message sent.");
            }
        }
    }
}

 

 5)扫描端口

using System;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace ScanPort
{
    class Program
    {
        private static int port;
        private static string IP;
        static void Main(string[] args)
        {
            string targetIP = args[0];
            int startPort =10;
            int endPort = 100;          
            Thread work;

            int result = Check(targetIP, startPort, endPort);
            IP = targetIP;
            switch(result)
            {
                case 100:
                    Console.WriteLine("开始扫描:");
                    for(int i=startPort;i<endPort;i++)
                    {
                        port = i;
                        work = new Thread(new ThreadStart(Scan));
                        work.Start();
                    }
                    Console.WriteLine("扫描结束:");
                    break;
                case 101:
                    Console.WriteLine("端口错误!");     
                    break;
                case 200:
                    Console.WriteLine("目标主机不可达!");
                    break;
                case 201:
                    Console.WriteLine("目标主机不可达,端口错误!");
                    break;
            }
            Console.ReadKey();
        }

        private static int PingTargetIP(string ip)
        {
            Ping ping = new Ping();
            PingOptions opt = new PingOptions();
            opt.DontFragment = true;

            string data = "aaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.Default.GetBytes(data);
            int timeout = 120;
            PingReply replay = ping.Send(ip, timeout, buffer, opt);     

            if (replay.Status == IPStatus.Success)
            {
                return 1;   
            }
            else
            {
                return 0;
            }
        }

        private static int Check(string ip,int startPort,int endPort)
        {
            int pingResult, result;

            if(PingTargetIP(ip)>0)
            {
                pingResult = 100;
            }
            else
            {
                pingResult = 200;
            }

            if(startPort<0||endPort>65535||startPort>endPort)
            {
                result = pingResult + 1;
            }
            else
            {
                result = pingResult ;
            }
            return result;
        }

        private static void Scan()
        {
            int currentPort = port;    
            try
            {
                TcpClient tcpClient = new TcpClient(IP, currentPort);
                Console.WriteLine("    开放端口:" + currentPort);
            }
            catch
            {

            }
        }
    }
}

 

posted @ 2017-11-12 20:06  81192  阅读(1311)  评论(0编辑  收藏  举报