🌍 Networking

TCP

Transmission Control Protocol

A reliable data transfer protocol. 3-way handshake, ordering guarantees, error recovery.

📖 Detailed Explanation

TCP (Transmission Control Protocol) is a core protocol of the Internet protocol suite (TCP/IP), responsible for reliable, ordered data transmission. It was designed in 1974 by Vint Cerf and Bob Kahn, and today most Internet services, including web browsing (HTTP/HTTPS), email (SMTP), and file transfer (FTP), run on top of TCP.

The core of TCP is the 3-way handshake. The client sends a SYN packet, the server responds with SYN-ACK, and the client sends an ACK to establish the connection. When closing a connection, a 4-way handshake (FIN → ACK → FIN → ACK) is performed. During this process, the TIME_WAIT state occurs, and on high-traffic servers, managing sockets in this state becomes an important tuning point.

TCP ensures network stability through Flow Control and Congestion Control. Flow Control prevents buffer overflow on the receiver using a sliding window method, and Congestion Control manages network congestion with the Slow Start, Congestion Avoidance, and Fast Retransmit algorithms. It automatically retransmits packets when they are lost and guarantees ordering through sequence numbers.

The choice between TCP and UDP is determined by the characteristics of the service. TCP is suitable for services where data integrity is important, such as the web, email, and file transfer. UDP, on the other hand, is used for services where latency matters more than a small amount of packet loss, such as real-time streaming, online games, and VoIP. Recently, HTTP/3 has been using the UDP-based QUIC protocol to reduce TCP's connection overhead.

💻 Code Example

import socket

# === TCP 서버 ===
def tcp_server():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # SO_REUSEADDR: TIME_WAIT 상태의 포트 재사용
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

    # Keep-Alive 설정 (연결 유지 확인)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

    server.bind(('0.0.0.0', 8080))
    server.listen(5)  # 백로그 큐 크기
    print("서버 대기 중... (포트 8080)")

    while True:
        client, addr = server.accept()
        print(f"연결됨: {addr}")

        # 타임아웃 설정
        client.settimeout(30.0)

        try:
            data = client.recv(1024)
            print(f"수신: {data.decode()}")
            client.send(b"Hello from server!")
        finally:
            client.close()

# === TCP 클라이언트 ===
def tcp_client():
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 연결 타임아웃 설정
    client.settimeout(10.0)

    try:
        client.connect(('localhost', 8080))  # 3-way handshake 발생
        client.send(b"Hello from client!")

        response = client.recv(1024)
        print(f"응답: {response.decode()}")
    except socket.timeout:
        print("연결 타임아웃!")
    finally:
        client.close()  # 4-way handshake로 연결 종료

# === 소켓 상태 확인 (실무 디버깅) ===
def check_socket_options(sock):
    # TCP_NODELAY: Nagle 알고리즘 비활성화 (지연 감소)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

    # 버퍼 크기 확인
    recv_buf = sock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)
    send_buf = sock.getsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF)
    print(f"수신 버퍼: {recv_buf}, 송신 버퍼: {send_buf}")
# TCP 연결 상태 확인
netstat -ant | grep ESTABLISHED
netstat -ant | grep TIME_WAIT | wc -l  # TIME_WAIT 소켓 개수

# ss 명령어 (netstat보다 빠름)
ss -t -a                    # 모든 TCP 소켓
ss -t state established     # ESTABLISHED 상태만
ss -t state time-wait       # TIME_WAIT 상태만
ss -tlnp                    # 리스닝 포트와 프로세스

# TCP 연결 테스트
nc -zv google.com 443       # TCP 포트 연결 확인
telnet google.com 80        # TCP 연결 테스트

# tcpdump로 TCP 패킷 분석
sudo tcpdump -i eth0 'tcp port 80' -n
sudo tcpdump -i any 'tcp[tcpflags] & tcp-syn != 0'  # SYN 패킷만

# 3-way handshake 확인
sudo tcpdump -i eth0 'tcp[tcpflags] & (tcp-syn|tcp-ack) != 0' -n

# TCP 커널 파라미터 확인 및 튜닝
cat /proc/sys/net/ipv4/tcp_fin_timeout      # FIN_WAIT2 타임아웃
cat /proc/sys/net/ipv4/tcp_tw_reuse         # TIME_WAIT 재사용
cat /proc/sys/net/ipv4/tcp_keepalive_time   # Keep-Alive 시간

# TIME_WAIT 최적화 (고트래픽 서버)
sudo sysctl -w net.ipv4.tcp_tw_reuse=1
sudo sysctl -w net.ipv4.tcp_fin_timeout=30

