Chap. 6) Berkeley Sockets

Process-to-Process Communication

Introduction to Transport Layer

▪ How "data" are transferred? packet switching ⇔ circuit switching (physical

ex)	p.205 fig.5-4,	p.208 fig.5-6,	p.208 fig.5-7	connection)

▪ Socket: APIs(Application Program Interfaces) to the TCP/IP S/W.

ex)	p.260 fig.6-1

p.261 fig.6-2: TCP(connection-oriented protocol - virtual connection)

p.262 fig.6-3: UDP(connectionless protocol - datagram)

packet switching의 두가지 방법

⇒ Application programmers can "choose" whichever service is more appropriate for their specific applications.

ex) p.205 fig5-5

⇒ 어떠한 통신방법을 사용할 것인가? protocol

누구와 통신할 것인가? IP address(host) and port no.(process)

Packet Switching Technique

▪ Computer Network: IP Network

Network Layer

- host-host comm.

① Routing

② Congestion Control

③ Internetworking

S

S

R

R

R

R

R

R

R

S

R

S

KNUE

leased line

NSFNet

U. C. at

Berkeley

U. C. at

L. A.

210.93.99.60

211.34.193.6

KREN

(서울대)

KORNet

(KT)

▪ History

- Developed for long-distance digital "data" comm. in the early 70's.

⇒ Computer network에서 digital data의 전달 방식.

▪ Virtual Circuit

- A 'preplaned' route is established before any packets are sent by sending a "special control" packet, a Call Request Packet.

⇒ A routing decision is made only "once".

- Once the 'logical connection' (virtual circuit) is set up, all packets follow that route.

⇒ All packets for that virtual circuit follow the same route and arrive "in sequence"

(ex) p.283 fig.8-4 (a) (Stallings 4th ed.)

- Characteristics

․ Appropriate for "long" duration of transmission.

․ Packets arrive in the "original" order.

▪ Datagram

- Each packet is routed "independently".

- The packets, each with the same dest. addr., may NOT follow the same route.

(ex) p.283 fig.8-4 (b) (Stallings 4th ed.)

- Characteristics

․ If 'congestion' develops in one part of the network, incoming datagrams can be routed "away" from the congestion.

⇒ "Adaptive"

▪ Two methods

① Virtual circuit: Connection-oriented service

② Datagram: Connectionless service

e.g., http://en.wikipedia.org/wiki/Virtual_circuit

- ‘Virtual circuit’ communication resembles ‘circuit switching’

⇒ Both are connection oriented, meaning that in both cases data is delivered 'in correct order', and 'signalling overhead' is required during a connection establishment phase.

① 'Layer 2/3' VC: Data Link/Network Layer에서 VC를 제공

Frame Relay (http://en.wikipedia.org/wiki/Frame_Relay)

ATM (http://en.wikipedia.org/wiki/Asynchronous_Transfer_Mode)

⇒ However, because of the large market of IP routers, and because 'advanced' IP routers support layer 3 switching, modern IP routers may today be faster than switches for connection oriented protocols.

② 'Layer 4' VC: Transport Layer(e.g. TCP)의 '종단' 간에서 VC를 제공

(Layer 3 IP: datagram 방식이기 때문)

⇒ Connection oriented transport layer datalink protocols such as TCP may rely on a connectionless packet switching network layer protocol such as IP.

⇒ Different packets may be routed over different paths, and thus be delivered out of order.

⇒ However, a virtual circuit is possible since TCP includes 'segment numbering' and 'reordering' on the receiver side to prevent out-of-order delivery.

Protocols: TCP and UDP

▪ Connection-oriented transfer: TCP

- First, the server (process) is started, then, sometime later a client (process) is started and establish a connection with a server by using a 'three-way handshake'.

ex) 전화.

- TCP 제공 service: "Reliable" data delivery service with end-to-end error detection and correction.

ex) smtp, ftp, telnet, pop(post office protocol) 등의 application들이 이용. (in /etc/services)

▪ Connectionless transfer: UDP

- The client does NOT establish a connection with the server and the server does NOT have to accept a connection from a client.

ex) 편지, 전보

- UDP 제공 service: The client just sends a "datagram" to the server on which the address of the server is written.

- NO error detection and correction.

⇒ "Unreliable" datagram delivery service.

- 짧고 간단한 message를 보내는데 사용.

