user2595617
user2595617

Reputation: 219

check IP address type, IPv4 or IPv6

I need to check whether the IP address is IPv4 or IPv6 in order to manipulate one accordingly.

this can be achieved with something simple, say

<cfset ip = "2a01:bc80:1::">
<cfif ip does not contain ":">
<cfset ipV="IPv4">
<cfelse>
<cfset ipV="IPv6">

though on the other hand, do not think this is a foolproof approach for solving this issue. I also tried to rewrite php example with regex but was not able to sort it out.

<cfset ip = "24.225.236.0">
<cfset checkIp = ReMatch("^[0-9a-f]{1,4}:([0-9a-f]{0,4}:){1,6}[0-9a-f]{1,4}$/", trim(ip))>

<cfif checkIp neq 0>
<cfset ipV="IPv4">
<cfelse>
<cfset ipV="IPv6">
</cfif>

<cfdump var="#ipV#">

What's the best, foolproof way to handle ip version checking?

Upvotes: 0

Views: 1536

Answers (2)

James Moberg
James Moberg

Reputation: 4475

I'd make a isIPv4() UDF so that you don't have to compare the result after performing the check. It could be as easy as:

<cfscript>
function isIPv4(ip){
  return listlen(ip,".") EQ 4;
}
</cfscript>

And then all you would have to do is:

<CFIF isIPv4(IPAddressToTest)>
  This is IPv4
<CFELSE>
  This is not IPv4
</CFIF>

Here's a ColdFusion 5-compatible UDF that checks to see if each octet is valid. (This is a good place to check.):

http://cflib.org/udf/IsIP

Upvotes: 0

Peter Boughton
Peter Boughton

Reputation: 112220

If IPv6 must have a colon, the only small improvement to a straight contains check is to not bother checking past the fifth character, because the segments are not longer than four hex characters?

Also, because the colon is most likely at the fifth position, starting there will return true results faster, so using lastIndexOf is probably slightly more efficient. (Though the difference will in most cases be miniscule.)

<cfset IpV = ( ip.lastIndexOf(':',4) GTE 0 ) ? 'IPv6' : 'IPv4' />

The 4 is because it's a Java method and that's the 0-indexed way to refer to the fifth character. If there is no match, -1 is returned hence the GTE 0 part.

The other improvement is irrelevant to the IP checking side of things, but is the ternary conditional operator... Variable = BooleanCondition ? ValueIfTrue : ValueIfFalse is nicer for simple conditional assignments like this.

Upvotes: 2

Related Questions