码迷,mamicode.com
首页 > Windows程序 > 详细

C#基本网络操作

时间:2017-11-12 20:51:22      阅读:394      评论:0      收藏:0      [点我收藏+]

标签:fragment   邮箱   stat   sock   mail   remove   stand   pdu   collect   

建档操作如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.");
            }
        }
    }
}

 

C#基本网络操作

标签:fragment   邮箱   stat   sock   mail   remove   stand   pdu   collect   

原文地址:http://www.cnblogs.com/llstart-new0201/p/7822659.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!