ex) ping, echo, talk 등의 application들이 이용. (in /etc/services)

▪ Why UDP?

- 특징:	① NO three-way handshake for establishing a connection.

② NO error detection and correction for each packet exchanged.

⇒ 'Low' communication overhead.

0 15	16 31
source port no.	destination port no.
length	checksum(CRC)-opt.
～ data ～

- UDP header: simple

- If the amount of data is "small", the overhead of ①(creating a connection) and ②(ensuring reliable delivery) may be greater than the work of "retransmitting" the entire data set.

⇒ UDP의 경우, ACK를 수행하지 않음.

- Connectionless : TCP는 서로 통신을 하기 전에 상대방을 확인하는 절차를 가짐으로써, connection을 맺는 작업을 하며, 연결된 connection을 통해서 데이타의 흐름이 이루어진다. 그러나 UDP 는 이러한 connection을 만들기 위한 작업을 하지 않고, 그냥 보내고 받기만 한다.

⇒ 사용자가 UDP 서비스를 하는 서버로 메시지를 보냈다고 하더라도, 메시지가 실제로 도착되었는지는 알 수 없다. 데이타는 보내질 수도 있고 그렇지 않을 수도 있다.

- Unreliable : UDP는 신뢰성 보장을 위한 어떠한 장치를 가지고 있지 않다. UDP로 전송된 패킷은 순서가 뒤바뀔 수도 있으며, 중간에 패킷이 손실될 수도 있다. ‘프로토콜’ 차원에서 패킷의 순서가 뒤바뀌었는지, 패킷이 손실되었는지 알 수 있는 방법은 없다.

⇒ UDP 패킷에 신뢰성을 주기 위해서는 ‘application 차원’에서 직접 코딩을 해주어야만 한다. (보통은 패킷을 만들때 데이타 헤더를 따로 만들어서 일련번호등을 넣어서 서버측에 보내고, 서버측에서는 이에 대한 응답을 보내는 방식을 이용하여 UDP 패킷에 신뢰성을 부여할 수 있다.)

- 상당히 많은 패킷이 오가면서, 별로 중요하지 않은 ‘몇 개의 데이타 손실’ 정도는 허용될 수 있는 곳에 사용

⇒ 모든 서비스에 TCP를 사용하기에는 TCP는 너무 느린 감이 있다.

e.g., 음성 및 비디오를 위한 실시간 streaming 서비스의 경우

⇒ 음성서비스를 TCP로 서비스할 경우의 문제점은 패킷이 중간에 빠질 경우 빠진 패킷에 대한 재전송을 요청하므로 음성서비스가 중단되어버린다.

⇒ 전화를 할때 중간에 약간의 잡음이 생겼다고 해서, 전화가 중단되는 것과 마찬가지의 상황이므로 ‘약간의 잡음’을 교정하느라고 서비스가 중단되는 것 보다는 잡음이 약간 허용되어라도 계속적으로 서비스가 되는 것이 더 낫다.

⇒ ‘통신품질’보다는 통신의 ‘연속성’이 더욱 중요시 되는 곳에 유용하게 사용될 수 있다. 물론 TCP로도 구현할 수 있으며, 상당수의 서비스가 TCP로 서비스 된다.

e.g., 게임을 할때 서로 교환되는 수많은 패킷의 경우 매우 중요한 데이타가 아니므로, 그리고 게임의 흐름이 끊기면 안되므로 UDP로 처리되는게 더 유리

▪ Why TCP?

- 특징: protocol에서 communication 품질 service들 제공

① Three-way handshake for establishing a connection.

② Error detection and correction for each packet exchanged.

⇒ ‘High’ communication overhead for ‘reliable’ data transfer.

- TCP header: complicate

0 15			16 31
source port no.			destination port no.
seq. no.
ack. no.
header len.	resv.	flags	window
checksum(CRC)			urgent pointer
options
～ data ～

- TCP provides

① connection: a logical end-to-end connection between two TCP modules.

⇒ 3-way handshake

․ ‘3 segments’ are exchanged.

(segment: the unit of data exchanged bet. cooperating TCP modules)

․ flags used:

U  A  E  R  S  F

R  C  O  S  Y  I

G  K  M  T  N  N

ⓐ The ACK bit:

0: Indicate that the piggyback ack. no. field is NOT in use.

1: Indicate that ACK is sent.

