2012-10-06 14 views
10

Sto tentando di stabilire una connessione socket TCP a un indirizzo IP. Posso fare questo analizzando direttamente un indirizzo IP in questo modo:Risoluzione di un indirizzo IP da DNS in C#

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! 

Tuttavia, non riesco a capire come indovinare questo indirizzo IP da una stringa DNS. Ho provato ogni combinazione di quanto segue:

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? 

Qualcuno di voi tipo anime avere una punta di aiutarmi a spremere un IPAddress da un DNS?

risposta

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

o semplicemente IPAddress address = Dns.GetHostAddresses("www.mydns.org")[0]; Se si desidera solo il primo.

+0

Si signore, sono un mago. Grazie. – Nanomurf

2
IPHostEntry entry = Dns.GetHostEntry(hostNameOrAddress: "www.google.com"); 
foreach (IPAddress addr in entry.AddressList) 
{ 
    // connect, on sucess call 'break' 
} 

semplicemente enumerare indirizzo chiamando GetHostEntry, sul Successo rompere il ciclo

3

Ho un metodo di estensione molto ordinato proprio per questo!

Prendo in considerazione che un IPV6 può essere restituito come primo indirizzo nell'elenco di indirizzi restituiti dalla classe DNS e consente di "favorire" un IPV6 o IPV4 sul risultato. Qui è la classe completamente documentato (solo con il metodo pertinente per questo caso per motivi di brevità):

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

Non dimenticare di mettere questa classe all'interno di uno spazio dei nomi! :-)

Ora si può semplicemente fare questo:

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