コンソールアプリケーションから自分のIPアドレスが何であるかを調べたいと思っています。コンソールアプリケーションでIPアドレスを取得する
私はRequest.ServerVariables
コレクションおよび/またはRequest.UserHostAddress
を使用してWebアプリケーションに使用されています。
これはどのようにコンソールアプリケーションで行うことができますか?
コンソールアプリケーションから自分のIPアドレスが何であるかを調べたいと思っています。コンソールアプリケーションでIPアドレスを取得する
私はRequest.ServerVariables
コレクションおよび/またはRequest.UserHostAddress
を使用してWebアプリケーションに使用されています。
これはどのようにコンソールアプリケーションで行うことができますか?
はこれを行う最も簡単な方法は次のとおりです。
using System;
using System.Net;
namespace ConsoleTest
{
class Program
{
static void Main()
{
String strHostName = string.Empty;
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = Dns.GetHostName();
Console.WriteLine("Local Machine's Host Name: " + strHostName);
// Then using host name, get the IP address list..
IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
IPAddress[] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
}
Console.ReadLine();
}
}
}
using System;
using System.Net;
public class DNSUtility
{
public static int Main (string [] args)
{
String strHostName = new String ("");
if (args.Length == 0)
{
// Getting Ip address of local machine...
// First get the host name of local machine.
strHostName = DNS.GetHostName();
Console.WriteLine ("Local Machine's Host Name: " + strHostName);
}
else
{
strHostName = args[0];
}
// Then using host name, get the IP address list..
IPHostEntry ipEntry = DNS.GetHostByName (strHostName);
IPAddress [] addr = ipEntry.AddressList;
for (int i = 0; i < addr.Length; i++)
{
Console.WriteLine ("IP Address {0}: {1} ", i, addr[i].ToString());
}
return 0;
}
}
System.Net.Dns.GetHostAddresses()はそれを行う必要があります。
System.Net名前空間はここにあなたの友人です。特に、DNS.GetHostByNameなどのAPI。
しかし、任意のマシンに複数のIPアドレス(複数のNIC、IPv4、IPv6など)がある可能性があります。
私は本当に複数のIPアドレスを持つあなたのコメントが好きです。それに基づいて、上のコードは本当にうまくいった。ありがとう! –
これを試してください:
String strHostName = Dns.GetHostName();
Console.WriteLine("Host Name: " + strHostName);
// Find host by name IPHostEntry
iphostentry = Dns.GetHostByName(strHostName);
// Enumerate IP addresses
int nIP = 0;
foreach(IPAddress ipaddress in iphostentry.AddressList) {
Console.WriteLine("IP #" + ++nIP + ": " + ipaddress.ToString());
}
たIPAddress [] =アドレスリストDns.GetHostAddresses(Dns.GetHostName())。
ここでは多くの回答がありますが、これは読みやすいようです。私はMartin Peckが複数のIPアドレスを持っていると言っていたのが好きです。私はこれが私に適切な解決策を提供すると思います。私はこれをローカルに走らせて、私が望むものを私に与えました。どうもありがとうございます! –
はい、私はマーティンに同意します。あなたは複数のIPアドレスを注意しなければなりません。このコードはこれを処理し、そこから何をするかを選択できます。 – CodeLikeBeaker
このコードをコピーしたページへのリンクを含めるべきでしょうか?つまり、Googleの最初の結果の1つです。 – Kevin