Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何进行网络Ping.NET_C#_.net_Vb.net_Ping_Lan - Fatal编程技术网

C# 如何进行网络Ping.NET

C# 如何进行网络Ping.NET,c#,.net,vb.net,ping,lan,C#,.net,Vb.net,Ping,Lan,我做了一个ping我的整个网络的小程序,但我认为我有一个问题,因为一些设备停止工作(每2分钟运行一次,完成操作需要1分钟),问题是: 有更好的方法吗 代码如下: Console.WriteLine("Haciendo ping a los equipos, no cierre esta ventana... "); Ping ping = new Ping(); byte[] buffer = new byte[32]; PingOptions pingoptns = new PingOptio

我做了一个ping我的整个网络的小程序,但我认为我有一个问题,因为一些设备停止工作(每2分钟运行一次,完成操作需要1分钟),问题是: 有更好的方法吗

代码如下:

Console.WriteLine("Haciendo ping a los equipos, no cierre esta ventana... ");
Ping ping = new Ping();
byte[] buffer = new byte[32];
PingOptions pingoptns = new PingOptions(128, true);
int timeout = Convert.ToInt32(ConfigurationManager.AppSettings["timeout"].ToString());
List<Equipo> list_Eq = new List<Equipo>();
DataTable dt = DB.ShowData("select ip from testping where estatus = 1");

// Por cada IP se realiza ping y se  agrega a la lista del modelo
foreach (DataRow item in dt.Rows)
{

    if (ping.Send(item[0].ToString(), timeout, buffer, pingoptns).Status == IPStatus.Success)
    {
        list_Eq.Add(new Equipo
        {
            ip = item[0].ToString(),
            estado = 1
        });
    }
    else
    {
        list_Eq.Add(new Equipo
        {
            ip = item[0].ToString(),
            estado = 0
        });
    }
}

// Se actualiza el estado de las ip segun la respuesta del ping
foreach (var eq in list_Eq)
{
    DB.ExecQuery("update testping set estado = " + eq.estado + " where ip = '" + eq.ip + "'");
}
Console.WriteLine(“Haciendo ping a los equipos,no cierre esta ventana…”);
Ping Ping=新Ping();
字节[]缓冲区=新字节[32];
PingOptions pingoptns=新的PingOptions(128,true);
int timeout=Convert.ToInt32(ConfigurationManager.AppSettings[“timeout”].ToString());
List List_Eq=新列表();
DataTable dt=DB.ShowData(“从testping中选择ip,其中estatus=1”);
//在模式列表中,您可以通过以下方式实现:
foreach(数据行中的数据行项)
{
if(ping.Send(项[0].ToString(),超时,缓冲区,pingoptns).Status==IPStatus.Success)
{
列表_Eq.添加(新设备)
{
ip=项[0]。ToString(),
estado=1
});
}
其他的
{
列表_Eq.添加(新设备)
{
ip=项[0]。ToString(),
estado=0
});
}
}
//这是一个很好的解决方案
foreach(列表中的var eq_eq)
{
DB.ExecQuery(“更新testping set estado=“+eq.estado+”其中ip=”“+eq.ip+””);
}
谢谢

