In C#, how do I resolve the IP address of a host?

眉间皱痕 提交于 2019-12-08 14:46:57

问题


How can you dynamically get the IP address of the server (PC which you want to connect to)?


回答1:


System.Dns.GetHostEntry can be used to resolve a name to an IP address.




回答2:


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



回答3:


If you Use the Below Method you will be able to resolve correctly

 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;
        }



回答4:


You want to do an nslookup.

Here's an example:

http://www.c-sharpcorner.com/UploadFile/DougBell/NSLookUpDB00112052005013753AM/NSLookUpDB001.aspx




回答5:


Based on your comment on chaos's answer, you don't want the IP address of a server, you want the IP address of a client. If that's the case, fix your question ... and your answer would be HttpRequest.UserHostAddress.



来源:https://stackoverflow.com/questions/1029749/in-c-how-do-i-resolve-the-ip-address-of-a-host

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!