C#基本网络操作
2021-04-29 08:27
标签:fragment 邮箱 stat sock mail remove stand pdu collect 建档操作如ping,查询本机主机ip,同步异步查询局域网内主机,同步异步邮件发送等 1)ping 通过ping类测试网络 2)查询本机ip与主机名 (一)通过Process类调用ipconfig.exe (二)通过DNS类获取 3)搜索局域网内可ping通的主机 搜索网段范围内所有Ip并测试。 (一)非异步操作 (二)异步操作 4)通过 SmtpClient类发送电子邮件 首相通过MailMessage添加邮件发送信息,包括主题,内容,附件等。其中附件通过Attachment类添加。 MailMessage类主题 定义发送协议 (一)同步发送 (二)异步发送 异步发送 结束后调用SendCompletedAction,其定义如下 发送邮件为了便于理解在此进行了分步分割,一下为完整代码,其中同步发送方法已注释: C#基本网络操作 标签:fragment 邮箱 stat sock mail remove stand pdu collect 原文地址:http://www.cnblogs.com/llstart-new0201/p/7822659.htmlusing 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();
}
}
}
using System;
using System.Net;
using System.Diagnostics;
using System.Net.Sockets;
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;
}
static string GetLocalIp()
{
try
{
string HostName = Dns.GetHostName(); //得到主机名
IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
for (int i = 0; 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)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
public static void SearchIP()
{
Liststring> ipList = new Liststring>();
//获取本地机器名
string myHostName = Dns.GetHostName();
//获取本机IP
string myHostIP = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault
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)
{
Liststring> ipList = new Liststring>();
if (e.Reply.Status == IPStatus.Success)
{
ipList.Add(e.Reply.Address.ToString());
Console.Write(e.Reply.Address.ToString());
Console.WriteLine("Ansyc-----------------------");
}
// Console.WriteLine("Ansyc-----------------------");
}
using System;
using System.ComponentModel;
using System.Net.Mail;
using System.Text;
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();
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.");
}
}
}
}