Transport Protocols Overview

36
Transport Protocols Transport Protocols Overview Overview

description

Transport Protocols Overview. provide logical communication between app processes running on different hosts transport protocols run in end systems send side: breaks app messages into segments , passes to network layer rcv side: reassembles segments into messages, passes to app layer - PowerPoint PPT Presentation

Transcript of Transport Protocols Overview

Page 1: Transport Protocols Overview

Transport Protocols OverviewTransport Protocols Overview

Page 2: Transport Protocols Overview

Transport services and protocolsTransport services and protocols

provide logical communication between app processes running on different hosts

transport protocols run in end systems send side: breaks app

messages into segments, passes to network layer

rcv side: reassembles segments into messages, passes to app layer

more than one transport protocol available to apps Internet: TCP and UDP

application

transportnetworkdata linkphysical

application

transportnetworkdata linkphysical

networkdata linkphysical

networkdata linkphysical

networkdata linkphysical

networkdata linkphysicalnetwork

data linkphysical

logical end-end transport

Page 3: Transport Protocols Overview

TCP versus UDPTCP versus UDP TCP

connection-oriented reliable byte stream

Application: typically concurrent server SMTP(Simple Mail

Transfer Protocol) Telnet FTP HTTP NNTP(Network News

TP)

UDP connectionless unreliable datagram

Applications: typically iterative server SNMP(Simple Network

Management Protocol) TFTP(Trivial FTP) BOOTP(Bootstrap

Protocol) DHCP(Bootstrap

Protocol)

Page 4: Transport Protocols Overview

TCP OverviewTCP Overview

full duplex data: MSS: maximum segment

size

connection-oriented: flow controlled: point-to-point:

reliable, in-order byte steam: no “message boundaries”

pipelined: TCP congestion and flow

control set window size

send & receive buffers

send() recv()

send() 란 send buffer 에 썼다는 의미이지 ,보냈다는 의미가 아니다 .send() 란 send buffer 에 썼다는 의미이지 ,보냈다는 의미가 아니다 .

Page 5: Transport Protocols Overview

TCP segment structureTCP segment structure

source port # dest port #

32 bits

applicationdata

(variable length)

sequence number

acknowledgement numberReceive window

Urg data pnterchecksum

FSRPAUheadlen

notused

Options (variable length)

URG: urgent data (generally not used)

ACK: ACK #valid

PSH: push data now(generally not used)

RST, SYN, FIN:connection estab(setup, teardown

commands)

# bytes rcvr willingto accept

countingby bytes of data(not segments!)

Internetchecksum

(as in UDP)

Page 6: Transport Protocols Overview

Multiplexing/demultiplexingMultiplexing/demultiplexing

application

transport

network

link

physical

P1 application

transport

network

link

physical

application

transport

network

link

physical

P2P3 P4P1

host 1 host 2 host 3

= process= socket

delivering received segmentsto correct socket

Demultiplexing at rcv host:gathering data from multiplesockets, enveloping data with header (later used for demultiplexing)

Multiplexing at send host:

Page 7: Transport Protocols Overview

Connectionless demux (cont)Connectionless demux (cont)

DatagramSocket serverSocket = new DatagramSocket(6428);

ClientIP:B

P2

client IP: A

P1P1P3

serverIP: C

SP: 6428

DP: 9157

SP: 9157

DP: 6428

SP: 6428

DP: 5775

SP: 5775

DP: 6428

SP provides “return address”

Page 8: Transport Protocols Overview

Connection-oriented demux (cont)Connection-oriented demux (cont)

ClientIP:B

P1

client IP: A

P1P2P4

serverIP: C

SP: 9157

DP: 80

SP: 9157

DP: 80

P5 P6 P3

D-IP:CS-IP: A

D-IP:C

S-IP: B

SP: 5775

DP: 80

D-IP:CS-IP: B

Page 9: Transport Protocols Overview

Sockets IntroductionSockets Introduction

Page 10: Transport Protocols Overview

Protocols and their ImplementationProtocols and their Implementation Protocol Implementation

보통 transport layer 이하 protocol 들은 kernel (OS) 내에 상주한다 . Why?

Link layer 는 H/W 와 이를 컴퓨터에 장착하기 위한 S/W (예 : Ethernet driver) 로 구현된다 .

Application protocol 은 user process ( 즉 , application) 으로 구현된다 .

Client-server model Internet 에서 많은 application

protocol 은 이 model 을 가정하고 있다 .

Server 는 여러 client 의 요청을 동시에 처리할 수 있어야 한다 .

Peer-to-peer model Peer 내에 client 와 server 모두

가지고 있는 model 로 생각할 수 있다 .

S/W

H/W EthernetAdapter

EthernetAdapter

Page 11: Transport Protocols Overview

Socket APISocket API API: Application Program Interface

