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

本文关键字:地址 获取 IP FTP 何知道 | 更新日期: 2023-09-27 18:35:15

这是我的ftp:

ftp://192.168.2.4

我想参加192.168.2.4

我尝试了什么

string ipAddress = FTPAddress.Substring(5,11)

有效

问题所在

如您所见,我将长度设置为 11 ,但是,当我更改 ftp 地址时,该11不起作用,我需要新的 ftp 地址长度。 你能帮忙吗

也许是雷古拉尔表达?

更新

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

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

创建一个Uri对象。IP 地址将位于Host属性中。

Uri link = new Uri("ftp://192.168.2.4");
string IpAddress = link.Host;

Uri类还可以提供更多有用的信息。

可以使用 URI 类来处理地址,然后使用 Host 属性读取该部分。

Uri ftpAddress = new Uri("ftp://192.168.2.4");
string ipAddress = ftpAddress.Host;

如果您需要将主机名转换为 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;
    }
}

可用于以下方案:

Uri ftpAddress = new Uri("ftp://example.com/");
string ipAddress = ftpAddress.ResolveHostnameToIp();