15

我正在尝试与 IP 地址建立 TCP 套接字连接。我可以通过直接解析这样的 IP 地址来做到这一点:

IPAddress ipAddress = IPAddress.Parse("192.168.1.123");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 80);
// Create a TCP/IP  socket.
Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  // This works!

但是,我无法弄清楚如何从 DNS 字符串中判断该 IP 地址。我已经尝试了以下每种组合:

IPAddress ipAddress = Dns.Resolve("www.mydns.org");   // No dice
IPAddress ipAddress = Dns.GetHostEntry("www.mydns.org");  // Nada
IPAddress ipAddress = IPAddress.Parse(Dns.Resolve("www.mydns.org"));   // So many errors...
IPAddress ipAddress = IPAddress.Parse(Dns.Resolve("www.mydns.org").toString());  // WTh is this attempt anyway?

你们中的任何一个好心人都可以帮我从 DNS 中挤出一个 IPAddress 吗?

4

3 回答 3

24
foreach (IPAddress ip in Dns.GetHostAddresses("www.mydns.org"))
{
    Console.WriteLine(ip.ToString());
}

或者只是IPAddress address = Dns.GetHostAddresses("www.mydns.org")[0];如果你只想要第一个。

于 2012-10-06T03:02:57.640 回答
10

为此,我有一个非常简洁的扩展方法!

我考虑到 IPV6 可能会作为 DNS 类返回的地址列表中的第一个地址返回,并允许您对结果“偏爱”IPV6 或 IPV4。这是完整记录的类(为简洁起见,仅使用此案例的相关方法):

using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;

/// <summary>
/// Basic helper methods around networking objects (IPAddress, IpEndPoint, Socket, etc.)
/// </summary>
public static class NetworkingExtensions
{
    /// <summary>
    /// Converts a string representing a host name or address to its <see cref="IPAddress"/> representation, 
    /// optionally opting to return a IpV6 address (defaults to IpV4)
    /// </summary>
    /// <param name="hostNameOrAddress">Host name or address to convert into an <see cref="IPAddress"/></param>
    /// <param name="favorIpV6">When <code>true</code> will return an IpV6 address whenever available, otherwise 
    /// returns an IpV4 address instead.</param>
    /// <returns>The <see cref="IPAddress"/> represented by <paramref name="hostNameOrAddress"/> in either IpV4 or
    /// IpV6 (when available) format depending on <paramref name="favorIpV6"/></returns>
    public static IPAddress ToIPAddress(this string hostNameOrAddress, bool favorIpV6=false)
    {
        var favoredFamily = favorIpV6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
        var addrs = Dns.GetHostAddresses(hostNameOrAddress);
        return addrs.FirstOrDefault(addr => addr.AddressFamily == favoredFamily)
               ??
               addrs.FirstOrDefault();
    }
}

不要忘记将此类放在命名空间中!:-)

现在您可以简单地执行此操作:

var server = "http://simpax.com.br".ToIPAddress();
var blog = "http://simpax.codax.com.br".ToIPAddress();
var google = "google.com.br".ToIPAddress();
var ipv6Google = "google.com.br".ToIPAddress(true); // if available will be an IPV6
于 2013-05-28T21:05:04.243 回答
2
IPHostEntry entry = Dns.GetHostEntry(hostNameOrAddress: "www.google.com");
foreach (IPAddress addr in entry.AddressList)
{
    // connect, on sucess call 'break'
}

通过调用 GetHostEntry 简单地枚举地址,成功打破循环

于 2012-10-06T03:09:53.600 回答