自身のIPアドレスを取得
- VisualC#
-
2010-10-26 - 更新:2012-06-27
この記事は最終更新日から1年以上経過しています。
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Net;
public static int check_ip()
{
string hostname; // ホスト名
IPHostEntry ipentry; // IPエントリ(IPアドレスリスト)
IPAddress ipaddr; // IPアドレス
string ipaddress; // IPアドレス
string[] IP_ARRAY;
int n;
ipaddress = "0.0.0.0";
try
{
// ホスト名を取得
hostname = Dns.GetHostName();
// ホスト名からIPアドレスを取得する
ipentry = Dns.GetHostEntry(hostname);
// windows7だと、IPアドレスがインデックス「2」のため
// ループで取り出す
for (int i = 0; i < ipentry.AddressList.Length; i++)
{
// Regex : 正規表現
Regex myRegex = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
// 対象文字列が存在するか?
if (myRegex.IsMatch(ipentry.AddressList[i].ToString()))
{
ipaddr = ipentry.AddressList[i];
ipaddress = ipaddr.ToString();
break;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
Application.Exit();
}
// ネットワーク識別子を取得
IP_ARRAY = ipaddress.Split('.');
// ネットワーク識別子を返す
n = int.Parse(IP_ARRAY[2]);
return n;
}
この記事がお役に立ちましたらシェアお願いします
3,788 views




