unix network programming1 unix network programming 2nd edition

32
UNIX Network Programming 1 UNIX Network UNIX Network Programming Programming 2nd Edition 2nd Edition

Upload: shanna-watkins

Post on 27-Dec-2015

292 views

Category:

Documents


3 download

TRANSCRIPT

UNIX Network Programming 1

UNIX Network ProgrammingUNIX Network Programming2nd Edition2nd Edition

UNIX Network Programming 2

Chapter 1. IntroductionChapter 1. Introduction

• Contents

– Introduction

– A Simple Daytime Client

– Error Handling: Wrapper Functions

– A Simple Daytime Server

– OSI Model

– Unix Standards

UNIX Network Programming 3

1.1 Introduction1.1 Introduction

• Client / Server

Client ServerCommunication link

Figure 1.1 Network application : client and server

Client

Client

Client

Server...

...

Figure 1.2 Server handling multiple clients at the same time.

UNIX Network Programming 4

1.1 Introduction 1.1 Introduction (continued)(continued)

• Example : Client and Server on the same Ethernet communication using TCP

WebClient

TCP

IP

Ethernetdriver

Webserver

TCP

IP

Ethernetdriver

TCP protocol

Application protocol

IP protocol

Ethernet protocol

Actual flow between client and server

Ethernet

Application layer

transport layer

network layer

datalink layer

User

process

Protocol stack

within kernel

Figure 1.3 Client and server on the same Ethernet communicating using TCP

UNIX Network Programming 5

1.1 Introduction 1.1 Introduction (continued)(continued)

• Example : Client and Server on different LANs connected through WAN.

clientapplication

Hostwith

TCP/IP

serverapplication

Hostwith

TCP/IP

router

router router router

router

router

LAN LAN

WAN

Figure 1.4 Client and server on different LANs connected through a WAN

UNIX Network Programming 6

1.2 A Simple Daytime Client1.2 A Simple Daytime Client#include “unp.h”

intmain (int argc, char **argv){

int sockfd, n;char recvline[MAXLINE+1];struct sockaddr_in servaddr;

if ( argc != 2) err_quit(“usage: a.out <IPaddress>”);

if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)err_sys(“socket error”);

bzero( &servaddr, sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_port = htons(13); /* daytime server */if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0)err_quit(“inet_pton error for %s”,argv[1]);

if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)err_sys(“connect error”);

while ( (n = read(sockfd, recvline, MAXLINE)) > 0 ) {recvline[n] = 0; /* null termicate */if ( fputs(recvline, stdout) == EOF)err_sys(“fputs error”);}if ( n < 0 ) err_sys ( “read error “);

exit(0);}

1

2

3

4

5

UNIX Network Programming 7

• #include "unp.h"

• int main(int argc, char **argv)

• {

• int sockfd, n;

• struct sockaddr_in6 servaddr;

• char recvline[MAXLINE + 1];

• if (argc != 2) err_quit("usage: a.out <IPaddress>");

• if ( (sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)

• err_sys("socket error");

• bzero(&servaddr, sizeof(servaddr));

• servaddr.sin6_family = AF_INET6;

• servaddr.sin6_port = htons(13); /* daytime server */

• if (inet_pton(AF_INET6, argv[1], &servaddr.sin6_addr) <= 0)

• err_quit("inet_pton error for %s", argv[1]);

• if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)

• err_sys("connect error");

• while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {

• recvline[n] = 0; /* null terminate */

• if (fputs(recvline, stdout) == EOF)

• err_sys("fputs error");

• }

• if (n < 0)

• err_sys("read error");

• exit(0);

• }

1.3 protocol Independence1.3 protocol Independence

UNIX Network Programming 8

1.4 Error Handling: Wrapper Functions1.4 Error Handling: Wrapper Functions

• Since terminating on an error is the common case, we can shorten our program by defining a wrapper function that performs the actual function call, tests the return value, and terminates on an error.

• sockfd = Socket(AF_INET, SOCK_STREAM, 0);

int

Socket(int family, int type, int protocol)

{

int n;

if( (n = socket( family, type, protocol)) < 0 )

err_sys(“socket error”);

return (n);

}

• Unix errno Value

Figure 1.7 Our wrapper function for the socket function

UNIX Network Programming 9

1.5 A Simple Daytime Server1.5 A Simple Daytime Server#include “unp.h”#include <time.h>

intmain(int argc, char **argv){

int listenfd, connfd;struct sockaddr_in servaddr;char buff[MAXLINE];time_t ticks;

listenfd = Socket(AF_INET, SOCK_STREAM, 0);

bzero(&servaddr, sizeof(servaddr));servaddr.sin_family = AF_INET;servaddr.sin_addr.s_addr = htonl(INADDR_ANY);servaddr.sin_port = htons(13); /* daytime server */

Bind(listenfd, (SA *) *servaddr, sizeof(servaddr) );

Listen(listenfd, LISTENQ);

for( ; ; ) {connfd = Accept(listenfd, (SA *) NULL, NULL) ;

ticks = time(NULL);snprintf(buff, sizeof(buff), “%.24s\r\n”, ctime(&ticks) );Write(connfd, buff, strlen(buff) );

Close(connfd);}

}

