【发布时间】:2015-01-31 16:02:31
【问题描述】:
C# 获取 LAN 中的活动 IP 地址,这在控制台应用程序中运行良好,当它出现在基于表单的应用程序时我遇到错误,我是 c# 新手,请帮助。获取非静态字段的错误对象引用
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private static List<Ping> pingers = new List<Ping>();
private static int instances = 0;
private static object @lock = new object();
private static int result = 0;
private static int timeOut = 250;
private static int ttl = 5;
public String IP;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
IP = textBox1.Text;
string baseIP = "192.168.1.";
Console.WriteLine("Pinging 255 destinations of D-class in {0}*", baseIP);
CreatePingers(255);
PingOptions po = new PingOptions(ttl, true);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
byte[] data = enc.GetBytes("abababababababababababababababab");
SpinWait wait = new SpinWait();
int cnt = 1;
Stopwatch watch = Stopwatch.StartNew();
foreach (Ping p in pingers)
{
lock (@lock)
{
instances += 1;
}
p.SendAsync(string.Concat(baseIP, cnt.ToString()), timeOut, data, po);
cnt += 1;
}
while (instances > 0)
{
wait.SpinOnce();
}
watch.Stop();
DestroyPingers();
Console.WriteLine("Finished in {0}. Found {1} active IP-addresses.", watch.Elapsed.ToString(), result);
Console.ReadKey();
}
public static void Ping_completed(object s, PingCompletedEventArgs e)
{
lock (@lock)
{
instances -= 1;
}
if (e.Reply.Status == IPStatus.Success)
{
IP = e.Reply.Address.ToString();
result += 1;
}
else
{
//Console.WriteLine(String.Concat("Non-active IP: ", e.Reply.Address.ToString()))
}
}
private static void CreatePingers(int cnt)
{
for (int i = 1; i <= cnt; i++)
{
Ping p = new Ping();
p.PingCompleted += Ping_completed;
pingers.Add(p);
}
}
private static void DestroyPingers()
{
foreach (Ping p in pingers)
{
p.PingCompleted -= Ping_completed;
p.Dispose();
}
pingers.Clear();
}
}
}
【问题讨论】: