■ IPアドレスを取得する
サンプル
sing System; using System.Net; using System.Windows.Forms; using System.Linq; using System.Net.Sockets; namespace SampleForm { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { this.label1.Text = this.GetIPAddress(); } private string GetIPAddress() { // ホスト名を取得する string hostName = Dns.GetHostName(); IPHostEntry ipHostEntry = Dns.GetHostEntry(hostName); return ipHostEntry.AddressList.Where(x => x.AddressFamily == AddressFamily.InterNetwork).FirstOrDefault().ToString(); } } }
参考文献
https://garafu.blogspot.com/2015/08/local-machine-information.htmlhttp://www.atmarkit.co.jp/fdotnet/dotnettips/778getmyipaddress/getmyipaddress.html
https://dobon.net/vb/dotnet/internet/dnslookup.html
■ IPアドレスを判定
* IPAddress.TryParse メソッド を使用する => 正規表現など自作でもできると思うが、IP6などの考慮を入れると素直に上記のメソッドを使った方がいいかも。http://msdn.microsoft.com/ja-jp/library/system.net.ipaddress.tryparse.aspx
サンプル
using System.Net;
private void button1_Click(object sender, EventArgs e)
{
IPAddress ip;
if (IPAddress.TryParse(this.textBox1.Text, out ip))
{
this.label1.Text = ip.ToString();
}
else
{
this.label1.Text = "It's not IP address";
}
}
使用上の注意
* 8進数や16進数にも対応していることに注意。詳細は、下記「IPを扱う上での注意事項」を参照のこと。
■ IPアドレスを比較
* IPAddress.Equals メソッド を使用する
サンプル
using System.Net;
private void button2_Click(object sender, EventArgs e)
{
var ip1 = IPAddress.Parse("120.1.02.224");
var ip2 = IPAddress.Parse("120.001.002.224");
if (ip2.Equals(ip1))
{
this.label2.Text = "It's the same";
}
else
{
this.label2.Text = "It's not the same";
}
}
■ IPを扱う上での注意事項
* 以下の様なルールがあることに注意。(以下「サンプル」も参照) + 先頭が「0」で始まっていれば、8進数であると解釈 + 先頭が「0x」で始まっていれば、16進数であると解釈 + 8進数、10進数、16進数の混在も可能 →IPアドレスを実装する際、独自実装よりも、上記のように.NETの既存のメソッドを使用した方が良さそう * IE8,IE9 で 「http://192.168.001.023/」 にアクセスしてみると、 「http://192.168.1.19」にアクセスしにいく(IE7はできない模様)http://sumikko8note.blog.fc2.com/blog-entry-13.html
サンプル
* 22.101.31.153 (10 進数) * 026.0145.037.0231 (8 進数) → 10進数だと「22.101.31.153」 * 0x16.0x65.0xF1.0x99 (16 進数) → 10進数だと「22.101.24.153」 * 0x16.101.037.153 (上記 3 種類をすべて組み合わせたもの) → 10進数だと「22.101.31.153」