ⓑ The SYN bit: Indicate that a 'connection' is establishing.

The connection 'request' has SYN=1 and ACK=0.

The connection 'reply' has SYN=1 and ACK=1.

ⓒ The FIN bit: Used to release a connection.

⇒ Indicate that the sender has NO more data.

ⓓ The RST bit: Used to reset a connection.

ⓔ The EOM bit: Used to indicate the end of message.

ⓕ The URG bit: Used for urgent pointer.

Host A's TCP		Host B's TCP
SYN=1, ACK=0, seq. no.=0, (ISN - initial seq. no., usually 0) NO data	①	(B knows A's request and what seq. no. A will use as a starting no. for its segment)
(A knows B is 'alive' and what seq. no. B will start with.)	②	SYN=1, ACK=1, seq. no.=0, NO data (B's segment acknowledges the receipt of A's segment.)
ACK=1, seq. no.=1, data (the first real byte of data sent is ISN+1 (usually 1).)	③	"data transfer has begun."

② reliability: PAR(Positive Acknowledgement with Retransmission)

․ If the data is received "undamaged" (by checking the CRC checksum), the receiver send an ACK back to the sender.

․ If the data is received "damaged", the receiver 'discards' it.

⇒ After an appropriate time-out period, the sending TCP module "retransmits" any segment for which no ACK has been received. (ARQ)

③ a continuous stream of bytes.

⇒ Each byte is numbered 'sequentially' starting from the ISN.

․ TCP maintain the 'sequence' using the seq. no. and ack. no. field between the sender and receiver.

⇒ The seq. no. field identifies the sequential position in the data stream of the "first" data byte in the segment.

⇒ The ack. no. field is the seg. no. of the "last" byte received.

1 4000	4001 6000
1st segment	2nd segment

ex)

the sender set the seq. no. field
	1		4001
			1000

the receiver set the ack. no. and window field
	1		1001
	4000		6000

1 1000	1001 3000
1st segment	2nd segment

④ flow control

⇒  The 'window' field contains the no. of bytes the receiver is able to accept.

ⓐ The sender can continue sending segments as long as

the total no. of bytes it sends〈 the window size

ⓑ The receiver "controls" the flow of bytes by changing the size of the window.

ex) window size = 0 ;	the receiver's buffer is 'full'.

⇒ The sender must "cease" transmission until it receives a non-zero window value.

▪ Summary

http://www.stanford.edu/class/cs193i/handouts2003/05Networking2.pdf

e.g., # netstat -s    ; 사용가능한 프로토콜들에 대한 통계정보 확인

(# netstat  ; 네트워크 상태를 종합적으로 확인하는 명령어)

Port No.

▪ How a client process contacts to a server process?

⇒ 16-bit port no.

⇒ client process가 '요청하는 service'를 담당하는 server process에 연결할 때 사용.

▪ On Unix/Linux, port no.s are defined in /etc/services.

ex) # more /etc/services

ftp	21/tcp

telnet	23/tcp

smtp	25/tcp

……

talk	517/udp

ex) httpd (Apache Web Server)의 default port no.: 80 (httpd.conf)

▪ Two kinds

- well-known port no.: 특정 system application에 assign됨.

1 ～ 255: reserved for well-known processes.

ex) ftp:21, telnet:23, smtp:25, pop:110 등.

256 ～ 1023: reserved for superuser processes in 4.3 BSD.

ex) talk:517, uucp:540 등.

⇒ 'System' service

- ephemeral port no.: short-lived for user processes.	1024 ～

⇒ 'User' service

▪ The TCP ports are independent of the UDP ports.

ex) TCP port 1035 ≠ UDP port 1035

▪ The 5-tuple is needed for the Internet communication.

{the protocol, the client's IP addr., the client's port no.,

the server's IP addr., the server's port no.}

⇒ the combination of an IP addr. and a port no. is stored in a "socket"

⇒ "unique" within the entire Internet.

⇒ socket() & bind()

ex)	For a ftp service from a client to a server,

client

TCP socket { 203.247.208.60, 1350, 134.75.204.2, 21 }

server

⇔	{ 203.247.208.60, 1350, 134.75.204.2, 21 } TCP socket

; this info. is needed for both the sender and the receiver.

For 'another' ftp connection,

TCP socket { 203.247.208.60, '1351', 134.75.204.2, 21 }

⇒ this 5-tuple is different from the above.

