IPAddress.parse () utilizzando la porta su IPv4
-
12-11-2019 - |
Domanda
Sto cercando di analizzare una stringa contenente un indirizzo IP e una porta che utilizza iPAddress.parse. Funziona bene con gli indirizzi IPv6 ma non con gli indirizzi IPv4. Somone può spiegare perché questo accade?
Il codice che sto usando è:
IPAddress.Parse("[::1]:5"); //Valid
IPAddress.Parse("127.0.0.1:5"); //null
Nessuna soluzione corretta
Altri suggerimenti
Uri url;
IPAddress ip;
if (Uri.TryCreate(String.Format("http://{0}", "127.0.0.1:5"), UriKind.Absolute, out url) &&
IPAddress.TryParse(url.Host, out ip))
{
IPEndPoint endPoint = new IPEndPoint(ip, url.Port);
}
Ciò accade perché la porta non fa parte dell'indirizzo IP. Appartiene a TCP/UDP e dovrai prima toglierlo. La classe URI potrebbe essere utile per questo.
IPAddress non è la porta IP+. Vuoi ipendpoint.
Esempio da http://www.java2s.com/code/csharp/network/parsehoststring.htm
public static void ParseHostString(string hostString, ref string hostName, ref int port)
{
hostName = hostString;
if (hostString.Contains(":"))
{
string[] hostParts = hostString.Split(':');
if (hostParts.Length == 2)
{
hostName = hostParts[0];
int.TryParse(hostParts[1], out port);
}
}
}
EDIT: OK, ammetto che non era la soluzione più elegante. Prova questo che ho scritto (solo per te) invece:
// You need to include some usings:
using System.Text.RegularExpressions;
using System.Net;
// Then this code (static is not required):
private static Regex hostPortMatch = new Regex(@"^(?<ip>(?:\[[\da-fA-F:]+\])|(?:\d{1,3}\.){3}\d{1,3})(?::(?<port>\d+))?$", System.Text.RegularExpressions.RegexOptions.Compiled);
public static IPEndPoint ParseHostPort(string hostPort)
{
Match match = hostPortMatch.Match(hostPort);
if (!match.Success)
return null;
return new IPEndPoint(IPAddress.Parse(match.Groups["ip"].Value), int.Parse(match.Groups["port"].Value));
}
Si noti che questo accetta solo l'indirizzo IP, non il nome host. Se si desidera supportare il nome host, dovrai risolverlo in IP o non utilizzare iPAddress/ipendpoint.
IPAddress.Parse ha lo scopo di prendere una stringa che contiene un indirizzo IP nella notazione a trazione tratteggiata per IPv4 e nella notazione del colon-exadecimale per IPv6. Quindi il tuo primo esempio funziona per IPv6 e il tuo secondo esempio fallisce perché non supporta una porta per IPv4. Collegamento http://msdn.microsoft.com/en-us/library/system.net.ipaddress.parse.aspx