9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C#でIPアドレス⇔ホスト名の変換

Posted at

もういろんなところで紹介されている内容ですが、.NETのDnsクラスの使い方を備忘のために残しておきます。

IPアドレスからホスト名を得る

using System;
using System.Net;

IPHostEntry host = Dns.GetHostEntry("127.0.0.1");
Console.WriteLine(host.HostName);

ホスト名からIP(v4)アドレスを得る

AddressFamily が AddressFamily.InterNetwork のものを抜き出せば、IPV4アドレスを取得出来ます。

using System;
using System.Net;
using System.Net.Sockets;

var hostName = "example.com";
IPHostEntry ip = Dns.GetHostEntry(hostName);
foreach (IPAddress address in ip.AddressList)
{
	if (address.AddressFamily == AddressFamily.InterNetwork)
		Console.WriteLine(address);
}

ホスト名からIP(v6)アドレスを得る

AddressFamily が AddressFamily.InterNetworkV6 のものを抜き出せば、IPV6アドレスを取得出来ます。

using System;
using System.Net;
using System.Net.Sockets;

var hostName = "example.com";
IPHostEntry ip = Dns.GetHostEntry(hostName);
foreach (IPAddress address in ip.AddressList)
{
	if (address.AddressFamily == AddressFamily.InterNetworkV6)
		Console.WriteLine(address);
}

自分自身のIPアドレスを得る

GetHostEntryメソッドに空文字列を渡すことで自分自身のコンピューターのIPアドレスを取得出来ます。

using System;
using System.Net;

var hostName = ""; // 空文字にする
IPHostEntry ip = Dns.GetHostEntry(hostName);
foreach (IPAddress address in ip.AddressList)
{
    Console.WriteLine(address);
}

ローカル コンピューターのホスト名を得る

ローカル コンピューターのホスト名を取得するには、Dns.GetHostNameメソッドを呼び出すだけです。

using System;
using System.Net;

var hostName = Dns.GetHostName();
Console.WriteLine(hostName);
9
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?