Linux: ネットワーク基礎 — ip / curl / sshとネットワーク診断
Linuxネットワークコマンドは「なぜ繋がらないのか」を診断する必須ツールです。IPの確認からポート接続テスト、DNS解決からHTTPリクエストまで — これらのコマンドがネットワークトラブルシューティングの全過程をカバーします。
📋 前提条件:まず以下を完了していること
- レッスン3:ターミナルの基礎
1. このレッスンで学ぶこと
- ip addr/route:ネットワーク設定の確認
- ping/mtr:接続テスト
- curl/wget:HTTPリクエスト
- ss/netstat:ポートリスニング確認
- dig:DNSクエリ
2. 「Webサイトが開かない」ストーリー
(1) 悩み:サービスをデプロイしたが外部からアクセスできない
小明はポート3000でNode.jsサービスをデプロイしましたが、ブラウザでhttp://server-ip:3000にアクセスするとタイムアウトし続けました。
まずローカルで確認:
curl http://localhost:3000
# ✅ Returns HTML normally
次に外部から確認:
# Check if the port is listening
ss -tlnp | grep 3000
# LISTEN 0 128 127.0.0.1:3000 0.0.0.0:* ← Only listening on localhost!
# Node.js bound to 127.0.0.1 instead of 0.0.0.0
(2) バインドアドレスの修正
小明はserver.listen(3000, '127.0.0.1')をserver.listen(3000, '0.0.0.0')に変更。再起動後、外部アクセスが正常に動作しました。
PermitRootLogin noを設定してrootの直接SSHログインを無効化し、一般ユーザー + sudoを使用してください。また、パスワードログイン(PasswordAuthentication no)も無効化し、鍵認証のみを使用してください。
(3) 得られるもの:体系的なトラブルシューティング手法
小明はトラブルシューティングの手順を学びました:ローカルでcurlしてサービス動作確認 → ssでリスニングアドレス確認 → ファイアウォール確認 → 外部からcurlで検証。
3. 知識ポイント
(1) ip — ネットワーク設定
# View IP addresses
ip addr show
# Or shorthand
ip a
# View routing table
ip route
# Or shorthand
ip r
# View network interface status
ip link show
# Enable/disable interface
sudo ip link set eth0 up
sudo ip link set eth0 down
(2) ping/mtr — 接続テスト
# ping (test network connectivity)
ping google.com # Continuous ping, Ctrl+C to stop
ping -c 4 google.com # Ping only 4 times
ping -c 4 -i 2 google.com # 2-second interval
ping -c 10 -q google.com # Summary only
# mtr (combines traceroute and ping)
mtr google.com # Continuously trace route
mtr -r -c 10 google.com # Report mode (output after 10 rounds)
(3) curl/wget — HTTPリクエスト
# curl (HTTP requests)
curl https://example.com # GET request
curl -I https://example.com # Headers only
curl -o page.html https://example.com # Save to file
> 💡 ヒント:`curl -v`(verboseモード)はHTTP問題のデバッグに強力なツール — 完全なリクエストヘッダー、レスポンスヘッダー、TLSハンドシェイク過程を表示し、DNS問題、接続タイムアウト、証明書エラー、リダイレクト問題の特定に役立ちます。`curl`リクエストが失敗した時、まず`-v`を追加して詳細を確認してください。
curl -L http://httpbin.org/redirect/3 # Follow redirects
curl -k https://self-signed.com # Skip SSL verification
curl -X POST -d '{"key":"value"}' -H "Content-Type: application/json" https://api.example.com
# wget (file download)
wget https://example.com/file.zip # Download file
wget -c https://example.com/big.zip # Resume download
wget -r -np https://example.com/docs/ # Recursive download
(4) ss/netstat — ポートリスニング確認
# ss (recommended, faster)
ss -tlnp # TCP listening ports
ss -ulnp # UDP listening ports
ss -tlnp | grep 80 # Filter port 80
ss -tuna # All TCP/UDP connections
# netstat (traditional, may need install)
netstat -tlnp
netstat -i # Network interface statistics
(5) dig — DNSクエリ
# dig
dig example.com # Full DNS query
dig +short example.com # IP only
dig example.com A # Query A record
dig example.com MX # Query mail record
dig @8.8.8.8 example.com # Use specific DNS server
# Other DNS tools
nslookup example.com # Simple query
host example.com # More concise
ℹ️ 注意:
dig、nslookup、hostはすべてDNSレコードをクエリできますが、出力フォーマットが異なります —digが最も詳細(クエリ時間、サーバーなどを含む)、nslookupがより簡潔、hostが最もミニマル(IPのみ)。DNStroubleシューティングにはdig、素早いIP検索にはhostまたはdig +shortを使用してください。
(6) ▶ サンプル:ローカルネットワーク設定の確認
# View all IP addresses
ip -br addr
# lo UNKNOWN 127.0.0.1/8
# eth0 UP 192.168.1.100/24
# View default gateway
ip route | grep default
# default via 192.168.1.1 dev eth0
# View DNS
cat /etc/resolv.conf
# nameserver 8.8.8.8
# nameserver 1.1.1.1
出力:
TEXTlo UNKNOWN 127.0.0.1/8 eth0 UP 192.168.1.100/24 default via 192.168.1.1 dev eth0 nameserver 8.8.8.8 nameserver 1.1.1.1
(7) ▶ サンプル:ネットワーク接続トラブルシューティング
# 1. Ping the gateway first (confirm LAN works)
ping -c 2 192.168.1.1
# 2. Ping an external IP (confirm internet works)
ping -c 2 8.8.8.8
# 3. DNS resolution (confirm domain resolution works)
dig +short google.com
# 4. Port connectivity (confirm service port is open)
nc -zv google.com 80
# Connection to google.com (142.250.80.14) 80 port [tcp/http] succeeded!
# 5. HTTP request (confirm service is working)
curl -I https://example.com
出力:
TEXTPING 192.168.1.1 (192.168.1.1) 56(84) bytes of data. 64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=0.423 ms --- 192.168.1.1 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=118 time=12.3 ms --- 8.8.8.8 ping statistics --- 2 packets transmitted, 2 received, 0% packet loss 142.250.80.14 Connection to google.com (142.250.80.14) 80 port [tcp/http] succeeded! HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 Server: ECS (dcb/7F84)
(8) ▶ サンプル:curlでAPIテスト
# GET request
curl https://api.github.com/users/octocat
# View response headers
curl -I https://httpbin.org
# POST JSON data
curl -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-d '{"name":"Alice","role":"developer"}'
# Authenticated request
curl -u "username:token" https://api.github.com/user
# Test HTTP status code
curl -s -o /dev/null -w "%{http_code}" https://example.com
出力:
TEXT{"login":"octocat","id":583231,"avatar_url":"https://avatars.githubusercontent.com/u/583231?v=4"} HTTP/1.1 200 OK Server: gunicorn/19.9.0 Content-Type: application/json { "json": { "name": "Alice", "role": "developer" } } 200
(9) ▶ サンプル:ポートトラブルシューティング
# View all listening TCP ports
ss -tlnp
# Check if port 3306 (MySQL) is listening
ss -tlnp | grep 3306
# View ports for a specific process
ss -tlnp | grep nginx
# Test if a remote port is open
echo "Testing port 80..."
timeout 3 bash -c "echo >/dev/tcp/example.com/80" && echo "Open" || echo "Closed"
# View connection states
ss -tuna | grep ESTAB
出力:
TEXTState Recv-Q Send-Q Local Address:Port Peer Address:Port Process LISTEN 0 128 0.0.0.0:22 0.0.0.0:* LISTEN 0 128 0.0.0.0:80 0.0.0.0:* LISTEN 0 128 0.0.0.0:443 0.0.0.0:* LISTEN 0 128 *:3306 *:* LISTEN 0 511 *:80 *:* users:(("nginx",pid=1234,fd=6)) Open ESTAB 0 0 192.168.1.100:22 10.0.0.50:52341 ESTAB 0 0 192.168.1.100:443 172.16.0.5:49832
(10) ▶ サンプル:ファイルダウンロード
# wget download
wget -c https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso
# curl download
curl -L -o ubuntu.iso https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso
# Download and extract
curl -L https://github.com/user/repo/archive/main.tar.gz | tar -xz
出力:
TEXT--2026-07-07 10:23:01-- https://releases.ubuntu.com/22.04/ubuntu-22.04.3-live-server-amd64.iso Resolving releases.ubuntu.com... 185.125.190.37 HTTP request sent, awaiting response... 200 OK Length: 2014838784 (1.9G) [application/x-iso9660-image] Saving to: 'ubuntu-22.04.3-live-server-amd64.iso' % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 45% 891M 0 0 891M 0 0 12.3M 0:00:02 0:00:01 0:00:01 12.3M
(11) ▶ 総合例:ネットワーク診断スクリプト
#!/bin/bash
# net-diag.sh - Network diagnostics tool
TARGET="${1:-google.com}"
echo "========================================"
echo " Network Diagnostics Report"
echo " Time: $(date)"
echo "========================================"
echo ""
echo "1. Local Network Configuration"
echo "----------------"
ip -br addr 2>/dev/null || ifconfig
echo ""
echo "2. Default Gateway"
echo "-----------"
ip route | grep default
echo ""
echo "3. DNS Servers"
echo "--------------"
cat /etc/resolv.conf | grep nameserver
echo ""
echo "4. DNS Resolution ($TARGET)"
echo "----------------------"
dig +short "$TARGET" 2>/dev/null || nslookup "$TARGET" 2>/dev/null || host "$TARGET"
echo ""
echo "5. Network Connectivity"
echo "--------------"
ping -c 4 -q "$TARGET" 2>&1 | tail -3
echo ""
echo "6. HTTP Response"
echo "-------------"
curl -s -o /dev/null -w "HTTP %{http_code}, time: %{time_total}s\n" "https://$TARGET" --connect-timeout 5
echo ""
echo "7. Route Tracing"
echo "------------"
mtr -r -c 3 "$TARGET" 2>/dev/null | tail -5 || echo "mtr not installed"
echo ""
echo "8. Listening Ports"
echo "-----------"
ss -tlnp 2>/dev/null | head -10 || netstat -tlnp 2>/dev/null | head -10
echo ""
echo "========================================"
❓ よくある質問
Q: pingが失敗したら必ずネットワーク問題? A: 必ずしもそうではありません。多くのサーバーはICMP(ping)をファイアウォールでブロックしています。pingが失敗してもHTTPが動作するのは全く正常です。代替手段:
nc -zv host portまたはcurl -Iで特定のサービスポートをテスト。
Q: curlとwgetの違いは? A: curlはより機能豊富(全HTTPメソッド、カスタムヘッダー、JSONデータをサポート)、APIテストに最適。wgetはダウンロード機能が強力(再帰的ダウンロード、レジューム、サイトミラーリング)。日常のAPIテストにはcurl、ファイルダウンロードにはwgetを使用。
Q: ssとnetstatどちらが良い? A: ssの方が新しく高速 —
/proc/netを解析せずカーネルソケットバッファから直接読み取ります。netstatは古く、接続数が多いシステムでは遅い。ssを優先してください。新しいシステムではnetstatがデフォルトでインストールされていない場合があります。
Q: ポート80と443の違いは? A: 80はHTTP(平文)、443はHTTPS(暗号化)。現代のWebサイトは基本的に443のみ使用。
curl http://...が動作しない場合はcurl https://...を試してください。
Q: SSH接続が遅い理由は? A: 一般的な原因:1) DNS逆引き(
UseDNS noを設定)。2) GSSAPI認証(GSSAPIAuthentication noを設定)。3) ネットワーク遅延。簡単な修正:~/.ssh/configにUseDNS noとGSSAPIAuthentication noを追加。
📖 まとめ
ip addr/ip routeでIPとルーティングを確認ping -c 4で接続テスト、mtrでルートトレースcurl -Iでレスポンスヘッダー確認、curl -X POST -d '{}'でリクエスト送信ss -tlnpでリスニングポートを確認dig +shortで素早いDNSクエリ
📝 練習問題
- 基本(難易度 ⭐):
ip -br addrでローカルIPとネットワークインターフェースを確認し、ping -c 4 google.comで接続テストを行い結果を分析する - 中級(難易度 ⭐⭐):
ss -tlnpでマシンの全リスニングポートを確認し、curl -I https://example.comでHTTPレスポンスヘッダーを確認、dig +short github.comでGitHubのIPアドレスをクエリする - 上級(難易度 ⭐⭐⭐):ローカルIP、ゲートウェイ、DNS、接続性、HTTPレスポンス、リスニングポートを自動検出するネットワーク診断スクリプトを書き、フォーマット済みレポートを出力し、異常検出時に色付き警告を表示する