/*
 * Paraselene
 * Copyright (c) 2009, 2010  Akira Terasaki
 * このファイルは同梱されているLicense.txtに定めた条件に同意できる場合にのみ
 * 利用可能です。
 */
package paraselene.tool;

import paraselene.supervisor.*;

public class IP {
	private int	addr = 0;
	private int	mask = 0;
	RequestParameter.Mobile	mobile;

	private static int toBit( int n ) {
		int	ret = 0;
		int	cnt = 0x80000000;
		for ( int i = 0; i < 32; i++ ) {
			if ( n > 0 ) {
				ret |= cnt;
			}
			cnt >>= 1;
			n--;
		}
		return ret;
	}

	public IP( RequestParameter.Mobile mob, String ip_str ) {
		String[]	part = ip_str.trim().split( "/" );
		if ( part.length == 2 ) {
			mask = toBit( Integer.parseInt( part[1] ) );
		}

		String[]	ip = part[0].split( "\\." );
		if ( ip.length != 4 )	return;
		int	cnt = 24;
		for ( int i = 0; i < 4; i++ ) {
			int	no = Integer.parseInt( ip[i] );
			addr |= (no << cnt);
			cnt -= 8;
		}
		addr &= mask;
		mobile = mob;
	}

	public boolean isHit( String ip_str ) {
		IP	tmp = new IP( null, ip_str.trim() );
		return ( addr == (tmp.addr & mask) );
	}

}

