Computer >> Hướng Dẫn Máy Tính >  >> Điện Thoại Thông Minh >> Linux

Cách tìm địa chỉ IP công cộng (Public IP) từ dòng lệnh Linux

Hướng dẫn nhanh xác định public IP của máy Linux từ terminal – không cần trình duyệt.

Cách 1: wget + sed (cách gốc)

# wget -q -O - checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//'
122.172.9.222
  • -q: Quiet (không in tiến độ).
  • -O -: Ghi ra stdout.
  • sed: Lọc HTML trả về lấy IP.

Lưu ý: checkip.dyndns.org có thể thay đổi định dạng/ngừng hoạt động.

Cách 2: curl + dịch vụ API JSON (Khuyến khích – ổn định hơn)

# curl -s https://api.ipify.org
# curl -s https://ifconfig.me
# curl -s https://ipinfo.io/ip
# curl -s https://icanhazip.com
# curl -s https://ident.me

Trả về IP thuần túy, không cần parse HTML.

Cách 3: dig (DNS query) – Nhanh, không cần HTTP

# dig +short myip.opendns.com @resolver1.opendns.com
# dig +short TXT +noall +answer o-o.myaddr.l.google.com @ns1.google.com

Tạo script tiện ích myip

#!/bin/bash
# File: /usr/local/bin/myip (cần sudo để ghi vào /usr/local/bin)
curl -s https://api.ipify.org
echo  # Xuống dòng

Cấp quyền và dùng:

# chmod +x /usr/local/bin/myip
# myip
122.172.9.222

Lưu ý: Trên macOS, dùng /usr/local/bin (hoặc /opt/homebrew/bin trên Apple Silicon).

Lấy thêm thông tin chi tiết (GeoIP)

# curl -s https://ipinfo.io/json
{
  "ip": "122.172.9.222",
  "city": "Ho Chi Minh City",
  "region": "Ho Chi Minh",
  "country": "VN",
  "loc": "10.8231,106.6297",
  "org": "AS45899 VNPT Corp",
  "timezone": "Asia/Ho_Chi_Minh"
}

Ứng dụng thực tế

  • Script cập nhật Dynamic DNS (Cloudflare, DuckDNS, No-IP).
  • Kiểm tra VPN/Proxy có hoạt động: myip trước/sau khi bật VPN.
  • Whitelist IP trong firewall/security group (AWS SG, Cloudflare).
  • Xác thực IP base cho API/admin panel.

Lưu ý về IPv6

Nếu máy có IPv6, các dịch vụ trên có thể trả về IPv6. Buộc IPv4:

# curl -4 https://api.ipify.org
# dig -4 +short myip.opendns.com @resolver1.opendns.com