外出先からちょっと自宅のPCにアクセスしたいということはPCをよく使っている人にはよくあることだ。昨今はPCを直接インターネットにつなぐなどということはほとんどなくなり、ルータを介してインターネットに出入りしている人が多い。つまり、WANのIPアドレスはルータに割り当てられている。自分のうちのマシンに接続するには、ルータのIPアドレスを知っておかなくてはいけない。ほとんどの場合DHCPから割り当てられるだろうから、うちにいるときに調べていても、外出したら変わってしまったという事だって考えられる。
そのために自分のためにちょっとしたウェブサービスを書いてみた。警告しておくが、ASPNET Worker ProcessがWriteできるフォルダでなければこのコードはAccess DeniedのExceptionが発生してしまうので注意。
[WebMethod()]
public void Ping(string ComputerName)
{
string IP = this.Context.Request.UserHostAddress;
StringBuilder sbBody = new StringBuilder();
sbBody.Append(“IP detected: “ + IP + Environment.NewLine + “<br>”);
sbBody.Append(“Computer Name: “ + ComputerName + Environment.NewLine + “<br>”);
sbBody.Append(“Server Date/Time: “ + DateTime.Now.ToString() + Environment.NewLine + “<br>”);
string FileName = Context.Request.PhysicalApplicationPath + “MyWritableFolder\\MyFile.htm”;
FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write(sbBody.ToString());
sw.Flush();
sw.Close();
fs.Close();
}
ウェブサービスだけでは意味がない。これを消費するプログラムが必要だ。それにはWindowsサービスが最適であろう。そこでWindowsサービスから利用できるクラスを書いてみた。10分ごとにウェブサービスを実行してIPアドレスをサーバ側に知らせてくれるのだ。
public class Notifier
{
Timer _timer;
public Notifier()
{
_timer = new Timer(new TimerCallback(this.TickCallBack), null, new TimeSpan(0), new TimeSpan(0, 10, 0));
}
private void TickCallBack(object state)
{
try
{
VBASPCoder.PingService.PingService pingService = new VBASPCoder.PingService.PingService();
pingService.Ping(Environment.MachineName);
}
catch(Exception exp)
{
Logger.WriteLog(exp);
}
}
}
コメント書き込み