Can't parse domain into IP in C#?
I have this code:
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(txtBoxIP.Text), MainForm.port);
When I have an IP in the txtBoxIP (192.168.1.2) for example, it works great.
But if I want to put a DNS? like I'm putting (my.selfip.com) I get:
Sy开发者_高级运维stem.FormatException: An invalid IP address was specified.
at System.Net.IPAddress.InternalParse(String ipString, Boolean tryParse)
How can I make it support both IP and DNS ?
IPAddress ipAddress;
if (!IPAddress.TryParse (txtBoxIP.Text, out ipAddress))
ipAddress = Dns.GetHostEntry (txtBoxIP.Text).AddressList[0];
serverEndPoint = new IPEndPoint(ipAddress, MainForm.port)
Don't forget the error handling.
A DNS name isn't an IP address. Look at Dns.GetHostEntry()
for DNS resolution.
Edited to add: Here's what I've done:
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 ;
}
DNS to IP List
IPHostEntry nameToIpAddress;
nameToIpAddress = Dns.GetHostEntry("HostName");
foreach (IPAddress address in nameToIpAddress.AddressList)
Console.WriteLine(address.ToString());
Then you can use the IP's in the AddressList.
Here is a great article
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);
Note: No, it is not déjà vu, this answer is the exact same I provided on another duplicate question... I wanted to make the author of this one aware of the other so the best way I've found was to add it again here as just linking to other answers is frowned upon on Stack Overflow.
I've got a very neat extension method for just that!
I takes into account that an IPV6 may be returned as the first address in the list of addresses returned by the DNS class and allows you to "favor" an IPV6 or IPV4 on the result. Here is the fully documented class (only with the pertinent method for this case for reasons of brevity):
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();
}
}
Don't forget to put this class inside a namespace! :-)
Now you can simply do this:
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
You'll have to look up the IP of the hostname yourself:
string addrText = "www.example.com";
IPAddress[] addresslist = Dns.GetHostAddresses(addrText);
foreach (IPAddress theaddress in addresslist)
{
Console.WriteLine(theaddress.ToString());
}
Edit
To tell the difference between the two (BTW this uses some features of C# that may be in 3.5 and above):
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
精彩评论