001/**
002 *
003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
004 *
005 * This library is free software; you can redistribute it and/or
006 * modify it under the terms of the GNU Lesser General Public
007 * License as published by the Free Software Foundation; either 
008 * version 2.1 of the License, or (at your option) any later version.
009 * 
010 * This library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
013 * Lesser General Public License for more details.
014 * 
015 * You should have received a copy of the GNU Lesser General Public 
016 * License along with this library.  If not, see <http://www.gnu.org/licenses/>.
017 * 
018 **/
019package lucee.runtime.functions.decision;
020
021import java.net.Inet6Address;
022import java.net.InetAddress;
023import java.net.UnknownHostException;
024
025import lucee.commons.lang.StringUtil;
026import lucee.runtime.PageContext;
027import lucee.runtime.exp.PageException;
028import lucee.runtime.op.Caster;
029
030public class IsIPv6 {
031        public static boolean call(PageContext pc) throws PageException {
032                try {
033                        InetAddress ia = InetAddress.getLocalHost();
034                        InetAddress[] ias = InetAddress.getAllByName(ia.getHostName());
035                        return _call(ias);
036                } 
037                catch (UnknownHostException e) {
038                        throw Caster.toPageException(e);
039                }
040        }
041        
042        public static boolean call(PageContext pc,String hostName) throws PageException {
043                if(StringUtil.isEmpty(hostName)) return call(pc);
044                try {
045                        InetAddress[] ias = InetAddress.getAllByName(hostName);
046                        return _call(ias);
047                } 
048                catch (UnknownHostException e) {
049                        if(hostName.equalsIgnoreCase("localhost") || hostName.equals("127.0.0.1") || hostName.equalsIgnoreCase("0:0:0:0:0:0:0:1") || hostName.equalsIgnoreCase("::1"))
050                    return call(pc);
051                throw Caster.toPageException(e);
052                }
053        }
054        
055        
056        private static boolean _call(InetAddress[] ias) {
057                for(int i=0;i<ias.length;i++)        {
058            if(ias[i] instanceof Inet6Address) return true;
059        }
060        return false;
061        }
062}