Вопрос

So I have some code running an IP check to ensure an ADMIN account cannot have access from outside my network.

string strIP = Request.ServerVariables["REMOTE_ADDR"];
if (
    (strIP.Substring(0, 9) != "XXX.XX.X.")
&&  (strIP.Substring(0, 10) != "XXX.XX.XX.")
&&  (strIP.Substring(0, 6) != "XX.XX.")
&&  (strIP.Substring(0, 6) != "XX.XX.")
)
{
..// Check user for being an ADMIN // ....
}

This code was working fine for several weeks, but suddenly has started consistently to err out. The error message is:

Exception

Exception Type: System. ArgumentOUtOfRangeException

Exception Message: Index and length must refer to a location within the string. Parameter name: length.

When I remove the line with "Substring(0,10)", everything works. Also, when I change the line "Substring(0,10)" to "Substring(0,9)" and remove the last ".", everything works.

Can anyone tell me why or perhaps instruct on what is being done incorrectly? For the life of me I can't figure out what is going on.

Это было полезно?

Решение

The problem is that strIP doesn't have 10 characters because your configuration changed for some reason. You could do something like:

(strIP.Length >= 9 && strIP.Substring(0, 9) != "XXX.XX.X.")
||  (strIP.Length >= 10 && strIP.Substring(0, 10) != "XXX.XX.XX.")
||  (strIP.Length >= 6 && strIP.Substring(0, 6) != "XX.XX.")

Notice that the fourth line was a duplicate of the third.

Другие советы

Do not allow an out of bounds error to happen by putting a check for length of strIP before you try to do any of the sub-string comparisons, like this:

if (strIP.Length == 10)
{
    if ((strIP.Substring(0, 9) != "XXX.XX.X.")
        &&  (strIP.Substring(0, 10) != "XXX.XX.XX.")
        &&  (strIP.Substring(0, 6) != "XX.XX.")
        &&  (strIP.Substring(0, 6) != "XX.XX."))
    {
        ..// Check user for being an ADMIN // ....
    }
}
else
{
    // Do something here, error, message to user, deny access, etc.
}

UPDATE:

If you want to only apply checks, based upon the length of the string, then use a switch statement, like this:

switch (strIP.Length)
{
    case 6:
        if(strIP.Substring(0, 6) != "XX.XX.")
        {
            // Check user for being an ADMIN
        }
        break;
    case 9:
        if(strIP.Substring(0, 9) != "XXX.XX.X.")
        {
            // Check user for being an ADMIN
        }
        break;
    case 10:
        if(strIP.Substring(0, 10) != "XXX.XX.XX.")
        {
            // Check user for being an ADMIN
        }
        break;
    default:
        // IP string is not in format expected, do something here
        // Most likely would want to err on the side of caution and deny access
        break;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top