Holen Sie die IP-Adresse in einer Konsolenanwendung
-
21-08-2019 - |
Frage
Ich bin auf der Suche, um herauszufinden, was meine IP-Adresse von einer Konsolenanwendung ist.
Ich bin auf eine Web-Anwendung, die von der Request.ServerVariables
Sammlung und / oder Request.UserHostAddress
.
Wie kann dies in einer Konsole app getan werden?
Lösung
Der einfachste Weg, dies zu tun, ist wie folgt:
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();
}
}
}
Andere Tipps
Versuchen Sie folgendes:
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());
}
Das System.Net-Namespace ist dein Freund hier. Insbesondere APIs wie DNS.GetHostByName.
Es kann jedoch jede gegebene Maschine mehrere IP-Adressen (mehrere NICs, IPv4 und IPv6 etc.) haben, so ist es nicht ganz so einfach eine Frage, wie Sie darstellen.
IPAddress [] = Address Dns.GetHostAddresses (Dns.GetHostName ());
System.Net.Dns.GetHostAddresses () sollte es tun.
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;
}
}