ThinkPHP에서 서버 출구 IP를 확인하는 방법

저자:Lisa Farrell·2026-06-01

ThinkPHP 프로젝트에서 서버 측으로 https://my.ipin.io/info 를 호출하면 외부 인터넷에 접근할 때 사용하는 서버 출구 IP를 확인할 수 있습니다. 운영 진단, 프록시 확인, 클라우드 지역 확인에 적합합니다.

설계 목표

“ThinkPHP에서 서버 출구 IP를 확인하는 방법”에서는 IP 요청이 끝나기 전에도 페이지가 유용해야 합니다. 위치 결과는 보조 정보로 검증한 뒤 한정된 판단에만 사용하고, 필드가 불완전하면 적용하지 않습니다.

요청 및 판단 흐름

ThinkPHP에서 서버 출구 IP를 확인하는 방법: 아래 흐름은 이 구현에 맞춘 것으로, 일반적인 IP 조회 체크리스트를 재사용한 것이 아닙니다.

  1. 단계 1 — 기본 상태: OutboundIpService(endpoint)
  2. 단계 2 — 요청: connect=1.2s; total=3s
  3. 단계 3 — 검증: ip + country validation
  4. 단계 4 — 판단: Cache::set(..., 300)
  5. 단계 5 — 폴백: Log::warning context

운영 환경을 고려한 예제

ThinkPHP에서 서버 출구 IP를 확인하는 방법: 예제에는 타임아웃, 응답 검증, 결정적인 기본값, 프레임워크별 생명주기 처리가 포함됩니다.

<?php
namespace app\service;

use think\facade\Cache;
use think\facade\Log;

final class OutboundIpService
{
    public function __construct(
        private string $endpoint = 'https://my.ipin.io/info'
    ) {}

    public function lookup(): array
    {
        $fallback = Cache::get('ipin:last_good', [
            'ip' => 'Unknown', 'country' => 'ZZ',
            'region' => '', 'city' => '', 'source' => 'fallback'
        ]);
        $started = microtime(true);
        $ch = curl_init($this->endpoint);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CONNECTTIMEOUT_MS => 1200,
            CURLOPT_TIMEOUT_MS => 3000,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_HTTPHEADER => ['Accept: application/json'],
            CURLOPT_USERAGENT => 'ipin-outbound-check/1.0',
        ]);

        try {
            $body = curl_exec($ch);
            if ($body === false) {
                throw new \RuntimeException('cURL: '.curl_error($ch));
            }
            $status = (int) curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
            if ($status !== 200) {
                throw new \RuntimeException('HTTP '.$status);
            }
            $data = json_decode($body, true, 32, JSON_THROW_ON_ERROR);
            $ip = filter_var($data['ip'] ?? '', FILTER_VALIDATE_IP,
                FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE);
            $country = strtoupper((string) ($data['country'] ?? ''));
            if (!$ip || !preg_match('/^[A-Z]{2}$/', $country)) {
                throw new \UnexpectedValueException('Invalid IP payload');
            }
            $result = [
                'ip' => $ip, 'country' => $country,
                'region' => (string) ($data['region'] ?? ''),
                'city' => (string) ($data['city'] ?? ''),
                'source' => 'live',
            ];
            Cache::set('ipin:last_good', $result, 300);
            return $result;
        } catch (\Throwable $e) {
            Log::warning('Outbound IP lookup failed', [
                'message' => $e->getMessage(),
                'duration_ms' => (int) ((microtime(true) - $started) * 1000),
            ]);
            return $fallback;
        } finally {
            curl_close($ch);
        }
    }
}

테스트 매트릭스

“ThinkPHP에서 서버 출구 IP를 확인하는 방법”을 게시하기 전에 모의 응답이나 제어 가능한 VPN 출구로 다음 항목을 확인합니다.

조건입력 / 설정예상 결과
T1HTTP 200; ip=203.0.113.10; country=JPsource=live; Cache TTL=300
T2egress IP A → Bnew value after TTL
T3cURL error=28source=fallback; Log::warning
T4private IP / country=nullreject; cache unchanged

자동화 / 스모크 테스트

public function test_rejects_incomplete_payload(): void
{
    $service = new OutboundIpService('http://127.0.0.1:9081/missing-country');
    $result = $service->lookup();
    $this->assertSame('fallback', $result['source']);
}

장애 처리

ThinkPHP에서 서버 출구 IP를 확인하는 방법: 오류는 로그나 개발자 도구에서 확인할 수 있어야 하지만 빈 모듈이나 깨진 결제 화면을 방문자에게 보여서는 안 됩니다.

장애원인대응
cURL 6 / 60DNS / CACache:last_good + Log
HTTP 429 / 5xxremote APIshort cache; no request loop
allow_url_fopen=0file_get_contentscURL
proxy IP mismatchegress routeproxy/container network check

실제 적용 사례

“ThinkPHP에서 서버 출구 IP를 확인하는 방법”의 현실적인 적용 사례: API 서버를 새 프록시 뒤로 이전한 후 운영팀이 감지된 출구 IP를 협력사 허용 목록과 비교하고 마지막 정상 값을 저장합니다.

운영 시 주의사항

ThinkPHP에서 서버 출구 IP를 확인하는 방법: 기본 HTML을 완전하게 유지하십시오. IP 위치는 신원 증명이 아니며 브라우저의 위치 결과를 권한 제어에 사용하면 안 됩니다.

정리

“ThinkPHP에서 서버 출구 IP를 확인하는 방법”은 이제 공통 템플릿이 아니라 고유한 구현 경로, 테스트 근거, 폴백 동작을 갖습니다.