User process 가 kernel 사이의 interface 를 API 라고 한며 , 흔히 system call 이라고 부른다 .

Function call vs. system call Socket API is an API for communications

가장 널리 쓰이는 Communication API 여러 protocol suite 에 대해 generic API 제공 Transport, network, link layer 의 서비스를 받을 수 있는 API 도 제공

Page 12: Transport Protocols Overview

What is a socket?What is a socket? A handle (or descriptor) to a data structure

Not a pointer! The data structure lives in the kernel. UNIX/LINUX 에서는 socket 도 file 처럼 사용 가능 sockfd = socket(PF_INET, SOCK_STREAM, 0);

user-level library of functions send(sockfd, ...), recv(sockfd, …), …

a single system call via trap (special instruction causing software interrrupt) sys_socketcall(SEND, sockfd, …)

File, device

socket

Page 13: Transport Protocols Overview

Data Structure in Kernel (BSD)Data Structure in Kernel (BSD)

프로세스에서는 handle (descriptor) 로 socket structure 를 찾을 수 있다 .

Socket (file) 에 대해 read, write, select, close 등의 일반적인 file operation 을 socket 특성에 맞게 실행할 수 있다 .

Incoming packet 의 header 를 보고 해당되는 socket 을 찾을 수 있다 . TCP: (local addr, local port,

foreign addr, foreign port) Connected UDP socket 인

경우에도 해당

UDP: (local addr, local port)

UDP socket creationsockfd=socket(PF_INET, SOCK_DGRAM, 0);

sockfd

Page 14: Transport Protocols Overview

Transport Protocol

Sending and Receiving via SocketSending and Receiving via Socket

Address family

Local addr Foreign addr

Local port Foreign port

Recv bufferRecv buffer Send bufferSend buffer

Client App

Server App

Transport Protocol

Address family

Local addr Foreign addr

Local port Foreign port

Recv bufferRecv buffer Send bufferSend buffer

Socket API(Operations)

A TCP connection

Socketdescriptor

Page 15: Transport Protocols Overview

Socket Address StructuresSocket Address Structures

Page 16: Transport Protocols Overview

IPv4 SA structure

Generic SA structure SA structure 의 pointer 를 casting 할 때만 사용

IPv4 Socket Address StructureIPv4 Socket Address Structure SA structure itself are

used only on a given host, not used for communication

POSIX datatypes

always set to 0

Page 17: Transport Protocols Overview

Elementary Elementary Sockets APISockets API

Page 18: Transport Protocols Overview

TCP Client-Server Procedure TCP Client-Server Procedure 12.106.32.254192.168.42.1

206.168.112.219203.253.70.44

foreignlocal

????

foreignlocal

21150012.106.32.254206.168.112.219

foreignlocal

?21?0

foreignlocal

?21?0

foreignlocal

150021206.168.112.21912.106.32.254

Listening socket (=3)

Connected socket (=4)

FIN

TCP segment

foreignlocal

????

INADDR_ANY

Page 19: Transport Protocols Overview

socket(): Create a Socketsocket(): Create a Socket

Socket descriptor is a file descriptor in UNIX systems, but is not a file descriptor in Windows

field local foreign

addr ? ?

port ? ?

TCP socket

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */SOCKET socket (int family, int type, int protocol);Returns: socket descriptor on success, -1 (UNIX) or INVALID_SOCKET (Windows) on failure

Page 20: Transport Protocols Overview

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int connect (SOCKET s, const struct sockaddr *peer, int peer_len);Returns: 0 on success, -1 (UNIX) or nonzero (Windows) on failure

connect(): Establish the Connectionconnect(): Establish the Connection

Kernel 은 미사용 중인 port 번호를 택하고 , forwarding table을 loopkup 하여 peer 로 전송할 interface 의 IP address 를 source(local) IP 주소로 결정한다 .

3-way handshake Error 가 발생한 이유

extern int errno; /* UNIX */ GetLastError(); /* Windows */ No response to SYN: connection timeout (ETIMEDOUT)

다시 3 번 retry 후 , 총 75 초 지나면 error return Response is RST: no such server process (ECONNREFUSED) Receive ICMP unreachable error message: host unreachable

(EHOSTUNREACH or ENETUNREACH) connection 이 실패하면 , socket 은 더 이상 사용할 수 없으므로

close() 해야 한다 .

field local foreign

addr 206.168.112.219 12.106.32.254

port 1500 13

TCP socket - client

Page 21: Transport Protocols Overview

Send: Put the message (of length len in buf) into the TCP(socket) send buffer

Blocked if not enough space in TCP send buffer

Recv: Get a message(<= bufsize) from the TCP(socket) receive buffer

Blocked until TCP receive buffer becomes non-empty

n-byte message 를 send()했다고 해서 , 수신측에서 recv() 할 때 n-byte 를 받는 게 아니다 .

