Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> สมาร์ทโฟน >> Linux

วิธี Monitor Network Connection ใน Linux ด้วย netstat

คู่มือนี้สอนใช้ netstat ตรวจสอบ Network Connection, Listening Ports และวิเคราะห์ Traffic แบบ Real-time

📝 หมายเหตุ: netstat ถูก Deprecated แทนด้วย ss (socket statistics) จากแพ็กเกจ iproute2 คำสั่ง ss เร็วกว่า และแสดงข้อมูลมากกว่า แต่อ่าน netstat ได้ยังคงมีประโยชน์

คำสั่งพื้นฐาน

วิเคราะห์ 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

คำสั่งคำอธิบาย
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

คำสั่ง ss (แทน netstat - แนะนำ)

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ปิดสมบูรณ์

การใช้งานจริง: ตรวจจับ 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 ต้องเชี่ยวชาญ

netstatss (ใหม่)คำอธิบาย
netstat -antss -antTCP connections
netstat -anpss -anp+ PID/Process
netstat -anlss -anlListening sockets
netstat -anuss -anuUDP connections
netstat -iss -iInterface statistics
-ss -sSummary statistics
-ss -o state established '( dport = :80 or sport = :80 )'Filter ขั้นสูง