«   2025/03   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31
Archives
Today
Total
관리 메뉴

올해는 머신러닝이다.

Node로 GeoIP 서비스 개발 본문

스터디/Node Js

Node로 GeoIP 서비스 개발

행복한 수지아빠 2025. 3. 17. 12:06

직접 GeoIP 서비스를 만드는 방법을 안내드리겠습니다.

기본적으로 http://ip-api.com/json과 같은 GeoIP API 서비스는 이미 구축된 대형 IP 데이터베이스를 통해 IP 주소를 국가, 지역, 도시, 타임존으로 변환하는 작업을 수행합니다.

직접 구현하려면, 공개된 GeoIP 데이터베이스를 다운받아 서버에서 직접 처리하는 방식이 필요합니다. 가장 널리 사용되는 무료 GeoIP 데이터베이스는 MaxMind GeoLite2입니다.


✅ [직접 GeoIP 서비스 구축 방법]

다음 절차로 진행합니다:

1단계 - MaxMind에서 GeoIP 데이터베이스 다운로드하기

파일명 예시:

GeoLite2-City.mmdb

2단계 - Node.js로 GeoIP 서버 만들기

① 라이브러리 설치하기

npm install express maxmind cors
  • express : 웹 서버 구축용
  • maxmind : mmdb 데이터베이스를 읽고 IP 기반의 위치정보를 조회하는 라이브러리
  • cors : 클라이언트 요청 허용 미들웨어 (선택)

② 프로젝트 폴더 구조 예시

my-geoip-server/
├── app.js
└── GeoLite2-City.mmdb

③ 서버 코드 (app.js)

const express = require('express');
const maxmind = require('maxmind');
const cors = require('cors');

const app = express();
const PORT = process.env.PORT || 3000;

app.use(cors());

// MMDB 파일을 미리 로드하여 성능 향상
let cityLookup;

maxmind.open('./GeoLite2-City.mmdb')
  .then((lookup) => {
    cityLookup = lookup;
    console.log('GeoIP 데이터베이스 로드 완료.');
  })
  .catch(err => {
    console.error('데이터베이스 로드 실패:', err);
  });

// IP 얻는 함수
function getClientIP(req) {
  return req.headers['x-forwarded-for']?.split(',').shift()
    || req.socket?.remoteAddress
    || null;
}

// GeoIP API 라우트
app.get('/geoip', (req, res) => {
  const userIP = getClientIP(req);

  if (!userIP) {
    return res.status(400).json({ status: 'fail', message: 'IP 주소를 얻을 수 없습니다.' });
  }

  const geoData = cityLookup.get(userIP);

  if (!geoData) {
    return res.status(404).json({ status: 'fail', message: 'IP에 대한 위치 정보를 찾을 수 없습니다.' });
  }

  // 결과 JSON 형태로 반환
  res.json({
    status: 'success',
    country: geoData.country?.names?.en || '알 수 없음',
    countryCode: geoData.country?.iso_code || '알 수 없음',
    region: geoData.subdivisions?.[0]?.iso_code || '알 수 없음',
    regionName: geoData.subdivisions?.[0]?.names?.en || '알 수 없음',
    city: geoData.city?.names?.en || '알 수 없음',
    zip: geoData.postal?.code || '알 수 없음',
    lat: geoData.location?.latitude || '알 수 없음',
    lon: geoData.location?.longitude || '알 수 없음',
    timezone: geoData.location?.time_zone || '알 수 없음',
    query: userIP
  });
});

// 서버 실행
app.listen(PORT, () => {
  console.log(`GeoIP 서버가 포트 ${PORT}에서 실행 중입니다.`);
});

3단계 - 서버 실행 및 결과 확인

서버 실행:

node app.js

브라우저로 테스트:

http://localhost:3000/geoip

테스트 시 반환 결과(JSON 예시):

{
  "status": "success",
  "country": "South Korea",
  "countryCode": "KR",
  "region": "12",
  "regionName": "Seoul",
  "city": "Yd1-gu",
  "zip": "079",
  "lat": xxx.xxxx,
  "lon": 1xx.9xx,
  "timezone": "Asia/Seoul",
  "query": "123.456.789.000"
}

(데이터베이스 버전이나 IP에 따라 상세 정보는 다를 수 있음)


이대로 따라하면, 직접 구축한 GeoIP 서비스가 만들어집니다.