send(), recv(): TCP Data Transmissionsend(), recv(): TCP Data Transmission

field local foreign

addr 206.168.112.219 12.106.32.254

port 1500 13

TCP socket - client

field local foreign

addr 12.106.32.254 206.168.112.219

port 13 1500

TCP connected socket - server

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int recv (SOCKET s, void *buf, size_t bufsize, int flags);int read (SOCKET s, void *buf, size_t bufsize); /* UNIX */Returns: # of bytes read (>0), 0 if received FIN and no more data, -1 on failure

int send (SOCKET s, const void *buf, size_t len, int flags);int write (SOCKET s, const void *buf, size_t len); /* UNIX */Returns: # of bytes transferred on success, -1 on failure

Page 22: Transport Protocols Overview

bind(): Set My Addressbind(): Set My Address

If port # = 0, the kernel chooses a port (ephemeral port) If wildcard address(INADDR_ANY), the kernel chooses IP addr

Example: IPv4struct sockaddr_in servaddr;sockfd = socket(AF_INET, SOCK_STREAM, 0);bzero(&servaddr, sizeof(servaddr));seraddr.sin_family = AF_INET;seraddr.sin_addr.s_addr = htonl(INADDR_ANY);/* wild card */seraddr.sin_port = htons(13); /* Daytime server */bind(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

Example: IPv6struct sockaddr_in6 servaddr;seraddr.sin6_addr.s_addr =in6addr_any; /* wild card */

TCP listening socket - serverfield local foreign

addr * (0) ?

port 13 ?

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int bind (SOCKET s, const struct sockaddr *myaddr, int addrlen);Returns: 0 on success, -1 (UNIX) or SOCKET_ERROR (Windows) on error

Page 23: Transport Protocols Overview

listen(): Convert to the Listening Socketlisten(): Convert to the Listening Socket

Listening socket: connection request 를 accept 할 수 있는 socket 동시에 여러 개의 3-way handshaking 할 수 있게 queue 가 필요함 Queue size 는 backlog( 보통 5) 로 정의

참고 : backlog 의 수는 실제 queue size 와 일치하지 않고 , OS 마다 다르다 .

Data 를 송수신 할 수 없음 TCP state transition: CLOSED LISTEN TCP listening socket - server

field local foreign

addr * (0) ?

port 13 ?

queue

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int listen (SOCKET s, int backlog);Returns: 0 on success, -1 (UNIX) or SOCKET_ERROR (Windows) on error

Page 24: Transport Protocols Overview

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */SOCKET accept (SOCKET s, struct sockaddr *cliaddr, int *addrlen);Returns: a connected socket on success, -1 (UNIX) or INVALID_SOCKET (Windows) on failure

accept(): Accept a Connection Request accept(): Accept a Connection Request and create the Connected Socketand create the Connected Socket

field local foreign

addr * (0) ?

port 13 ?

blocked if the completed connection queue is empty

If the identity of client is not interested, use NULL pointer instead of cliaddr, addrlen

field local foreign

addr 12.106.32.254 206.168.112.219

port 13 1500

TCP listening socket - server

TCP connected socket - server

Page 25: Transport Protocols Overview

close(): close the socket and terminate the close(): close the socket and terminate the TCP connection if no more usedTCP connection if no more used

Socket send buffer 에 data 가 남아 있으면 보낸다 Reference_count-- 만일 , 이 socket 을 다른 프로세스와 공유하고 있다면 (if reference_count >

0), return 독점 사용하고 있다면 (if reference_count == o), 정상적인 TCP connection

termination (graceful termination) 이 이루어진다 . 즉 , FIN, ACK 를 교환한다 . Close 되면 , 더 이상 send/recv 불가능

#include <unistd.h> /* UNIX */#include <winsock2.h> /* Windows */int close (SOCKET s); /* UNIX */int closesocket (SOCKET s); /* Windows */Returns: 0 on success, -1 on error

Client 가 server 에게 request 를 모두 보냈다고 알리고 싶다 . ( 즉 , FIN을 보내고 싶다 .) 그러나 , server 로 부터의 response는 계속 도착할 것이고 , 이를 recv()해야 한다 . 방법은 ?

Page 26: Transport Protocols Overview

close close versusversus shutdown shutdown Close

decrease reference count close the socket only if count == 0 terminates both directions of data

transfer: reading and writing Cannot read after close

Shutdown initiate TCP’s normal termination

regardless of reference count terminates one direction (half of

connection)

SHUT_RD (SD_RECEIVE, Windows): read-half of the connection is closed Any data currently in socket receive buffer is discarded Any data received after this call is acknowledged and then silently discarded

SHUT_WR (SD_SEND, Windows): write-half of the connection is closed(half-close) Any data currently in socket send buffer will be sent

SHUT_RDWR (SD_BOTH, Windows): read-half and write-half of connection are both closed SHUT_RD + SHUT_WR

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int shutdown (SOCKET s, int howto);Returns: 0 on success, -1 on error

Page 27: Transport Protocols Overview

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int getsockname (SOCKET s, struct sockaddr *localaddr, int *addrlen);int getpeername (SOCKET s, struct sockaddr *peeraddr, int *addrlen);Returns: 0on success, -1 on error

Finding Protocol Addresses from socketsFinding Protocol Addresses from sockets

When is getsockname function required ? client 가 connect 후 자신의 IP

addr/port # 를 알고자 할 때 0 인 port # 로 bind 한 후 assign

된 local port # 를 알고자 할 때 socket 의 address family 를

알고자 할 때 server 가 wildcard IP addr 를

bind 하여 connection 이 이루어진 후 (accept 가 return 된 후 ) local IP addr 를 알고자 할 때

When is getpeername function required ? server 가 accept 후 child

process 가 fork 되고 exec되면 client 를 알 수 없음 (예 , inetd)

field local foreign

addr 206.168.112.219 12.106.32.254

port 1500 13

Page 28: Transport Protocols Overview

#include <sys/socket.h> /* UNIX */#include <winsock2.h> /* Windows */int recvfrom (SOCKET s, void *buf, size_t bufsize, int flags,

struct sockaddr *from, int *fromlen);int sendto (SOCKET s, const void *buf, size_t len, int flags,

const struct sockaddr *to, int tolen);Returns: datagram length on success, -1 on failure