1

2

3

4

UNIX Network Programming 10

1.7 OSI Model1.7 OSI Model

– Why do both sockets and XTI provide the interface from the upper three layers of the OSI model into the transport layer?

• First, the upper three layers handle all the details of the application and The lower four layers handle all the communication details.

• Second, the upper three layers is called a user process while the lower four layers are provided as part of the operating system kernel.

Application

SessionPresentation

TransportNetworkDatalinkPhysical

7

6

5

4

3

2

1

OSI Model

Application

TCP | | UDPIPv4, IPv6

Device driverand Hardware

Internet protocol suite

SocketsXTI

userprocess

kernel

applicationdetails

communicationdetails

Figure 1.14 Layers on OSI model and Internet protocol suite

UNIX Network Programming 11

1.10 Unix Standards1.10 Unix Standards

• POSIX

– Potable Operating System Interface

– a family of standards being developed by IEEE

• The Open Group

– an international consortium of vendors and end-user customers from industry, government, and academia.

• IETF (Internet Engineering Task Force)

– a large open international community of network designers, operators, vendors, and researchers concerned with the evolution of the Internet architecture and the smooth operation of the internet.

UNIX Network Programming 12

Chapter 2. The Transport Layer :Chapter 2. The Transport Layer : TCP and UDP TCP and UDP

• Contents

– Introduction

– The Big Picture

– UDP: User Datagram Protocol

– TCP: Transmission Control Protocol

– TCP Connection Establishment and Termination

– TIME_WAIT State

– Port Numbers

– TCP Port Numbers and Concurrent Servers

– Buffer Sizes and Limitations

UNIX Network Programming 13

2.1 Introduction2.1 Introduction

• Overview of the TCP / IP protocol

• Transport layer : TCP & UDP

UNIX Network Programming 14

2.2 The Big Picture2.2 The Big Picture

m-routed

pingtcp-dump

appl.appl.appl.appl.trace-route

pingtrace-route

TC P U DP

IC M P

IG M P IP v4

ARP ,RARP

IP v6IC M P v

6

data-link

B P F ,DLP I

IP v4 applic ationAF _IN E T

soc kaddr_in{ }

IP v6 applic ationAF _IN E T6

soc kaddr_in6{ }

AP I

128- bitaddresses

32- bitaddresses

F igure 2.1 O verview o f TC P / IP pro toc o ls

UNIX Network Programming 15

2.3 UDP : User Datagram Protocol2.3 UDP : User Datagram Protocol

• The application writes a datagram to a UDP socket, which is encapsulated as either a IPv4 of a IPv6 datagram, which is sent to its destination.

• UDP provides a connectionless service.

• Each UDP datagram has a length and we can consider a datagram as a record.

• RFC 768[Postel 1980]

UNIX Network Programming 16

2.4 TCP: Transmission Control Protocol2.4 TCP: Transmission Control Protocol

• Provides connections between clients and servers.

• Provides reliability.– RTT ( round-trip-time)

• TCP also sequences the data by associating a sequence number with every byte that it sends.

• TCP provides flow control.

– window

• A TCP connection is also full-duplex.

UNIX Network Programming 17

2.5 TCP 2.5 TCP Connection Establishment and TerminationConnection Establishment and Termination

• Three-Way Handshake

• SYN segment

• ACK

c lient serversocket,bind,listen

accpet(b locks)socketconnect(b locks)

(ac tion open)

connect returns

accept returnsread(b locks)

F igure 2.2 TC P three- way handshake

UNIX Network Programming 18

TCP HeaderTCP Header

16- bit source port number 16- bit destination port number

32- bit sequence number

32- bit acknowledgment number

16- bit window s ize4- bit header

lengthreserved

(6bit)

16- bit TC P checksum 16- bit urgent po inter

option ( if any)

data ( if any)

FIN

SYN

RST

PSH

ACK

URG

0 15 16 32

20 bytes

TC P H eader

UNIX Network Programming 19

EncapsulationEncapsulation

application

TC P

IP

E thernetdriver

user data

user dataAppl

header

application data

application data

application data

TC Pheader

TC Pheader

TC Pheader

IPheader

IPheader

E thernetheader

E thernettrailer

TC P segment

IP datagram

E thernet frame

46 to 1500 bytes

E thernet14 20 20 4

E nc apsulatio n o f data as it go se do wn the pro to c o l stac ks

UNIX Network Programming 20

2.5 TCP 2.5 TCP Connection Establishment and Termination Connection Establishment and Termination (cont)(cont)

• TCP Options

– MSS option• With this option the TCP sending the SYN announces its maximum segment

size, the maximum amount of data that it is willing to accept in each TCP segment, on this connection.

