2

This is my ftp:

ftp://192.168.2.4

I want to take the 192.168.2.4

What I tried

string ipAddress = FTPAddress.Substring(5,11)

that works

The problem

as you see, I set the length to 11, however, when I change the ftp address, that 11 won't work and I would need the new ftp address length. could you help please

maybe reguralr expression?

Update

Sometimes the ftp address could be like this: ftp://ip/folder

Uwe Keim
  • 38,279
  • 56
  • 171
  • 280
Marco Dinatsoli
  • 9,834
  • 34
  • 124
  • 238

2 Answers2

6

Create an Uri object. IP address will be in Host property.

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

Uri class can also provide more useful information.

opewix
  • 4,825
  • 1
  • 16
  • 42
6

You can use the URI Class for handling the address then use the Host Property to read that portion of it.

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

And if you need to convert Hostnames to IPAddresses the following extension class might help (based on this Answer):

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

Can be used in the following scenario:

Uri ftpAddress = new Uri("ftp://example.com/");
string ipAddress = ftpAddress.ResolveHostnameToIp();
Community
  • 1
  • 1
AeroX
  • 3,317
  • 2
  • 23
  • 38