在C#中,如何解析主机的IP地址?

时间:2009-06-22 22:38:15

标签: c# ip-address resolve

如何动态获取服务器的IP地址(要连接的PC)?

5 个答案:

答案 0 :(得分:17)

System.Dns.GetHostEntry可用于将名称解析为IP地址。

答案 1 :(得分:10)

IPHostEntry Host = Dns.GetHostEntry(DNSNameString);
DoSomethingWith(Host.AddressList);

答案 2 :(得分:2)

如果您使用以下方法,则可以正确解析

 public static bool GetResolvedConnecionIPAddress(string serverNameOrURL, out IPAddress resolvedIPAddress)
        {
            bool isResolved = false;
            IPHostEntry hostEntry = null;
            IPAddress resolvIP = null;
            try
            {
                if (!IPAddress.TryParse(serverNameOrURL, out resolvIP))
                {
                    hostEntry = Dns.GetHostEntry(serverNameOrURL);

                    if (hostEntry != null && hostEntry.AddressList != null && hostEntry.AddressList.Length > 0)
                    {
                        if (hostEntry.AddressList.Length == 1)
                        {
                            resolvIP = hostEntry.AddressList[0];
                            isResolved = true;
                        }
                        else
                        {
                            foreach (IPAddress var in hostEntry.AddressList)
                            {
                                if (var.AddressFamily == AddressFamily.InterNetwork)
                                {
                                    resolvIP = var;
                                    isResolved = true;
                                    break;
                                }
                            }
                        }
                    }
                }
                else
                {
                    isResolved = true;
                }
            }
            catch (Exception ex)
            {

            }
            finally
            {
                resolvedIPAddress = resolvIP;
            }

            return isResolved;
        }

答案 3 :(得分:0)

答案 4 :(得分:0)

根据你对混沌答案的评论,你不需要服务器的IP地址,你想要客户端的IP地址。如果是这种情况,请修正您的问题......您的答案将是HttpRequest.UserHostAddress。