คู่มือนี้สอนใช้ netstat ตรวจสอบ Network Connection, Listening Ports และวิเคราะห์ Traffic แบบ Real-time
📝 หมายเหตุ: netstat ถูก Deprecated แทนด้วย ss (socket statistics) จากแพ็กเกจ iproute2 คำสั่ง ss เร็วกว่า และแสดงข้อมูลมากกว่า แต่อ่าน netstat ได้ยังคงมีประโยชน์
คำสั่งพื้นฐาน
| คำสั่ง | คำอธิบาย |
netstat -ant | แสดง TCP Connection ทั้งหมด (-a all, -n numeric, -t tcp) |
netstat -anp | แสดง PID/Program name (-p ต้อง root) |
netstat -anl | แสดงเฉพาะ Listening ports |
netstat -ant | grep :80 | กรองเฉพาะ Port 80 |
netstat -ant | grep :80 | wc -l | นับจำนวน Connection Port 80 |
วิเคราะห์ Connection State
# สรุป State ทั้งหมด
netstat -ant | awk '{print $6}' | sort | uniq -c | sort -n
# ผลลัพธ์ตัวอย่าง:
1 CLOSE_WAIT
4 FIN_WAIT2
8 LISTEN
16 ESTABLISHED
409 TIME_WAIT
ความหมายของ TCP State
| State | ความหมาย |
LISTEN | รอ Connection เข้า (Server) |
SYN_SENT | ส่ง SYN ไปแล้ว รอ SYN-ACK (Client) |
SYN_RECV | รับ SYN ส่ง SYN-ACK แล้ว รอ ACK (Server) |
ESTABLISHED | เชื่อมต่อสำเร็จ กำลังสื่อสาร |
FIN_WAIT1 | ส่ง FIN ไปแล้ว รอ ACK/FIN |
FIN_WAIT2 | ได้ ACK แล้ว รอ FIN จากอีกฝั่ง |
TIME_WAIT | ปิด Connection แล้ว รอเวลา (2*MSL) ป้องกัน Delayed packets |
CLOSE_WAIT | รับ FIN แล้ว รอ Application ปิด (Leak = Bug) |
CLOSED | ปิดสมบูรณ์ |
คำสั่ง ss (แทน netstat - แนะนำ)
| netstat | ss (ใหม่) | คำอธิบาย |
netstat -ant | ss -ant | TCP connections |
netstat -anp | ss -anp | + PID/Process |
netstat -anl | ss -anl | Listening sockets |
netstat -anu | ss -anu | UDP connections |
netstat -i | ss -i | Interface statistics |
| - | ss -s | Summary statistics |
| - | ss -o state established '( dport = :80 or sport = :80 )' | Filter ขั้นสูง |
การใช้งานจริง: ตรวจจับ DoS/Attack
# หา IP ที่เชื่อมต่อเยอะที่สุด (Top 20)
netstat -ant | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn | head -20
# ss version (เร็วกว่า)
ss -ant | awk '{print $5}' | cut -d: -f1 | sort | uniq -c | sort -rn | head -20
netstat/ss เป็นเครื่องมือวินิจฉัย Network พื้นฐานที่ SysAdmin ต้องเชี่ยวชาญ