Ping多个IP地址并将计时器设置为重新ping

时间:2013-07-29 05:47:40

标签: c#

我有以下代码来ping IP地址,但是当我运行此代码时,它没有运行,因为数据库没有更新。

以下是Start代码:

protected void Start()
{
    string ip_STCKL = "*.*.10.";
    string ip_STCKCH = "*.*.128.";

    for (int ipCount = ip_addr; ipCount < 195; ipCount++)
    {
        string ip = ip_STCKL + ipCount.ToString();

        string loopIp = ip;
        WaitCallback func = delegate(object state)
        {
            if (PingIP(loopIp))
            {
                UpdateStatusKL(loopIp, true);
                Console.WriteLine("Ping Success");
            }
            else
            {
                loopIp = ip_STCKCH + ipCount.ToString();
                if (PingIP(loopIp))
                {
                    UpdateStatusKL(loopIp, true);
                    //Console.WriteLine("Ping Success");
                }
                else
                {
                    UpdateStatusKL(loopIp, false);
                    //Console.WriteLine("Ping Failed");
                }
            }
        };
        ThreadPool.QueueUserWorkItem(func);
        //ThreadPool.GetAvailableThreads;
    }

    //Console.ReadLine();
}

这是获取状态的ping函数:

public static bool PingIP(string IP)
{
    bool result = false;
    try
    {
        Ping ping = new Ping();
        PingReply pingReply = ping.Send(IP);

        if (pingReply.Status == IPStatus.Success)
            result = true;
    }
    catch(Exception)
    {
        result = false;
    }

    return result;
}

获取状态后,更新到数据库:

public void UpdateStatusKL(string IP, bool Status)
{

    string New_Status = "";

    if (Status)
    {
        New_Status = "REACHABLE";
    }
    else
    {
        New_Status = "UNREACHABLEE";
    }


    //Declare the connection object
    OracleConnection Conn = new OracleConnection("Data Source=COMMSERVERKL;User
    Id=mt_mon;Password=butus123");

    //Make the connection
    Conn.Open();

    //Define you query
    string sql = "UPDATE BalaiConnectionStatus SET Balai_Status = :pstatus,
    Timestamp = :pTime WHERE IP_STCKL = :pIP OR IP_STCKCH = :pIP";
    //Declare the Command
    OracleCommand cmd = new OracleCommand(sql, Conn);

    //Add the parameters needed for the SQL query
    cmd.CommandType = CommandType.Text;

    cmd.Parameters.Add("pstatus", OracleType.VarChar).Value = New_Status;
    cmd.Parameters.Add("pTime", OracleType.VarChar).Value =
    DateTime.Now.ToString();
    cmd.Parameters.Add("pIP", OracleType.VarChar).Value = IP;


    //Execute the query

    cmd.ExecuteNonQuery();

    Conn.Close();
}

定时器触发后每隔15分钟,它会调用Start功能再次开始ping所有IP地址:

private void timer1_Tick(object sender, EventArgs e)
{
    ip_addr = 10;
    Start();
}

我的代码有什么问题,如何解决?

0 个答案:

没有答案