2009-05-13 22 views
16

コンソールアプリケーションから自分のIPアドレスが何であるかを調べたいと思っています。コンソールアプリケーションでIPアドレスを取得する

私はRequest.ServerVariablesコレクションおよび/またはRequest.UserHostAddressを使用してWebアプリケーションに使用されています。

これはどのようにコンソールアプリケーションで行うことができますか?

答えて

23

はこれを行う最も簡単な方法は次のとおりです。

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(); 
     } 
    } 
} 
+0

ここでは多くの回答がありますが、これは読みやすいようです。私はMartin Peckが複数のIPアドレスを持っていると言っていたのが好きです。私はこれが私に適切な解決策を提供すると思います。私はこれをローカルに走らせて、私が望むものを私に与えました。どうもありがとうございます! –

+1

はい、私はマーティンに同意します。あなたは複数のIPアドレスを注意しなければなりません。このコードはこれを処理し、そこから何をするかを選択できます。 – CodeLikeBeaker

+2

このコードをコピーしたページへのリンクを含めるべきでしょうか?つまり、Googleの最初の結果の1つです。 – Kevin

1
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; 
    }  
} 

ソース:次のようにhttp://www.codeproject.com/KB/cs/network.aspx

1

System.Net.Dns.GetHostAddresses()はそれを行う必要があります。

2

System.Net名前空間はここにあなたの友人です。特に、DNS.GetHostByNameなどのAPI。

しかし、任意のマシンに複数のIPアドレス(複数のNIC、IPv4、IPv6など)がある可能性があります。

+0

私は本当に複数のIPアドレスを持つあなたのコメントが好きです。それに基づいて、上のコードは本当にうまくいった。ありがとう! –

2

これを試してください:

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());  
} 
3

たIPAddress [] =アドレスリストDns.GetHostAddresses(Dns.GetHostName())。

関連する問題