尝试异步Ping:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("IP", typeof(string));
            dt.Columns.Add("TimeOut", typeof(int));
            dt.Columns.Add("Canceled", typeof(bool));
            dt.Columns.Add("Error", typeof(List<string>));
            dt.Columns.Add("Reply", typeof(List<PingReply>));
            dt.Columns.Add("Sent", typeof(int));
            dt.Columns.Add("Received", typeof(int));

            dt.Rows.Add(new object[] { "172.160.1.19", 0, false, null, null, 4, 0 });
            dt.Rows.Add(new object[] { "172.160.1.27", 0, false, null, null, 4, 0 });
            dt.Rows.Add(new object[] { "172.160.1.37", 0, false, null, null, 4, 0 });
            dt.Rows.Add(new object[] { "172.160.1.57", 0, false, null, null, 4, 0 });


            MyPing ping = new MyPing(dt); 
        }
    }

    public class MyPing
    {
        static AutoResetEvent waiter = new AutoResetEvent(false);
        const string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        private Object thisLock = new Object();

        DataTable dt;
        Dictionary<string, DataRow> pingDict = new Dictionary<string, DataRow>();
        const int TIMEOUT = 12000;
        public MyPing() { }
        public MyPing(DataTable dtin)
        {
            dt = dtin;

            Console.WriteLine("Haciendo ping a los equipos, no cierre esta ventana... ");



            // Por cada IP se realiza ping y se  agrega a la lista del modelo
            foreach (DataRow item in dt.Rows)
            {
                Ping ping = new Ping();
                string ip = item.Field<string>("IP");
                pingDict.Add(ip, item);
                ping.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
                byte[] buffer = Encoding.ASCII.GetBytes(data);
                PingOptions pingoptns = new PingOptions(128, true);
                Console.WriteLine("send : {0}", ip);
                ping.SendAsync(ip, TIMEOUT, buffer, pingoptns, item);
            }

            waiter.WaitOne();
        }
        private void PingCompletedCallback (object sender, PingCompletedEventArgs e)
        {
            lock (thisLock)
            {

                DataRow row = null;
                try
                {
                    row = e.UserState as DataRow;
                    string sendIP = row.Field<string>("IP");
                    string replyIP = e.Reply.Address.ToString();
                    Console.WriteLine("reply IP : {0}, send IP : {1}", replyIP, sendIP);
                    // If the operation was canceled, display a message to the user.
                    if (e.Cancelled)
                    {
                        row.SetField<bool>("Canceled", true);
                        return;
                    }

                    // If an error occurred, display the exception to the user.
                    if (e.Error != null)
                    {
                        if (row["Error"] == DBNull.Value) row["Error"] = new List<string>();
                        row.Field<List<string>>("Error").Add(e.Error.Message);
                    }
                    if (e.Reply.Status == IPStatus.TimedOut)
                    {
                        row["TimeOut"] = row.Field<int>("TimeOut") + 1;
                    }
                    else
                    {
                        if (row["Reply"] == DBNull.Value) row["Reply"] = new List<PingReply>();
                        row.Field<List<PingReply>>("Reply").Add(e.Reply);
                        row["Received"] = row.Field<int>("Received") + 1;
                    }

                    row["Sent"] = row.Field<int>("Sent") - 1;
                    if (row.Field<int>("Sent") > 0)
                    {
                        Ping ping = new Ping();
                        string ip = row.Field<string>("IP");
                        ping.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
                        byte[] buffer = Encoding.ASCII.GetBytes(data);
                        PingOptions pingoptns = new PingOptions(128, true);
                        Console.WriteLine("send : {0}", ip);
                        ping.SendAsync(ip, TIMEOUT, buffer, pingoptns, row); ;
                    }
                    else
                    {
                        pingDict.Remove(sendIP);
                        if (pingDict.Count == 0) waiter.Set();
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Exception : {0}", ex.Message);
                }
            }
        }
    }

}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统文本;
使用系统数据;
Net系统;
使用System.Net.Sockets;
使用System.Net.NetworkInformation;
使用系统线程;
命名空间控制台应用程序1
{
班级计划
{
静态void Main(字符串[]参数)
{
DataTable dt=新的DataTable();
添加(“IP”,类型(字符串));
添加(“超时”,typeof(int));
添加(“取消”,类型为(bool));
添加(“错误”,类型(列表));
添加(“回复”,类型(列表));
添加(“已发送”,类型为(int));
dt.列。添加(“收到”,类型(int));
Add(新对象[]{“172.160.1.19”,0,false,null,null,4,0});
Add(新对象[]{“172.160.1.27”,0,false,null,null,4,0});
Add(新对象[]{“172.160.1.37”,0,false,null,null,4,0});
Add(新对象[]{“172.160.1.57”,0,false,null,null,4,0});
MyPing ping=新的MyPing(dt);
}
}
公共类MyPing
{
静态自动重置事件=新自动重置事件(false);
const string data=“aaaaaaaaaaaaaaaaaaaaaaaaaaaa”;
私有对象thisLock=新对象();
数据表dt;
Dictionary pingDict=新字典();
常数int超时=12000;
公共MyPing(){}
公共MyPing(数据表dtin)
{
dt=dtin;
Console.WriteLine(“设备庄园,无需安装设备…”);
//在模式列表中,您可以通过以下方式实现:
foreach(数据行中的数据行项)
{
Ping Ping=新Ping();
字符串ip=项目字段(“ip”);
pingDict.Add(ip,项目);
ping.PingCompleted+=新的PingCompletedEventHandler(PingCompletedCallback);
byte[]buffer=Encoding.ASCII.GetBytes(数据);
PingOptions pingoptns=新的PingOptions(128,true);
WriteLine(“发送:{0}”,ip);
SendAsync(ip、超时、缓冲区、pingoptns、项);
}
服务员,等一等;
}
私有void PingCompletedCallback(对象发送方,PingCompletedEventArgs e)
{
锁(这个锁)
{
DataRow行=null;
尝试
{
row=e.UserState为DataRow;
字符串sendIP=行字段(“IP”);
字符串replyIP=e.Reply.Address.ToString();
WriteLine(“回复IP:{0},发送IP:{1}”,回复IP,发送IP);
//如果操作已取消,则向用户显示消息。
如果(如已取消)
{
行设置字段(“已取消”,为真);
回来
}
//如果发生错误,则向用户显示异常。
如果(例如错误!=null)
{
如果(行[“Error”]==DBNull.Value)行[“Error”]=new List();
行字段(“错误”).Add(例如错误消息);
}
if(e.Reply.Status==IPStatus.TimedOut)
{
行[“超时”]=行字段(“超时”)+1;
}
其他的
{
如果(行[“回复”]==DBNull.Value)行[“回复”]=new List();
行字段(“回复”)。添加(如回复);
行[“已接收”]=行字段(“已接收”)+1;
}
行[“已发送”]=行字段(“已发送”)-1;
如果(行字段(“已发送”)>0)
{
Ping Ping=新Ping();
字符串ip=行字段(“ip”);
ping.PingCompleted+=新的PingCompletedEventHandler(PingCompletedCallback);
byte[]buffer=Encoding.ASCII.GetBytes(数据);
PingOptions pingoptns=新的PingOptions(128,true);
WriteLine(“发送:{0}”,ip);
SendAsync(ip、超时、缓冲区、pingoptns、行);
}
其他的
{
pingDict.Remove(sendIP);
如果(pingDict.Count==0)waiter.Set();
}
}
    using System;
using System.Text;
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Configuration;
using System.Threading.Tasks;

namespace pingtask
{
    class Program
    {
        static void Main(string[] args)
        {

            Task task = new Task(makePing);
            task.Start();
            task.Wait();
            Console.WriteLine("Test finished.");
            Console.ReadLine();

        }

        static async void makePing()
        {

            Ping ping = new Ping();
            byte[] buffer = new byte[32];
            PingOptions pingoptns = new PingOptions(128, true);
            int timeOut = 4000;

            List<string> list_Eq = new List<string>();
            list_Eq.Add("192.168.23.33");
            list_Eq.Add("192.168.0.11");
            list_Eq.Add("192.168.0.7");
            list_Eq.Add("192.168.0.8");
            list_Eq.Add("192.168.0.9");
            list_Eq.Add("192.168.0.5");
            list_Eq.Add("192.168.0.1");
            list_Eq.Add("192.168.0.2");
            list_Eq.Add("192.168.0.3");
            list_Eq.Add("192.168.0.10");
            list_Eq.Add("192.168.0.14");
            list_Eq.Add("192.168.0.4");

            foreach (var item in list_Eq)
            {
                Console.WriteLine("ADDRESS:" + item);
                PingReply reply = await ping.SendPingAsync(item, timeOut, buffer, pingoptns);
                Console.WriteLine("TIME:" + reply.RoundtripTime);
                Console.WriteLine("==============================");
            }

        }
    }
}