原文 获取外网IP, C#获取本机的MAC地址,C#通过编程方式实现Ping
获取外网IP地址
思路是通过WebRequest连接一些网上提供IP查询服务的网站,下载到含有你的IP的网页,然后用正则表达式提取出IP来
class Program
{
static void Main(string[] args)
{
Console.WriteLine(GetExportIP()); Console.ReadKey();
} public static string GetExportIP()
{
//获取外部IP
string strUrl = "http://www.ip.cn/getip.php?action=getip&ip_url=&from=web";
//string strUrl = "http://216.157.85.151/getip.php?action=getip&ip_url=&from=web";
Uri uri = new Uri(strUrl);
WebRequest webreq = WebRequest.Create(uri);
Stream s = webreq.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd();
all = Regex.Replace(all,@"(\d+)","000$1");
all = Regex.Replace(all, @"0+(\d{3})", "$1");
string reg = @"(\d{3}\.\d{3}\.\d{3}\.\d{3})";
Regex regex = new Regex(reg);
Match match = regex.Match(all);
string ip = match.Groups[].Value;
return Regex.Replace(ip,@"0*(\d+)","$1");
}
}
获取本机MAC
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management; namespace _17获取MAC地址
{
class Program
{
static void Main(string[] args)
{
ManagementObjectSearcher nisc = new ManagementObjectSearcher("select * from Win32_NetworkAdapterConfiguration");
foreach (ManagementObject nic in nisc.Get())
{
if (Convert.ToBoolean(nic["ipEnabled"]) == true)
{
Console.WriteLine("{0} - {1}", nic["ServiceName"], nic["MACAddress"]);
}
} Console.ReadKey();
}
}
}
Ping
废话少说,具体代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.NetworkInformation; namespace _20通过编程方式实现Ping
{
class Program
{
static void Main(string[] args)
{
Ping ping = new Ping();
PingOptions pingOpt = new PingOptions();
pingOpt.DontFragment = true;//是否设置分段数据
string myInfo = "Hello, world!";
byte[] bufferInfo = Encoding.ASCII.GetBytes(myInfo);
int timeOut = ;
string ipTarget = "192.168.1.102";
PingReply pingReply = ping.Send(ipTarget, timeOut, bufferInfo);
if (pingReply.Status == IPStatus.Success)
{
Console.WriteLine("耗费时间 - {0}\n路由节点数 - {1}\n数据分段 - {2}\n缓冲区大小 - {3}", pingReply.RoundtripTime, //耗费时间
pingReply.Options.Ttl, //路由节点数
pingReply.Options.DontFragment ? "发生分段" : "没有发生分段",//数据分段
pingReply.Buffer.Length//缓冲区大小
);
}
else
{
Console.WriteLine("无法ping通");
} Console.ReadKey();
}
}
}
C# 实现ping的功能