无法在C#中将域解析为IP?

时间:2011-06-27 20:54:12

标签: c# .net dns ip

我有这段代码:

IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(txtBoxIP.Text), MainForm.port);

例如,当我在txtBoxIP(192.168.1.2)中有IP时,它的效果很好。

但是如果我想放一个DNS?就像我正在推送(my.selfip.com):

System.FormatException: An invalid IP address was specified.
at System.Net.IPAddress.InternalParse(String ipString, Boolean tryParse)

如何使其支持IP和DNS?

6 个答案:

答案 0 :(得分:8)

IPAddress ipAddress;
if (!IPAddress.TryParse (txtBoxIP.Text, out ipAddress))
   ipAddress = Dns.GetHostEntry (txtBoxIP.Text).AddressList[0];
serverEndPoint = new IPEndPoint(ipAddress, MainForm.port)

不要忘记错误处理。

答案 1 :(得分:2)

DNS到IP列表

IPHostEntry nameToIpAddress;
nameToIpAddress = Dns.GetHostEntry("HostName");
foreach (IPAddress address in nameToIpAddress.AddressList)
    Console.WriteLine(address.ToString());

然后您可以使用AddressList中的IP。

Here是一篇很棒的文章

答案 2 :(得分:2)

DNS名称不是IP地址。查看Dns.GetHostEntry()以获取DNS解析。

编辑补充:这就是我所做的:

public static IPEndPoint CreateEndpoint( string hostNameOrAddress , int port )
{
  IPAddress addr    ;
  bool      gotAddr = IPAddress.TryParse( hostNameOrAddress , out addr ) ;

  if ( !gotAddr )
  {
    IPHostEntry dnsInfo = Dns.GetHostEntry( hostNameOrAddress ) ;

    addr = dnsInfo.AddressList.First() ;

  }

  IPEndPoint instance = new IPEndPoint( addr , port ) ;
  return instance ;
}

答案 3 :(得分:2)

var input = txtBoxIP.Text;
IPAddress ip;

// TryParse returns true when IP is parsed successfully
if (!IPAddress.TryParse (input, out ip))
    // in case user input is not an IP, assume it's a hostname
    ip = Dns.GetHostEntry (input).AddressList [0]; // you may use the first one

// note that you'll also want to handle input errors
// such as invalid strings that are neither IPs nor valid domains,
// as well as hosts that couldn't be resolved

var serverEndPoint = new IPEndPoint (ip, MainForm.port);

答案 4 :(得分:1)

您必须自己查找主机名的IP:

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

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

修改

告诉两者之间的区别(BTW使用C#的某些功能,可能在3.5及以上):

bool isDomain = false;
foreach(char c in addrText.ToCharArray())
{
   if (char.IsLetter(c)){
     isDomain = true;
     break;
}

if (isDomain)
   // lookup IP here
else
   // parse IP here

答案 5 :(得分:0)

注意:不,它不是似曾相识,这个答案与我在另一个重复的问题上提供的完全相同......我想让这个人的作者知道另一个,所以最好的方式我'我发现是在这里再次添加它,因为在Stack Overflow上只是链接到其他答案。

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

我考虑到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