• C# 模仿PING操作,监控主机是否可以通信


    以下是C#代码,可以直接复制使用。

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Management;
    
    namespace PingMock
    {
        class MockerClass
        {
            private static Object thisobject = new Object();
            public void Ping(string Host)
            {
                //string rtn = "";
                
                ManagementObjectSearcher mos = null;
                ManagementObjectCollection moc = null;
                LogClass writeLog = new LogClass();
    
                try
                {
                    string searchString = "select * from win32_PingStatus where Address = '" + Host.Trim() + "'";
    
                    mos = new ManagementObjectSearcher(searchString);
                    moc = mos.Get();
    
                    foreach (ManagementObject mo in moc)
                    {
                        object obj = mo.Properties["StatusCode"].Value;
    
                        if (obj == null)
                        {
                            lock (thisobject)
                            {
                                writeLog.WriteLogFile(Host + " PING 执行失败。可能是主机未知。");
                            }
                            //return Host+" PING 执行失败。可能是主机未知。";
                        }
                        else
                        {
                            if (obj.ToString().Trim() == "0")
                            {
                                //rtn = "OK";
                                break;
                            }
                            lock (thisobject)
                            {
                                writeLog.WriteLogFile(Host + " PING 不通!");
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    writeLog.WriteLogFile(Host + " PING 不通,可能原因为:" + ex.Message);
                    //rtn = Host+" PING 不通,可能原因为:"+ ex.Message;
                }
                finally
                {
                    if (moc != null) moc.Dispose();
                    if (mos != null) mos.Dispose();
                }
    
                //return rtn;
            } 
        }
    }
    

      

    可以修改城自己需要的形式。我这个是不返回结果,直接记录日志中。

  • 相关阅读:
    JAVA整理05---手写简单的linkedlist来学习linkedlist
    JAVA整理04---手写简单的arraylist来学习arraylist
    java整理03--常用类
    java整理02--面向对象深入
    每周学习进度
    软件工程课程总结
    梦断代码阅读笔记03
    scrum第二阶段项目冲刺_day10
    scrum第二阶段项目冲刺_day09
    scrum第二阶段项目冲刺_day08
  • 原文地址:https://www.cnblogs.com/StupidsCat/p/2619512.html
Copyright © 2020-2023  润新知