c# - 将 IPAddress[] 转换为字符串

标签 c# httplistener

我有一个服务器应用程序,我试图自动将 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/

相关文章:

c# - TextBox.Clear() 或 TextBox.Text = string.Empty

c# - 在非异步方法中返回异步任务的正确方法

c# - 用于无损 Exif 重写的 .NET C# 库?

c# - 如何从 HttpListenerRequest 获取表单参数?

c# - .NET 4.5 中的 HttpListener 无法将套接字识别为 WebSocket

c# - 如何删除在 DataDirectory 中创建的 .sdf 文件

c# - 通过PowerShell使我的C#应用​​程序可管理

c# - 带有发布数据的 httplistener

c# - System.Net.ProtocolViolationException :Bytes to be written to the stream exceed the Content-Length bytes size specified

c# - 基于HttpListener的自托管站点——如何处理鉴权?