pfsense/pfsense — pull request #962 by stilez (2014-02-21 03:35:08+00:00)
Title: Simplify is_ipaddrwithport() & is_hostnamewithport

Simplify the code for these two functions.

The changed code is extremely similar to the method already used by is_literalipaddrv6().

is_ipaddrwithport() uses explode, impode, pushed parts, and generally makes checking and validating more complex than needed. Using a single regex, one can distinguish IPv4:port candidates from [IPv6]:port candidates in one line, avoid separate testing for [] in literal IPv6, and split the parts reliably, more easily than explode-and-array-manipulate.

Similar logic allows is_hostnamewithport() to avoid all explodes, array pop/push, etc, and use a single regex too.

NOTE: it's useful to let a calling function know whether the IP found by is_ipaddrwithport() is an IPv4 or IPv6 IP, as this can shortcut further checks and simplify code. is_ipaddrwithport() returns a True/false value.

As any positive number Boolean-evaluates to True, I have taken advantage of this to have "success" usefully return 4 or 6 (not just "true") to say the type of IP:port matched. It's no extra effort or cost, transparent to any Boolean test, and allows a lot of efficiency and code simplification elsewhere, since calling code that needs to validate an IP:port *and* test if it's IPv4 or IPv6, a common situation, can now do this from the results of the single is_ipaddrwithport() call.