# TCP 버퍼 크기 튜닝
sudo sysctl -w net.core.rmem_max=16777216
sudo sysctl -w net.core.wmem_max=16777216

# 최대 연결 수 확인
cat /proc/sys/net/core/somaxconn            # listen() 백로그 최대값
ulimit -n                                    # 파일 디스크립터 제한
const net = require('net');

// === TCP 서버 ===
const server = net.createServer((socket) => {
    console.log(`클라이언트 연결: ${socket.remoteAddress}:${socket.remotePort}`);

    // Keep-Alive 설정 (30초마다 확인)
    socket.setKeepAlive(true, 30000);

    // Nagle 알고리즘 비활성화 (저지연)
    socket.setNoDelay(true);

    // 타임아웃 설정
    socket.setTimeout(60000);

    socket.on('data', (data) => {
        console.log(`수신: ${data.toString()}`);
        socket.write('Hello from server!');
    });

    socket.on('timeout', () => {
        console.log('소켓 타임아웃');
        socket.end();
    });

    socket.on('error', (err) => {
        console.error(`소켓 에러: ${err.message}`);
    });

    socket.on('close', () => {
        console.log('연결 종료');
    });
});

// 백로그 설정
server.listen(8080, '0.0.0.0', 511, () => {
    console.log('TCP 서버 시작 (포트 8080)');
});

// === TCP 클라이언트 ===
function tcpClient() {
    const client = new net.Socket();

    // 연결 타임아웃
    client.setTimeout(10000);

    client.connect(8080, 'localhost', () => {
        console.log('서버에 연결됨 (3-way handshake 완료)');
        client.write('Hello from client!');
    });

    client.on('data', (data) => {
        console.log(`응답: ${data.toString()}`);
        client.destroy();  // 연결 종료
    });

    client.on('error', (err) => {
        if (err.code === 'ECONNREFUSED') {
            console.error('연결 거부됨 - 서버가 실행 중인지 확인');
        } else if (err.code === 'ETIMEDOUT') {
            console.error('연결 타임아웃');
        }
    });
}

// === 연결 풀 (실무 패턴) ===
const connections = new Map();

function getConnection(host, port) {
    const key = `${host}:${port}`;
    if (!connections.has(key)) {
        const socket = new net.Socket();
        socket.connect(port, host);
        socket.setKeepAlive(true, 30000);
        connections.set(key, socket);
    }
    return connections.get(key);
}

🗣️ Say It Like This in Practice

💬 In a Performance Issue Response Meeting
"There are 30,000 TIME_WAIT sockets piled up on the server, so new connections can't be made. We need to enable tcp_tw_reuse and modify the application to use a Connection Pool. And if we turn on Keep-Alive to increase the connection reuse rate, we can also reduce the handshake overhead."
💬 In a technical interview
"TCP establishes a connection with a 3-way handshake, and provides ordering and reliability through sequence numbers and ACKs. Flow Control manages the receiver's buffer with a sliding window, and Congestion Control regulates network congestion with Slow Start and AIMD. In an actual project, I have experience reducing real-time response latency from 200ms to 5ms by disabling the Nagle algorithm."
💬 In an Architecture Review
"If it's a game server, consider UDP rather than TCP. With TCP, packet loss causes delay while waiting for retransmission, and in real-time games this is fatal. Alternatively, there's a way to keep the connection alive with WebSocket and detect disconnections with a heartbeat. HTTP/3's QUIC is also worth considering."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
TIME_WAIT Socket Explosion

Creating a large number of short-lived connections causes TIME_WAIT sockets to pile up, leading to port exhaustion. Use a Connection Pool and reuse connections with Keep-Alive. On the server side, consider setting tcp_tw_reuse=1.

❌
Latency Caused by the Nagle Algorithm

The Nagle algorithm, which batches small packets before sending them, causes delays of 200ms or more in real-time communication. For chat, games, and financial transaction systems, disable it with the TCP_NODELAY option.

❌
Zombie Connections from Not Setting Keep-Alive

Even when a client disappears due to a network failure, the server mistakenly believes the connection is still alive. Set SO_KEEPALIVE, and also implement a heartbeat at the application level.

✅
Correct TCP Configuration

Reuse connections with Connection Pool + Keep-Alive. Enable TCP_NODELAY for real-time services. Tune somaxconn and tcp_fin_timeout for high-traffic servers. Always set timeouts and implement graceful shutdown.

🔗 Related Terms

📚 Learn More