Identify a ping request to an IP address in C#?

2019-06-14 16:16发布

I want to know how to find out if a system is shutdown or not using its IP address (consider i have been provided list of IP addresses).

Currently i have a console application that is taking a command as an input and executing it on command prompt and showing me the output on the console.

class Program
{
    static void Main(string[] args)
    {
        Process cmdProcess = new Process();
        cmdProcess.StartInfo.FileName = "cmd.exe";
        cmdProcess.StartInfo.RedirectStandardInput = true;
        cmdProcess.StartInfo.RedirectStandardOutput = true;
        cmdProcess.StartInfo.CreateNoWindow = true;
        cmdProcess.StartInfo.UseShellExecute = false;
        cmdProcess.Start();      
    }
}

标签: c# cmd
2条回答
混吃等死
2楼-- · 2019-06-14 16:28

You should use WMI to attempt to obtain the WMI_OperatingSystem on the remote machine.

If you're able to access that object and have suitable permissions, you'll also be able to invoke its Shutdown method1.

Unlike ping, the above verifies that you can connect to the machine for the purposes you actually need to2.

(If connecting to WMI via IP address isn't working, you may wish to consult this question)


1I suppose there may be a perverse situation where, on the one hand, you have some form of permission to initiate remote shutdowns, but on the other some aspect of doing this via WMI is blocked, but that's really a push back to your administrators - you're being asked to perform an administrative task, the right route is WMI.

2ping just tells you that ICMP ECHO is being processed correctly by the remote machine3. It gives you no indication of whether the system is capable of any other activity. It's pointless to "pre-check" connectivity with ping if you're going to follow that up with other activity that requires connectivity and other things in order to work. Among other things, between running a "pre-check" and acting on the outcome, the external reality may have changed.

You'll need to write code that copes with network connectivity changing whilst you're attempting your activity anyway (or the remote machine going down for other reasons, etc).

3And that nothing is filtering ICMP ECHO traffic.

查看更多
太酷不给撩
3楼-- · 2019-06-14 16:48

If the machine is replying to pings, as per @Paxz 's suggestion, you can do this :

var ping = new Ping();
var pingReply = ping.Send("123.123.123.123");

if (pingReply.Status == IPStatus.Success)
{
}
查看更多
登录 后发表回答