– Window Scale option

– Timestamp option

UNIX Network Programming 21

• TCP Connection Termination

• half-close : Between steps 2 and 3 it is possible for data to flow from the end doing the passive close to the end doing active close.

2.5 TCP 2.5 TCP Connection Establishment and Termination Connection Establishment and Termination (cont)(cont)

c lient server

close

close(ac tive c lose)

connect returns

(pass ive c lose)read re turns 0

FIN M

ack N +1

ack M + 1

F igure 2.3 P ackets exchanged when a TC P connec tion is c losed.

FIN N

UNIX Network Programming 22

2.5 TCP 2.5 TCP CoConnection Estabnnection Establishment and Tlishment and Termination ermination (con(cont)t)

C LO S E D

L IS TE N

E S TAB L IS H E D

S Y N _R C VD S Y N _S E N T

C LO S E _WAIT

C LO S IN G LAS T_AC KF IN _WAIT_1

TIM E _WAITF IN _WAIT_2

starting po int

pass ive open

data transfer state

ac tive open

simultaneous c lose

2M S L timeout

pass ive c lose

appl: pass ive opensend: < nothing>

recv: S YN

send: S YN , AC Ks imultaneous open

recv: F INsend: AC K

recv: AC K

send: < nothing>

appl: c loseor timeout

recv : c losesend: F IN

recv : AC Ksend: < nothing>

recv : F INsend: AC K

recv : F INsend: AC K

recv : AC Ksend: < nothing>

ac tive c lose

F igure 2.4 TC P s tate trans ition diagram

- Statetransitiondiagram

UNIX Network Programming 23

• Watching the Packets

2.5 TCP 2.5 TCP Connection Establishment and Termination Connection Establishment and Termination (cont)(cont)c lient server

socket,bind,listenLISTEN(passive open)accpet(b locks)

socketconnect(b locks)

(ac tion open) S YN _S E N T

ESTABLISHEDconnect returns

ESTABLISHEDaccept returnsread(b locks)

F igure 2.5 P acket exc hange fo r TC P connec tion

closeLAST_ACK

close(ac tive c lose)

F IN _WAIT_1C LO S E _WAIT(pass ive c lose)read re turns 0

writeread(b locks)

read re turns

read re turns

<client forms request>

<server processes request>

writeread(b locks)

CLO SED

FIN_W AIT_2

TIM E_W AIT

UNIX Network Programming 24

2.6 2.6 TIME_WAITTIME_WAIT State State

• The end that performs the active close is the end that remains in the TIME_WAIT state=>because that end is the one that might have to retransmit the final ACK.

• There are two reason for TIME_WAIT state

– to implement TCP’s full-duplex connection termination reliably

– to allow old duplicate segments to expire in the network

UNIX Network Programming 25

2.7 Port Numbers2.7 Port Numbers

UNIX Network Programming 26

2.8 2.8 TCP port Numbers TCP port Numbers and Concurrent Serversand Concurrent Servers

server c lient

(* .21, * . * )

206.62.226.35206.62.226.66 198.69.10.2

{198.69.10.2.1500,206.62.226.35.21}

lis tening socket

connection request to

206.62.226.35, port 21

F igure 2.8 C onnec tion request from c lient to server

server c lient

(* .21, * . * )

206.62.226.35206.62.226.66 198.69.10.2

{198.69.10.2.1500,206.62.226.35.21}

lis tening socket

connection

F igure 2.9 C oncurrent server has child handle c lient

server(child)

{206.62.226.35.21,198.69.10.2.1500}

connected socket

fork

UNIX Network Programming 27

2.8 2.8 TCP port Numbers TCP port Numbers and Concurrent Serversand Concurrent Servers

server c lient1

(* .21, * . * )

206.62.226.35206.62.226.66 198.69.10.2

{198.69.10.2.1500,206.62.226.35.21}

lis tening socket

connection

F igure 2.10 S econd c lient connec tion with same server

server(child1)

{206.62.226.35.21,198.69.10.2.1500}

connected socket

fork

server(child2)

{206.62.226.35.21,198.69.10.2.1501}

connected socket

c lient2

{198.69.10.2.1500,206.62.226.35.21}

connection

UNIX Network Programming 28

2.9 Buffer Sizes and Limitations2.9 Buffer Sizes and Limitations

• Maximum size of IPv4 => 65535 byte

• Maximum size of IPv6 => 65575 byte

• MTU(maximum transmit unit) => fragmentation

• DF (don’t fragment)

• IPv4 and IPv6 define a minimum reassembly buffer size.

• TCP has MSS(maximum segment size)

UNIX Network Programming 29

TCP outputTCP output

UNIX Network Programming 30

UDP outputUDP output

UNIX Network Programming 31

2.10 standard internet service2.10 standard internet service

Notice: TCP and UDP port number is same.

UNIX Network Programming 32

2.11protocol usage by common internet Application2.11protocol usage by common internet Application