【发布时间】:2014-10-22 08:58:08
【问题描述】:
我有一个服务器应用程序,我试图自动将 IP 地址设置为,取自机器动态分配的 IP 地址。到目前为止,我已经获得了 IPv4,但它以 IPAddress[] 类型返回,我在转换为字符串 [] 时遇到了一些麻烦,因此我的 HttpListener 可以使用它。关于如何转换它的任何提示?还是我走错了路?
这是我用来获取 IP 地址的:
class Program
{
static void Main(string[] args)
{
string name = (args.Length < 1) ? Dns.GetHostName() : args[0];
try
{
IPAddress[] addrs = Array.FindAll(Dns.GetHostEntry(string.Empty).AddressList,
a => a.AddressFamily == AddressFamily.InterNetwork);
Console.WriteLine("Your IP address is: ");
foreach (IPAddress addr in addrs)
Console.WriteLine("{0} {1}", name, addr);
//Here I'm trying to convert the IPAddress[] into a string[] to use in my listener
string str = addrs.ToString();
string[] ipString = { str };
Response.Listener(ipString);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
//current way of setting the IP address - not optimal
string[] ipstring = new string[1] {"10.10.180.11:8080"};
Response.Listener(ipstring);
}
}
为了美好时光而聆听者:
public static void Listener(string[] prefixes)
{
if (!HttpListener.IsSupported)
{
Console.WriteLine("Windows XP SP2 or Server 2003 is required to use the HttpListener class.");
return;
}
// URI prefixes are required,
// for example "http://contoso.com:8080/index/".
if (prefixes == null || prefixes.Length == 0)
throw new ArgumentException("prefixes");
// Create a listener.
HttpListener listener = new HttpListener();
// Add the prefixes.
foreach (string s in prefixes)
{
listener.Prefixes.Add("http://" + s + "/");
}
listener.Start();
【问题讨论】:
标签: c# httplistener