48

我为此进行了很多谷歌搜索,我发现了很多例子,但没有一个对我有用。这是一个简单的问题,我觉得有一个简单的答案,无需定义新的类\模块等......

我的代码是这样的:

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 变量?

4

5 回答 5

91

您可以简单地使用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);
}
于 2012-11-06T10:26:27.200 回答
35
string howtogeek = "www.howtogeek.com";
IPAddress[] addresslist = Dns.GetHostAddresses(howtogeek);

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

howtogeek

于 2012-11-06T10:27:41.813 回答
10

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

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

using System.Linq;

string host = "google.com";

Dns.GetHostEntry(host).AddressList.First(addr => addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
于 2018-06-30T07:23:07.103 回答
2

这是我用来将主机名解析为 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];
    }
于 2020-05-16T20:55:24.060 回答
0

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

IPAddress addr = IPAddress.Parse(hostName)
于 2021-05-18T10:59:42.407 回答