IPアドレスを取得する

PCのIPアドレスを取得する方方です。
まずホスト名を取得し、それを元にエントリーを列挙しています。

IPアドレスは1つとは限らないので注意が必要です。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;   // これが必要

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // ホスト名を取得
            string hostname = Dns.GetHostName();

            // ホスト名からエントリー取得
            IPHostEntry ipentry = Dns.GetHostEntry(hostname);

            // IPアドレスは2つ以上のケースもあるのですべて列挙(有線+無線など)
            string msg = string.Empty;
            foreach (IPAddress ip in ipentry.AddressList)
            {
                msg += ip.ToString() + "\r\n";
            }

            MessageBox.Show(msg);
        }
    }
}

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

次のHTML タグと属性が使えます: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)