ホームセキュリティアプリケーションを開発しています。私がやりたいことの 1 つは、家にいるかどうかに基づいて、自動的に電源を入れたり切ったりすることです。家にいるときに自動的にネットワークに接続する Wi-Fi 付きの電話があります。
電話が接続され、DHCP 経由でアドレスが取得されます。静的 IP を使用するように構成することはできますが、私はむしろしたくありません。デバイスのMACアドレスを取得して、ネットワーク上で現在アクティブかどうかを教えてくれるC#/ .Netの「Ping」または同等のものはありますか?
編集:明確にするために、同じLAN上で電話を検出できるようにしたいPCでソフトウェアを実行しています。
編集: spoulson の助けのおかげで、私が思いついたコードは次のとおりです。興味のある電話が家にあるかどうかを確実に検出します。
private bool PhonesInHouse()
{
Ping p = new Ping();
// My home network is 10.0.23.x, and the DHCP
// pool runs from 10.0.23.2 through 10.0.23.127.
int baseaddr = 10;
baseaddr <<= 8;
baseaddr += 0;
baseaddr <<= 8;
baseaddr += 23;
baseaddr <<= 8;
// baseaddr is now the equivalent of 10.0.23.0 as an int.
for(int i = 2; i<128; i++) {
// ping every address in the DHCP pool, in a separate thread so
// that we can do them all at once
IPAddress ip = new IPAddress(IPAddress.HostToNetworkOrder(baseaddr + i));
Thread t = new Thread(() =>
{ try { Ping p = new Ping(); p.Send(ip, 1000); } catch { } });
t.Start();
}
// Give all of the ping threads time to exit
Thread.Sleep(1000);
// We're going to parse the output of arp.exe to find out
// if any of the MACs we're interested in are online
ProcessStartInfo psi = new ProcessStartInfo();
psi.Arguments = "-a";
psi.FileName = "arp.exe";
psi.RedirectStandardOutput = true;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
bool foundone = false;
using (Process pro = Process.Start(psi))
{
using (StreamReader sr = pro.StandardOutput)
{
string s = sr.ReadLine();
while (s != null)
{
if (s.Contains("Interface") ||
s.Trim() == "" ||
s.Contains("Address"))
{
s = sr.ReadLine();
continue;
}
string[] parts = s.Split(new char[] { ' ' },
StringSplitOptions.RemoveEmptyEntries);
// config.Phones is an array of strings, each with a MAC
// address in it.
// It's up to you to format them in the same format as
// arp.exe
foreach (string mac in config.Phones)
{
if (mac.ToLower().Trim() == parts[1].Trim().ToLower())
{
try
{
Ping ping = new Ping();
PingReply pingrep = ping.Send(parts[0].Trim());
if (pingrep.Status == IPStatus.Success)
{
foundone = true;
}
}
catch { }
break;
}
}
s = sr.ReadLine();
}
}
}
return foundone;
}