我有一个服务器应用程序,我试图自动将 IP 地址设置为从机器动态分配的 IP 地址中获取的地址。到目前为止,我已经得到了这个来获取 IPv4,但它作为 IPAddress[] 类型返回,我在转换为 string[] 时遇到了一些麻烦,因此我的 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();
最佳答案
这应该可以解决问题。
string[] ips = addresses.Select(ip => ip.ToString()).ToArray();
确保您有 System.Linq
的 using 语句
关于c# - 将 IPAddress[] 转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26503756/