الحصول على عنوان IP في تطبيق وحدة
-
21-08-2019 - |
سؤال
وأنا أتطلع لمعرفة ما هو عنوان IP الخاص بي من تطبيق وحدة التحكم.
واعتدت على تطبيق ويب باستخدام مجموعة Request.ServerVariables
و / أو Request.UserHostAddress
.
وكيف يمكن القيام بذلك في التطبيق وحدة؟
المحلول
وأسهل طريقة للقيام بذلك هي كما يلي:
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.
ولكن، قد يكون أي جهاز معين عناوين IP متعددة (متعددة المراكز القومية، IPv4 و IPv6 الخ) حتى انها ليست تماما كما بسيط سؤال النحو الذي تشكله.
وIPADDRESS [] addresslist = 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;
}
}
المصدر: http://www.codeproject.com/KB/cs/network .aspx اتصال
لا تنتمي إلى StackOverflow