2019년 12월 23일 월요일

Maxmind Country IP Migration(mysql)

csv 파일 중
‘…Locations-en.csv’는 지역코드별 국가명.
‘…Blocks-IPv4.csv’는 IP subnet 별 지역코드.
두 개를 조합하여 국가코드를 뽑아낼 수 있다.
subnet으로 되어 있는 ip는 비교하기가 쉽지 않으므로 subnet을
  1. Blocks-IPv4.csv를 db에 insert
  2. 1의 테이블에 3의 필드를 추가.
  3. from_ip NVARCHAR(20),
    to_ip NVARCHAR(20),
    uint_from_ip int unsigned,
    uint_to_ip int unsigned
  4. update [TABLE]
    set from_ip= INET_NTOA(INET_ATON( SUBSTRING_INDEX(network, '/', 1))
    & 0xffffffff ^ ((0x1 << ( 32 - SUBSTRING_INDEX(network, '/', -1)) ) -1 )),
    to_ip= INET_NTOA(INET_ATON( SUBSTRING_INDEX(network, '/', 1))
    | ((0x100000000 >> SUBSTRING_INDEX(network, '/', -1) ) -1 ));
  5. UPDATE [TABLE] SET uint_from_ip = inet_aton(SUBSTRING(network, 1, LOCATE('/', network) - 1)),
    uint_to_ip = (inet_aton(SUBSTRING(network, 1, LOCATE('/', network) - 1)) + (pow(2, (32-CONVERT(SUBSTRING(network, LOCATE('/', network) + 1), UNSIGNED INT)))-1));
  6. 4는 subnet을 ip의 범위로 바꿔주는 쿼리며, 5는 ip를 int형 숫자로 바꿔주는 쿼리이다.
  7. 특정 IP를 비교할 때 IP를 int형 숫자로 변경 후(npm ip-subnet-calculator 참조), uint_from_ip와 uint_to_ip 사이에 있는지 확인하여 국가코드를 뽑아내면 된다.

댓글 없음: