Trang Chủ Quản Trị

Hướng dẫn tích hợp API kiểm tra mở cổng TCP/UDP, nhận diện Client IP và Quản trị hệ thống từ bên ngoài web.

1. Tổng Quan & Cơ Chế Xác Thực

Hệ thống PortCheck cung cấp 2 phân hệ API độc lập với cấp độ quyền hạn khác nhau:
🌐 Public API (Công Cộng) Không cần Token

Dành cho trang chủ, ứng dụng di động, tiện ích desktop hoặc lệnh curl tự động. Cho phép lấy IP/thông tin Client và kiểm tra khả năng mở của 1 cổng TCP hoặc UDP bất kỳ ngoài Internet.

  • GET /api/ip
  • GET /api/client-info
  • POST /api/check
🔐 Admin API (Đặc Quyền Quản Trị) Yêu cầu API Key / Session

Dành riêng cho quản trị viên, script CI/CD giám sát máy chủ hoặc bot quản lý hạ tầng. Cho phép quét dải cổng (X đến Y) song song, xem/sửa cấu hình hệ thống, quản lý mẫu preset và đọc log.

Header: X-Admin-Key: <API_KEY> hoặc Authorization: Bearer <API_KEY>

2. Public API (Trang Chủ)

Các API công cộng phục vụ kiểm tra cổng đơn lẻ và nhận diện chi tiết kết nối mạng của client. Định dạng trao đổi dữ liệu tiêu chuẩn là application/json (hoặc text/plain với lệnh curl).
GET /api/ip Public - Không cần Token

API siêu tốc (ultra-fast, độ trễ < 1ms) chỉ trích xuất và trả về địa chỉ IP của client ngay trong bộ nhớ, không thực hiện DNS lookup ngược hay phân tích nặng. Thích hợp để hiển thị tức thì IP người dùng hoặc dùng trong các script bash / curl nhẹ.

Tham số Query URL (Tùy chọn)

Tham số Kiểu Bắt buộc Mô tả
format string Tùy chọn Nhận json (mặc định) hoặc text (chỉ in raw IP, rất tiện cho script/curl).

Mã Nguồn Mẫu Gọi API

# Lấy IP dạng JSON
curl -s https://portcheck.trong.pro/api/ip

# Lấy raw IP dạng plain text
curl -s "https://portcheck.trong.pro/api/ip?format=text"

Ví Dụ Phản Hồi JSON Thành Công (HTTP 200 OK)

{
  "ip": "27.72.100.25",
  "client_ip": "27.72.100.25"
}
GET /api/client-info Public - Không cần Token

Trả về địa chỉ IP công cộng của client cùng thông tin phân tích mạng chuyên sâu (như trang ip-info): nhận diện User-Agent (trình duyệt, HĐH, thiết bị), kiểm tra Proxy/VPN/Cloudflare, tên miền phân giải ngược (PTR), cổng nguồn ephemeral port và ngôn ngữ.

Tham số Query URL (Tùy chọn)

Tham số Kiểu Bắt buộc Mô tả
format string Tùy chọn Nhận json (mặc định) hoặc text (chỉ in raw IP, rất tiện cho lệnh bash/curl).

Mã Nguồn Mẫu Gọi API

# Lấy toàn bộ thông tin JSON chi tiết
curl -s https://portcheck.trong.pro/api/client-info

# Hoặc chỉ lấy địa chỉ IP dạng chuỗi văn bản (Plain Text)
curl -s "https://portcheck.trong.pro/api/client-info?format=text"

Ví Dụ Phản Hồi JSON Thành Công (HTTP 200 OK)

{
  "client_ip": "113.161.45.12",
  "ip": {
    "client_ip": "113.161.45.12",
    "remote_addr": "113.161.45.12",
    "remote_port": 54210,
    "reverse_dns": "static.viettel.vn",
    "is_ipv6": false
  },
  "proxy": {
    "is_proxy_or_vpn": false,
    "verdict": "direct",
    "label_vi": "Kết nối trực tiếp (Không phát hiện Proxy/VPN)",
    "label_en": "Direct Connection (No Proxy/VPN Detected)",
    "detected_headers": {},
    "claimed_ip": null,
    "is_trusted_proxy": false
  },
  "user_agent": {
    "raw": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...",
    "browser": { "name": "Google Chrome", "version": "122.0.0.0" },
    "os": { "name": "Windows", "version": "10 / 11" },
    "device_type": "Desktop"
  },
  "connection": {
    "protocol": "HTTP/2.0",
    "https": true,
    "accept_language": "vi-VN,vi;q=0.9,en-US;q=0.8,en;q=0.7",
    "primary_language": "Tiếng Việt (vi-VN)",
    "accept_encoding": "gzip, deflate, br",
    "connection_header": "keep-alive"
  },
  "timestamp": "2026-10-18T16:00:00Z"
}
POST /api/check Public - Không cần Token

Thực hiện kiểm tra tính khả dụng của đúng một cổng TCP (bắt tay 3 bước SYN-ACK) hoặc UDP (gói tin thăm dò socket & kiểm tra lỗi ICMP) tới một địa chỉ IP công cộng hoặc tên miền FQDN.

Chính sách an ninh mạng: Hệ thống tự động chặn hoàn toàn tấn công SSRF (chặn IP loopback 127.0.0.1, dải private 10.x, 172.16.x, 192.168.x, link-local metadata 169.254.169.254, CGNAT, broadcast). Các cổng spam/malware nhạy cảm (25, 135, 137–139, 445) bị từ chối với mã 400 port_blocked đối với khách thông thường.

Cấu Trúc JSON Request Body

Trường Kiểu Bắt buộc Mô tả & Ràng buộc
target string Bắt buộc Địa chỉ IPv4, IPv6 hoặc tên miền FQDN (VD: 203.0.113.25 hoặc example.com).
port integer Bắt buộc Số nguyên từ 1 đến 65535 (đúng 1 cổng mỗi lượt gọi).
protocol string Bắt buộc Chỉ chấp nhận "tcp" hoặc "udp".

Mã Nguồn Mẫu Gọi API

curl -X POST https://portcheck.trong.pro/api/check \
  -H "Content-Type: application/json" \
  -d '{
    "target": "google.com",
    "port": 443,
    "protocol": "tcp"
  }'

Ví Dụ Phản Hồi Thành Công (HTTP 200 OK)

{
  "target": "google.com",
  "resolved_ip": "142.250.204.46",
  "port": 443,
  "protocol": "tcp",
  "status": "open",
  "method": "php_socket",
  "latency_ms": 14.8,
  "reason": "connection_succeeded",
  "diagnostics": [
    "Máy chủ đích đã chấp nhận kết nối TCP (SYN-ACK) và hoàn tất bắt tay 3 bước từ VPS."
  ],
  "checked_at": "2026-10-18T16:05:00Z"
}

3. Admin API (Phân Hệ Quản Trị)

Admin API dành riêng cho người quản trị với các tính năng nâng cao: quét dải cổng song song (X đến Y), đọc và cập nhật cấu hình trực tiếp, lưu trữ mẫu preset và xem log hệ thống.

Cơ Chế Xác Thực Admin API Cho Ứng Dụng Bên Ngoài

Mọi yêu cầu gửi tới Admin API từ app bên ngoài hoặc script tự động phải kèm theo Secret API Key thông qua một trong hai HTTP header:

X-Admin-Key: portcheck_admin_secret_key_2026
Authorization: Bearer portcheck_admin_secret_key_2026

* Lưu ý: Khi gọi bằng API Key, hệ thống tự động cho phép thực thi mà không cần token CSRF trình duyệt. Bạn có thể thay đổi API Key này trong tệp config/config.php.

POST /admin/api.php?action=scan (hoặc /api/admin/scan) Admin - Yêu Cầu API Key

Quét song song đa cổng trong dải từ start_port đến end_port (tối đa 100-200 cổng cùng lúc) bằng kiến trúc Non-blocking Socket (stream_select) với tốc độ chỉ 1–2 giây. Bỏ qua hoàn toàn danh sách cổng bị chặn (blocked_ports).

Cấu Trúc JSON Request Body

Trường Kiểu Bắt buộc Mô tả
target string Bắt buộc IP công cộng hoặc FQDN của máy chủ cần quét.
start_port integer Bắt buộc Cổng bắt đầu dải (VD: 20).
end_port integer Bắt buộc Cổng kết thúc dải (VD: 100). Khoảng cách tối đa tuân theo cấu hình max_scan_range.
protocol string Bắt buộc "tcp" hoặc "udp".

Mã Nguồn Mẫu Quét Dải Cổng

curl -X POST https://portcheck.trong.pro/api/admin/scan \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026" \
  -H "Content-Type: application/json" \
  -d '{
    "target": "scanme.nmap.org",
    "start_port": 20,
    "end_port": 100,
    "protocol": "tcp"
  }'

Ví Dụ Phản Hồi JSON

{
  "success": true,
  "target": "scanme.nmap.org",
  "resolved_ip": "45.33.32.156",
  "protocol": "tcp",
  "start_port": 20,
  "end_port": 25,
  "count": 6,
  "results": [
    { "port": 20, "status": "closed", "latency_ms": 210.4 },
    { "port": 21, "status": "closed", "latency_ms": 208.7 },
    { "port": 22, "status": "open", "latency_ms": 215.1 },
    { "port": 23, "status": "closed", "latency_ms": 209.3 },
    { "port": 24, "status": "closed", "latency_ms": 211.0 },
    { "port": 25, "status": "filtered", "latency_ms": null }
  ]
}
GET POST /admin/api.php?action=get_config | save_config Admin - Yêu Cầu API Key

Truy xuất hoặc cập nhật động cấu hình hệ thống: danh sách cổng cấm blocked_ports, thời gian chờ timeout, giới hạn tần suất rate-limits, mức concurrency và dải cổng scan tối đa.

curl -s https://portcheck.trong.pro/admin/api.php?action=get_config \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026"
GET /admin/api.php?action=get_logs Admin - Yêu Cầu API Key

Truy xuất nhật ký kiểm tra cổng và chẩn đoán gần nhất của hệ thống phục vụ giám sát và lưu trữ kiểm toán.

curl -s https://portcheck.trong.pro/admin/api.php?action=get_logs \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026"

4. Bảng Mã Trạng Thái HTTP & Định Dạng Lỗi

PortCheck tuân thủ chuẩn HTTP Status Codes, không bao giờ trả về HTTP 200 cho các trường hợp request lỗi hay bị từ chối:
Mã HTTP Trạng thái / Error Code Ý nghĩa & Biện pháp xử lý
200 OK success: true Yêu cầu kiểm tra hoặc truy xuất thông tin thành công.
400 Bad Request invalid_target Mục tiêu không hợp lệ, không phân giải được DNS hoặc vi phạm chính sách địa chỉ IP công cộng (SSRF loopback/private).
400 Bad Request port_blocked Cổng nằm trong danh sách cấm của hệ thống (VD: 25, 445). Khách cần liên hệ admin hoặc sử dụng Admin API.
401 Unauthorized unauthorized Chưa xác thực quyền quản trị. Thiếu hoặc sai header X-Admin-Key / phiên session hết hạn.
403 Forbidden csrf_invalid Mã xác thực CSRF không hợp lệ (áp dụng khi gọi từ trình duyệt mà không dùng API Key).
429 Too Many Requests rate_limited Vượt quá giới hạn tần suất yêu cầu (Mặc định 15 req/phút mỗi IP hoặc giới hạn đồng thời Concurrency). Hãy đợi trước khi thử lại.
500 Internal Error internal_error Lỗi nội bộ hệ thống trong quá trình khởi tạo socket mạng.

5. Giới Hạn Tần Suất & Chính Sách Bảo Mật SSRF

Cơ Chế Phòng Chống SSRF (Server-Side Request Forgery)

Khi nhận được tên miền (VD: example.com), máy chủ giải quyết toàn bộ bản ghi DNS A và AAAA. Nếu bất kỳ địa chỉ nào trả về là IP nội bộ, loopback (127.0.0.1), cloud metadata (169.254.169.254), CGNAT hay dải mạng riêng tư (RFC 1918), yêu cầu lập tức bị hủy bỏ và trả về 400 Bad Request. Kết nối socket được tạo trực tiếp tới IP đã kiểm duyệt để chống triệt để kỹ thuật tấn công DNS Rebinding.

Cơ Chế Rate Limiting & Concurrency Locks

Hệ thống áp dụng thuật toán Sliding Window và Concurrency Slots (khóa tệp nguyên tử flock không phong tỏa) để đảm bảo không bị cạn kiệt tài nguyên mạng (file descriptors). Khách thông thường được cấp tối đa 15 yêu cầu / 60 giây và tối đa 5 kết nối đồng thời.

1. Overview & Authentication Architecture

PortCheck exposes two segregated REST API subsystems with differentiated privilege tiers:
🌐 Public API (Client Tier) No Token Required

Designed for frontends, mobile applications, desktop CLI utilities, or automated curl checks. Allows inspecting client connection metadata and testing reachability for any single public TCP or UDP port.

  • GET /api/ip
  • GET /api/client-info
  • POST /api/check
🔐 Admin API (Management Tier) API Key Required

Reserved for administrators, CI/CD infrastructure monitoring scripts, or alert bots. Enables parallel multi-port range scanning (Port X to Port Y), runtime configuration management, preset profiles, and logs.

Header: X-Admin-Key: <API_KEY> or Authorization: Bearer <API_KEY>

2. Public API Reference

Public endpoints for single-port reachability checks and client connection telemetry. Standard payload exchange format is application/json (or text/plain via query parameters).
GET /api/ip Public - Unauthenticated

Ultra-fast client IP endpoint (< 1ms latency). Directly extracts the observed client IP in-memory without reverse DNS lookup or heuristic overhead. Perfect for instant UI IP resolution and lightweight CLI / curl scripts.

URL Query Parameters (Optional)

Parameter Type Requirement Description
format string Optional Accepts json (default) or text (outputs only raw IP string, ideal for bash/curl).

API Invocation Examples

# Fetch IP as JSON payload
curl -s https://portcheck.trong.pro/api/ip

# Fetch raw IP as plain text
curl -s "https://portcheck.trong.pro/api/ip?format=text"

Sample Successful JSON Response (HTTP 200 OK)

{
  "ip": "27.72.100.25",
  "client_ip": "27.72.100.25"
}
GET /api/client-info Public - Unauthenticated

Returns the client's public IP address alongside deep network telemetry: User-Agent breakdown (browser, OS, device form factor), proxy/VPN/Cloudflare heuristic evaluation, reverse DNS (PTR record), ephemeral source port, and HTTP language preferences.

URL Query Parameters (Optional)

Parameter Type Requirement Description
format string Optional Accepts json (default) or text (prints raw IP string, ideal for bash/shell commands).

Sample Integration Code

# Fetch comprehensive JSON telemetry
curl -s https://portcheck.trong.pro/api/client-info

# Or retrieve raw IP address in Plain Text format
curl -s "https://portcheck.trong.pro/api/client-info?format=text"

Successful JSON Response Example (HTTP 200 OK)

{
  "client_ip": "113.161.45.12",
  "ip": {
    "client_ip": "113.161.45.12",
    "remote_addr": "113.161.45.12",
    "remote_port": 54210,
    "reverse_dns": "static.viettel.vn",
    "is_ipv6": false
  },
  "proxy": {
    "is_proxy_or_vpn": false,
    "verdict": "direct",
    "label_vi": "Kết nối trực tiếp (Không phát hiện Proxy/VPN)",
    "label_en": "Direct Connection (No Proxy/VPN Detected)",
    "detected_headers": {},
    "claimed_ip": null,
    "is_trusted_proxy": false
  },
  "user_agent": {
    "raw": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36...",
    "browser": { "name": "Google Chrome", "version": "122.0.0.0" },
    "os": { "name": "Windows", "version": "10 / 11" },
    "device_type": "Desktop"
  },
  "connection": {
    "protocol": "HTTP/2.0",
    "https": true,
    "accept_language": "en-US,en;q=0.9",
    "primary_language": "English (en-US)",
    "accept_encoding": "gzip, deflate, br",
    "connection_header": "keep-alive"
  },
  "timestamp": "2026-10-18T16:00:00Z"
}
POST /api/check Public - Unauthenticated

Performs an active network reachability probe on a single target port via TCP (3-way handshake SYN-ACK) or UDP (socket probe & ICMP port unreachable evaluation) to any public destination IP or hostname.

Network Security Policy: SSRF attacks are strictly prohibited (loopback 127.0.0.1, RFC 1918 subnets, cloud metadata 169.254.169.254, CGNAT, and broadcast addresses are blocked). Sensitive spam/malware ports (25, 135, 137–139, 445) are denied with 400 port_blocked for unauthenticated requests.

JSON Request Body Schema

Field Type Requirement Description & Constraints
target string Required Public IPv4, IPv6, or domain FQDN (e.g., 203.0.113.25 or example.com).
port integer Required Integer between 1 and 65535 (exactly 1 port per check).
protocol string Required Must be "tcp" or "udp".

Sample Integration Code

curl -X POST https://portcheck.trong.pro/api/check \
  -H "Content-Type: application/json" \
  -d '{
    "target": "google.com",
    "port": 443,
    "protocol": "tcp"
  }'

Successful JSON Response Example (HTTP 200 OK)

{
  "target": "google.com",
  "resolved_ip": "142.250.204.46",
  "port": 443,
  "protocol": "tcp",
  "status": "open",
  "method": "php_socket",
  "latency_ms": 14.8,
  "reason": "connection_succeeded",
  "diagnostics": [
    "Destination accepted the TCP connection (SYN-ACK) and completed the 3-way handshake."
  ],
  "checked_at": "2026-10-18T16:05:00Z"
}