ex) p.210 fig.5-9, p.210 fig.5-10.

ex) How a ‘ftp service’ is performed?

PID=2001

PID=2031

PID=126

e.g., # netstat -a    ; 현재 생성된 소켓 연결들 확인

e.g., # netstat -a    ; Windows (http 등 확인, -an: port no.로 표시)

e.g., # netstat -o    ; 각 연결의 소유자 process ID 표시

Ex) How a HTTP service is performed?

① URL을 사용하여 service를 request.

Web browser	Web server

http://server:port/***.html

② TCP 'connection' 설정.

Web browser	Web server

A TCP connection is established

③ Web Server로부터 해당 ***.html 파일 전송 후 connection 끊어짐.

⇒ ‘Stateless’ protocol

⇒ 'Session' is NOT provided.

⇒ Session ‘ID’를 사용함으로써 웹사이트에 로그인 후 페이지들 방문시마다 매번 로그인하지 않아도 되는 편리함 제공.

▪ Protocol no.s are defined in /etc/protocols.

ex) # more /etc/protocols

ip	0	IP

……

tcp	6	TCP

udp	17	UDP

	6		protocol
203.247.208.60			source IP addr.
134.75.204.2			dest. IP addr.
1350		21	source port no.
			dest. port no.

ex) How the server knows what to do, if data arrived?

IP

IP

address 203.247.208.60

address 134.75.204.2

TCP

UDP

protocol 6

port 21

TCP header

fork& exec

IP header

inetd

ftpd

Overview of Berkeley Sockets

▪ Socket: APIs(Application Program Interfaces) to the TCP/IP S/W.

ex)	p.260 fig.6-1, p.261 fig.6-2,	p.262 fig.6-3

▪ Unix domain protocols

- Sockets in the Unix domain can only be used to communicate with the processes on the "same" Unix machine.

⇒ Not network communication.

- They are a form of IPC in one machine, but their implementation has been built into the 4.3 BSD networking system in the same fashion as other "true" communication protocols.

Socket Addresses

▪ Socket system call을 사용하기 위해서는 '4가지' header file이 필요.

① Protocol-independent addr. structure: generic structure. (일반적인 틀)

Defined in <sys/socket.h>

struct sockaddr{

u_short sa_family;	/* sa: socket addr. */

char	sa_data[14];

	2 bytes
0
1
2
3
4
5
6
7

};

ex) p.264

② Protocol-specific addr. structure

- For Internet: Defined in <netinet/in.h>

struct in_addr{

u_long s_addr;

};

struct sockaddr_in{

short	sin_family;      /* family: AF_INET, AF_NS, AF_UNIX */

u_short	sin_port;	/* port no.: 16 bit - 2 bytes	*/

struct in_addr   sin_addr;	/* IP addr.: 32 bit - 4 bytes */

char	sin_zero[8];	/* unused       - 8 bytes	*/

};

ex) p.285 ～ p.286: client - contact하고자 하는 server의 port no. & IP addr.

server - contact를 기다리는 server의 port no. & IP addr.

- For Xerox NS: <netns/ns.h>

- For Unix domain protocol: <sys/un.h>

ex) p.264, p.266 fig.6-5

- Why ‘two addr. structures’ are needed?

․ Socket system calls (connect(), bind() 등) are “generic”.

⇒ system call들이 개개의 protocol에서 독립되도록, protocol-specific한 인수(sockaddr_in, sockaddr_ns, sockaddr_un)들을 generic한 형태(sockaddr)로 형변환(casting)해서 받음.

⇒ The network system calls take two arguments: the addr. of the "generic" sockaddr structure and the "size" of the actual protocol-specific structure.

ex)  struct sockaddr_in	serv_addr;

"casting the protocol-specific

……	structure into the generic structure"

connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

generic type	Internet-specific type

c.f.) p.58 fig2-5: execlp. execvp, execl, execv, execle, execve

⇒ 같은 system call들이 argument가 다르므로 각각 다른 함수로 존재.

③ <sys/types.h>

- Provides C definitions and data type definitions that are used throughout the system.

ex) p.264 fig.6-4

④ <arpa/inet.h>

- address conversion routine에서 필요.

ex)

char. string:	"134.75.204.2"

inet_addr()	inet_ntoa()

32-bit integer: 10000110 01001011 11001100 00000010

ex) p.284 "inet.h"