UDP Datagram TransmissionUDP Datagram Transmission

No connection is needed. Recvfrom: 메시지를 recv 하고 송신자 (from) 확인

If 0 returns : datagram of length 0 (???) If no interest in senders address

from : NULL, addrlen : NULL Recv 할 때 마다 송신자가 다를 수 있다 .

Sendto: 메시지를 수신자 (to) 에게 send Send 할 때 마다 수신자가 다를 수 있다 .

Page 29: Transport Protocols Overview

May Lost via UDP Socket Comm.May Lost via UDP Socket Comm. Lost datagram due to

lost in network socket receive buffer overflow

UDP has no flow control

Lost 되지 않았다면 , UDP 를 통한 송수신시 message 경계가 유지된다 . 송신한 메시지는 크기가 유지된 채로 수신된다 . 예외적으로 , 수신된 메지지가 짤릴 수 있다 .

(truncated) 수신된 메시지에 비트에러가 있을 수 있다 .

Page 30: Transport Protocols Overview

Connected UDP SocketConnected UDP Socket Call connect only to communication with exactly one peer

Kernel just records IP address and port # of the peer Connected UDP socket

No need to specify the destination IP addr and port # for output operation write, send instead of sendto

No need to verify received response read, recv instead of recvfrom

Asynchronous errors are returned Connected UDP socket provides better performance

Unconnected UDP socket: make a temporary connection(1/3 overhead) May connect multiple times for a UDP socket by specifying a new IP

addr and port #

하나의 지정된 상대와 UDP 통신할 때는TCP 처럼 connect() 하여 send(), recv()하는 편이 좋다 .

Page 31: Transport Protocols Overview

Miscellaneous FunctionsMiscellaneous Functions

Page 32: Transport Protocols Overview

Value-Result ArgumentsValue-Result Arguments

SA structure are always passed by reference

process to kernel: bind, connect, sendto

kernel to process: accept, recvfrom, getsockname,getpeername

struct sockaddrstruct sockaddr

Page 33: Transport Protocols Overview

Byte OrderingByte Ordering

Host Byte Order Network Byte Order

프로토콜에서 그대로 header 에 싣을 수 있도록Network address 와 port 는 항상 network byte order 로 저장되어야 한다 .그러나 , 컴퓨터 종류에 따라 byte 저장 순서가 다를 수 있다 .

0000 0001 0000 0010

0000 0001 0000 0010

un.c[0]

un.c[0]

un.c[1]

un.c[1]

Page 34: Transport Protocols Overview

Byte Manipulation FunctionsByte Manipulation Functions

4.3BSD

ANSI C: a = b; style !!

Page 35: Transport Protocols Overview

IPv4 Address ConversionIPv4 Address Conversion Functions only for IPv4, not for IPv6 Dotted decimal(a string) 32-bit IP address

What about 255.255.255.255?

32-bit IP address Dotted decimal

Not reentrant, not thread-safe Function 내부에서 결과를 저장할 공간을 static memory 로 잡아서 ,

function call 때 마다 같은 영역을 쓰기 때문

Page 36: Transport Protocols Overview

IPv4/IPv6 Address ConversionIPv4/IPv6 Address Conversion Functions for IPv6: work with both IPv6 and IPv4