Michael

Michael

  • NA
  • 1
  • 0

c# and using IsDestinationReachable

Apr 6 2006 10:38 AM
Hi, I am an SMS administrator for our Company. It seems on a daily basis I have to connect to computers to fix something related to SMS. Well we have a large remote user base and frequently those machines are not connected when I need to do something to them. So I suppose I could try to remember to ping them throughout the day or set up a ping -t command, but that seemed wasteful. So as a beginning c# hobbyist (won't say programmer just yet), I broke out my Visual C# Express 2005 and thought how could I automate this task of finding out when a computer comes online. So I found out about the function IsDestinationReachable using a DLL Import within c#.

So I set up a window to ask for a computer name, then pass that to the next window that does the actual checking. If it does not reach the given machine, it sleeps for 15 seconds then tries again. Once the machine is reached, the window pops up on the display and an audible tone is also generated.

Well this seems to work for most machines. However, I have seen this app tell me a machine is now online when it is sitting right next to me, turned off, and unplugged from the network. If I try to ping the machine, I get no reply, as I would expect.

I have listed my code below. Can anyone offer some thoughts, hints, etc.?

private void frmWaitForActive_Load(object sender, EventArgs e)

{

//set window title and hide window.

Text = "Is " + strCompName + " online?";

this.Hide();

/*This section of code will perform the actual test of

* determining whether the indicated computer is reachable.

*

* A boolean variable is initially set to false, then the

* function called IsDestinationReachable is run using the

* supplied computer name as the host.

*

* If the host is reachable, then a window will display

* for the user indicating such, as well as a tone will sound

* as an audible indicator.

*

* If the host is not found, then the program sleeps

* for 15 seconds (15000 milliseconds) and the process

* is then repeated to check if the host is reachable.

*/

bool blnFlag = false;

while (blnFlag == false)

{

if (IsDestinationReachable(strCompName, IntPtr.Zero))

{

//the host is reachable. Now notify the administrator

WindowState = FormWindowState.Normal;

this.Show();

txtCompName.Text = strCompName + " is now on-line!";

blnFlag = true;

Beep(500, 550);

}

else

{

//Sleep 15 seconds (15000 milliseconds)

Thread.Sleep(15000);

}

}

}

private void cmdQuit_Click(object sender, EventArgs e)

{

Application.Exit();

}

//this DLL Import is to allow the alert tone to be generated

[DllImport("kernel32.dll")]

public static extern bool Beep(uint dwFreq, uint dwDuration);

//this DLL Import is used to determine if the given host is reachable

[DllImport("sensapi.dll")]

private extern static bool IsDestinationReachable(string dest, IntPtr ptr);

}