简体   繁体   中英

How to determine if an IP Address is routable?

I have an FTP server where it is returning an invalid IP Address for a PASV command. Filezilla automatically detects this. How do I validate an IP Address in C# to make sure it is routable?

Here is what filezilla has in the log: Command: PASV Response: 227 Entering Passive Mode (10,46,169,44,21,124). Status: Server sent passive reply with unroutable address. Using server address instead.

For checking private addresses(biggest subset of non-routable addresses) you could something like:

public static bool IsPrivateAddress(this IPAddress addr)
{
    if(addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
    {
        return addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal;
    }
    var bytes = addr.GetAddressBytes();
    return
        ((bytes[0] == 10) ||
        ((bytes[0] == 192) && (bytes[1] == 168)) ||
        ((bytes[0] == 172) && ((bytes[1] & 0xf0)==16)));
}

there are more non routable addresses (eg loopback, multicast, and experimental blocks) but it seems unlikely you would see those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM