コンソールアプリケーションでIPアドレスを取得します。
-
21-08-2019 - |
質問
私は自分の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();
}
}
}
他のヒント
これを試してください:
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());
}
System.Net名前空間には、ここにあなたの友達です。特に、DNS.GetHostByNameとしてのAPI。
ただし、任意のマシンが複数のIPアドレス(複数のNIC、IPv4およびIPv6など)を有していてもよいので、あなたが提起として、それはかなりのように簡単な質問ではありません。
たIPAddress [] =アドレスリストDns.GetHostAddresses(Dns.GetHostName());
System.Net.Dns.GetHostAddresses()それを行う必要があります。
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;
}
}
所属していません StackOverflow