将HostName解析为IP

时间:2012-11-06 10:23:00

标签: c#

我经历了很多谷歌搜索,我发现很多例子都不适用于我。这是一个简单的问题,我觉得有一个简单的答案,没有定义新的类\ modules等...

我的代码是:

Console.WriteLine ("Please enter an IP address or hostname");
string host = Console.ReadLine ();
***IP = resolved "host"*** 
Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);    
s.Connect (IP, 80);
s.close();

如何实际解析IP变量?

5 个答案:

答案 0 :(得分:73)

您只需使用DNS类即可:

IPHostEntry hostEntry;

hostEntry= Dns.GetHostEntry(host);

//you might get more than one ip for a hostname since 
//DNS supports more than one record

if (hostEntry.AddressList.Length > 0)
{
      var ip = hostEntry.AddressList[0];
      Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
      s.Connect(ip, 80);
}

答案 1 :(得分:30)

string howtogeek = "www.howtogeek.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);

foreach (IPAddress theaddress in addresslist)
{
   Console.WriteLine(theaddress.ToString());
 }

来自howtogeek

答案 2 :(得分:2)

请注意,接受的答案可以解析为IPv6。我试图连接到不接受IPv6作为输入字符串的服务。

因此,如果您想获取IPv4,请尝试以下代码段:

using System.Linq;

string host = "google.com";

Dns.GetHostEntry(host).AddressList.First(addr => addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)

答案 3 :(得分:1)

这是我用来将主机名解析为IPv4和/或IPv6的方法。

    using System.Net:

    // A host can have multiple IP addresses!
    public static IPAddress[] GetIPsByName(string hostName, bool ip4Wanted, bool ip6Wanted)
    {
        // Check if the hostname is already an IPAddress
        IPAddress outIpAddress;
        if (IPAddress.TryParse(hostName, out outIpAddress) == true)
            return new IPAddress[] { outIpAddress };
        //<----------

        IPAddress[] addresslist = Dns.GetHostAddresses(hostName);

        if (addresslist == null || addresslist.Length == 0)
            return new IPAddress[0];
        //<----------

        if (ip4Wanted && ip6Wanted)
            return addresslist;
        //<----------

        if (ip4Wanted)
            return addresslist.Where(o => o.AddressFamily == AddressFamily.InterNetwork).ToArray();
        //<----------

        if (ip6Wanted)
            return addresslist.Where(o => o.AddressFamily == AddressFamily.InterNetworkV6).ToArray();
        //<----------

        return new IPAddress[0];
    }

答案 4 :(得分:0)

IpAddress 具有将主机名解析为 IpAddress 的适当方法。

IPAddress addr = IPAddress.Parse(hostName)