如何知道从FTP地址获取IP地址

Mar*_*oli 2 .net c#

这是我的ftp:

ftp://192.168.2.4
Run Code Online (Sandbox Code Playgroud)

我想接受 192.168.2.4

我尝试了什么

string ipAddress = FTPAddress.Substring(5,11)
Run Code Online (Sandbox Code Playgroud)

这样可行

问题

如你所见,我将长度设置为11,但是,当我更改ftp地址时,这11将无法工作,我需要新的ftp地址长度.你能帮忙吗?

也许是reguralr表达?

更新

有时ftp地址可能是这样的: ftp://ip/folder

ope*_*wix 6

创建一个Uri对象.IP地址将在Host属性中.

Uri link = new Uri("ftp://192.168.2.4");
string IpAddress = link.Host;
Run Code Online (Sandbox Code Playgroud)

Uriclass也可以提供更多有用的信息.


Aer*_*roX 6

您可以使用URI类来处理地址,然后使用主机属性来读取它的一部分.

Uri ftpAddress = new Uri("ftp://192.168.2.4");
string ipAddress = ftpAddress.Host;
Run Code Online (Sandbox Code Playgroud)

如果您需要将Hostnames转换为IPAddresses,则以下扩展类可能有所帮助(基于此答案):

public static class UriHostResolveExtension
{
    public static String ResolveHostnameToIp(this Uri uri)
    {
        if (uri.HostNameType == UriHostNameType.Dns)
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(uri.Host);
            if (hostEntry.AddressList.Length > 0)
                return hostEntry.AddressList[0].ToString();
        }
        return uri.Host;
    }
}
Run Code Online (Sandbox Code Playgroud)

可用于以下场景:

Uri ftpAddress = new Uri("ftp://example.com/");
string ipAddress = ftpAddress.ResolveHostnameToIp();
Run Code Online (Sandbox Code Playgroud)