3. Admin API (Management Tier)

Specialized management endpoints designed for administrative automation: parallel port range sweeps (Port X to Y), runtime configuration edits, profile presets, and system event logging.

Admin API Authentication for External Applications

All calls to Admin API endpoints must supply your Secret API Key via one of two HTTP request headers:

X-Admin-Key: portcheck_admin_secret_key_2026
Authorization: Bearer portcheck_admin_secret_key_2026

* Note: Authenticating via API Key allows non-browser clients to execute tasks without session cookies or CSRF tokens. This token is defined in config/config.php.

POST /admin/api.php?action=scan (or /api/admin/scan) Admin - API Key Required

Concurrently sweeps multiple ports between start_port and end_port (up to 100-200 ports per batch) utilizing non-blocking asynchronous sockets (stream_select) in 1–2 seconds. Completely bypasses the public blocked_ports policy.

JSON Request Body Schema

Field Type Requirement Description
target string Required Target public IP or domain FQDN.
start_port integer Required Range start port (e.g., 20).
end_port integer Required Range end port (e.g., 100). Maximum span is enforced by max_scan_range.
protocol string Required "tcp" or "udp".

Sample Integration Code

curl -X POST https://portcheck.trong.pro/api/admin/scan \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026" \
  -H "Content-Type: application/json" \
  -d '{
    "target": "scanme.nmap.org",
    "start_port": 20,
    "end_port": 100,
    "protocol": "tcp"
  }'

JSON Response Example

{
  "success": true,
  "target": "scanme.nmap.org",
  "resolved_ip": "45.33.32.156",
  "protocol": "tcp",
  "start_port": 20,
  "end_port": 25,
  "count": 6,
  "results": [
    { "port": 20, "status": "closed", "latency_ms": 210.4 },
    { "port": 21, "status": "closed", "latency_ms": 208.7 },
    { "port": 22, "status": "open", "latency_ms": 215.1 },
    { "port": 23, "status": "closed", "latency_ms": 209.3 },
    { "port": 24, "status": "closed", "latency_ms": 211.0 },
    { "port": 25, "status": "filtered", "latency_ms": null }
  ]
}
GET POST /admin/api.php?action=get_config | save_config Admin - API Key Required

Query or dynamically update global system parameters: blocked_ports list, timeouts, rate-limiting quotas, maximum concurrency slots, and scan range bounds.

curl -s https://portcheck.trong.pro/admin/api.php?action=get_config \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026"
GET /admin/api.php?action=get_logs Admin - API Key Required

Retrieves recent application audit logs and diagnostic traces for system health monitoring and log ingestion.

curl -s https://portcheck.trong.pro/admin/api.php?action=get_logs \
  -H "X-Admin-Key: portcheck_admin_secret_key_2026"

4. HTTP Status Codes & Error Schemes

PortCheck adheres to strict HTTP Status Code semantics and never masks errors under HTTP 200 OK:
HTTP Code Status / Error Code Description & Remediation
200 OK success: true Port check or query completed successfully.
400 Bad Request invalid_target Target is invalid, unresolvable, or violates public IP policies (SSRF private/loopback).
400 Bad Request port_blocked Port is forbidden on public endpoints (e.g. 25, 445). Use Admin API or contact administrator.
401 Unauthorized unauthorized Missing or invalid X-Admin-Key header or expired admin session.
403 Forbidden csrf_invalid CSRF token validation failed (applicable to browser session forms).
429 Too Many Requests rate_limited Request rate limit exceeded (default 15 req/min per IP or concurrency limit). Wait before retrying.
500 Internal Error internal_error Internal server error while initializing network sockets.

5. Rate Limiting & SSRF Security Policies

Server-Side Request Forgery (SSRF) Defense

When supplied with a domain name, the server resolves all A and AAAA DNS records. If any resolved IP maps to internal, loopback (127.0.0.1), cloud metadata (169.254.169.254), CGNAT, or private addresses (RFC 1918), the check is immediately rejected with 400 Bad Request. Direct socket probes connect exclusively to the verified IP, immunizing against DNS Rebinding attacks.

Rate Limiting & Concurrency Control

PortCheck enforces a sliding-window token bucket algorithm combined with atomic non-blocking flock concurrency slots. Regular visitors are granted up to 15 requests per 60 seconds, capped at 5 concurrent sockets.