Unix Network Programming (2 nd Edition)

215
http://www.kwanghee.net http://www.kwanghee.net / Unix Unix Network Network Programming Programming (2 (2 nd nd Edition) Edition) Part 1. Introduction and TCP/IP Chapter 1. Introduction

description

Unix Network Programming (2 nd Edition). Part 1. Introduction and TCP/IP Chapter 1. Introduction. user process. web client. application layer. Web Server. application layer. TCP. TCP protocol. TCP. transport layer. protocol stack within kernel. IP. IP Protocol. IP. - PowerPoint PPT Presentation

Transcript of Unix Network Programming (2 nd Edition)

http://www.kwanghee.net/http://www.kwanghee.net/

UnixUnix

NetworkNetworkProgrammingProgramming(2(2ndnd Edition) Edition)

UnixUnix

NetworkNetworkProgrammingProgramming(2(2ndnd Edition) Edition)

Part 1. Introduction and TCP/IP

Chapter 1.Introduction

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

2

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข Most network application divided into โ€“ a client and a server

Client Servercommunication link

TCP

Ethernet Driver

IP

TCP

Web Serverweb client

IP

Ethernet Driver

application layer

transport layer

network layer

datalink layer

user process

protocol stack

within kernel

Ethernet

application layer

IP Protocol

Ethernet Protocol

TCP protocol

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

3

http://www.kwanghee.net/http://www.kwanghee.net/

Simple Daytime ClientSimple Daytime ClientSimple Daytime ClientSimple Daytime Client

1. #include "unp.h"

2. int3. main(int argc, char **argv)4. {5. int sockfd, n;6. char recvline[MAXLINE + 1];7. struct sockaddr_in servaddr;

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

10. if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)11. err_sys("socket error");

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

17. if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)18. err_sys("connect error");

19. while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {20. recvline[n] = 0; /* null terminate */21. if (fputs(recvline, stdout) == EOF)22. err_sys("fputs error");23. }24. if (n < 0)25. err_sys("read error");

26. exit(0);27. }

1. #include "unp.h"

2. int3. main(int argc, char **argv)4. {5. int sockfd, n;6. char recvline[MAXLINE + 1];7. struct sockaddr_in servaddr;

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

10. if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)11. err_sys("socket error");

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

17. if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)18. err_sys("connect error");

19. while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {20. recvline[n] = 0; /* null terminate */21. if (fputs(recvline, stdout) == EOF)22. err_sys("fputs error");23. }24. if (n < 0)25. err_sys("read error");

26. exit(0);27. }

Create TCP Socket

Specify serverโ€™s IP address and port

Establish connection with server

Read and display serverโ€™s reply

๋ช‡์‹œ์ฃ  ?

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

4

http://www.kwanghee.net/http://www.kwanghee.net/

IPv6 ClientIPv6 ClientIPv6 ClientIPv6 Client1. #include "unp.h"

2. int3. main(int argc, char **argv)4. {5. int sockfd, n;6. struct sockaddr_in6 servaddr;7. char recvline[MAXLINE + 1];

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

10. if ( (sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)11. err_sys("socket error");

12. bzero(&servaddr, sizeof(servaddr));13. servaddr.sin6_family = AF_INET6;14. servaddr.sin6_port = htons(13); /* daytime server */15. if (inet_pton(AF_INET6, argv[1], &servaddr.sin6_addr) <= 0)16. err_quit("inet_pton error for %s", argv[1]);

17. if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)18. err_sys("connect error");

19. while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {20. recvline[n] = 0; /* null terminate */21. if (fputs(recvline, stdout) == EOF)22. err_sys("fputs error");23. }24. if (n < 0)25. err_sys("read error");

26. exit(0);27. }

1. #include "unp.h"

2. int3. main(int argc, char **argv)4. {5. int sockfd, n;6. struct sockaddr_in6 servaddr;7. char recvline[MAXLINE + 1];

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

10. if ( (sockfd = socket(AF_INET6, SOCK_STREAM, 0)) < 0)11. err_sys("socket error");

12. bzero(&servaddr, sizeof(servaddr));13. servaddr.sin6_family = AF_INET6;14. servaddr.sin6_port = htons(13); /* daytime server */15. if (inet_pton(AF_INET6, argv[1], &servaddr.sin6_addr) <= 0)16. err_quit("inet_pton error for %s", argv[1]);

17. if (connect(sockfd, (SA *) &servaddr, sizeof(servaddr)) < 0)18. err_sys("connect error");

19. while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {20. recvline[n] = 0; /* null terminate */21. if (fputs(recvline, stdout) == EOF)22. err_sys("fputs error");23. }24. if (n < 0)25. err_sys("read error");

26. exit(0);27. }

IPv4 ํ•˜๊ณ ๊ฑฐ์˜ ์ฐจ์ด๊ฐ€

์—†์–ด์š” ..

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

5

http://www.kwanghee.net/http://www.kwanghee.net/

Error Handling (Error Handling (Wrapper Functions)Wrapper Functions)Error Handling (Error Handling (Wrapper Functions)Wrapper Functions)

โ€ข Performs the actual function call, tests the return value, and terminates on an errorโ€“ sockfd = Socket(AF_INET, SOCK_STREAM,0)

intSocket(int family, int type, int protocol){

int n;if (( n=socket(familty, type, protocol)) < 0)

err_sys(โ€œSocket errorโ€);return(n);

}

๊ทธ๋Ÿฌ๋‹ˆ๊น ,์†Œ์Šค๋ฅผ

๊ฐ„๋‹จํ•˜๊ฒŒ ๋ณด์—ฌ์ฃผ๋Š”

๊ฑฐ์ง€

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

6

http://www.kwanghee.net/http://www.kwanghee.net/

A Simple Daytime ServerA Simple Daytime ServerA Simple Daytime ServerA Simple Daytime Server

1. #include "unp.h"2. #include <time.h>3. int4. main(int argc, char **argv)5. {6. int listenfd, connfd;7. struct sockaddr_in servaddr;8. char buff[MAXLINE];9. time_t ticks;10. listenfd = Socket(AF_INET, SOCK_STREAM, 0);11. bzero(&servaddr, sizeof(servaddr));12. servaddr.sin_family = AF_INET;13. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);14. servaddr.sin_port = htons(13); /* daytime serve

r */15. Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));16. Listen(listenfd, LISTENQ);17. for ( ; ; ) {18. connfd = Accept(listenfd, (SA *) NULL, NULL);19. ticks = time(NULL);20. snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks));21. Write(connfd, buff, strlen(buff));22. Close(connfd);23. }24. }

Create Socket

Bind serverโ€™s well-known port to socket

Convert socket to listening socket

Accept client connection, send reply

& close

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

7

http://www.kwanghee.net/http://www.kwanghee.net/

OSI Model OSI Model (Layers in OSI model and Internet (Layers in OSI model and Internet protocol suite)protocol suite)

OSI Model OSI Model (Layers in OSI model and Internet (Layers in OSI model and Internet protocol suite)protocol suite)

Application

Session

Transport

Network

Datalink

Physical

Presentation

1 2 3 4 5 6 7

OSI Model

Application

TCP UDP

IPv4, IPv6Device

Driver &Hardware

Internet protocol suite

sockets XTI

user

Process

kernel

application

details

communications

details

์ €๋„ ๋ชจ๋ธ์ด์˜ˆ์š”

โ€ฆ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

8

http://www.kwanghee.net/http://www.kwanghee.net/

Unix StandardsUnix StandardsUnix StandardsUnix Standards

โ€ข POSIXโ€“ acronym for โ€œPortable Operation System Interfaceโ€โ€“ a family of standards being developed by the IEEE, also

adopted as by ISO/IECโ€“ http://www.pasc.org/standing/sd11.html

โ€ข The Open Groupโ€“ X/Open Company and Open Software Foundationsโ€“ XPG3(X/Open Portability Guide, Issue 3)โ€“ http://www.opengroup.org/public/tech/unix/version2

โ€ข IETF(Internet Engineering Task Force)โ€ข Unix Versions and Portability

โ€“ focus on Posix.1g

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network ProgrammingUnix Network Programming(2(2ndnd Edition) Edition)Unix Network ProgrammingUnix Network Programming(2(2ndnd Edition) Edition)

Part 1. Introduction and TCP/IP

Chapter 2.The Transport Layer: TCP and UDP

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

10

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข GOALโ€“ to provide enough detail to understand how to use the

protocols from a network programming perspectiveโ€“ provide references to more detailed descriptions of the

actual design, implementation, and history of the protocols

โ€ข TCPโ€“ to write robust clients and serverโ€“ sophisticated, byte-stream protocol

โ€ข UDPโ€“ simple, unreliable, datagram protocol

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

11

http://www.kwanghee.net/http://www.kwanghee.net/

The Big PictureThe Big PictureThe Big PictureThe Big Picture

m-routed

tcp-dump

pingtrace-route

app. app. app. app.trace-route

ping

API

TCP UDP

ICMP

IGMP IPv4 IPv6 ICMPv6

ARP,RARP

BPF,DLPI data link

32-bitaddress

128-bitaddress

IPv4 applications AF_INET sockaddr_in{} IPv6 applications AF_INET6 sockaddr_in6{}

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

12

http://www.kwanghee.net/http://www.kwanghee.net/

UDP (UDP (User Datagram Protocol)User Datagram Protocol)UDP (UDP (User Datagram Protocol)User Datagram Protocol)

โ€ข simple transport-layer protocolโ€ข App writes a datagram to a UDP socketโ€ข no guarantee that a UDP datagram ever reaches its

final destination โ€ข lack of reliabilityโ€ข UDP datagram has a lengthโ€ข a connectionless services

UDP ๋ฅผ ์†Œ๊ฐœํ•ฉ๋‹ˆ๋‹ค

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

13

http://www.kwanghee.net/http://www.kwanghee.net/

TCP (TCP (Transmission Control Protocol)Transmission Control Protocol)TCP (TCP (Transmission Control Protocol)Transmission Control Protocol)

โ€ข Provide connections between clients and serversโ€ข Provide reliabilityโ€ข also sequences the data by associating a sequence

number with every byteโ€ข Provide flow controlโ€ข full-duplex

์ •๊ณก

์„ ์ฐŒ

๋ฅด๋Š”

์ค‘

๋‚˜ TCP

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

14

http://www.kwanghee.net/http://www.kwanghee.net/

TCP Connection EstablishmentTCP Connection EstablishmentTCP Connection EstablishmentTCP Connection Establishment

client serversocket, bind, listenaccept(blocks)socket

connect(blocks)(active open)

SYN J

connect returns

SYN K, ack J+1

ack K+1accept returnsread(blocks)

TCP Three-way handshake

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

15

http://www.kwanghee.net/http://www.kwanghee.net/

TCP Connection TerminationTCP Connection TerminationTCP Connection TerminationTCP Connection Termination

Client Server

close(active close)

FIN M

(passive close)read returns 0ack M+1

FIN Nclose

ack N+1

Half close

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

16

http://www.kwanghee.net/http://www.kwanghee.net/

Watching the PacketsWatching the PacketsWatching the PacketsWatching the Packets

Client Serversocket, bind, listenLISTEN(passive open)accept(blocks)

socketconnect(blocks)(active open)SYN_SENT

SYN j, mss=1460

SYN_RCVDSYN k, ack j+1, mss = 1024

ESTABLISHEDconnect returns ack K+1

ESTABLISHEDaccept returnsread(blocks)write

read(blocks)data(request)

read returns<server processes request>

read returns

data(replay)ack of request

ack of reply

close

CLOSE_WAIT(passive close)read return 0

FIN M(active close) FIN_WAIT_1

ack M+1FIN_WAIT_2

FIN N

ack N+1

closeLAST_ACK

CLOSEDTIME_WAIT

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

17

http://www.kwanghee.net/http://www.kwanghee.net/

TIME_WAIT State & Port NumberTIME_WAIT State & Port NumberTIME_WAIT State & Port NumberTIME_WAIT State & Port Number

โ€ข TIME_WAIT Stateโ€“ MSL(Maximum segment life time)

โ€  RFC 1122, about 2 min.

โ€“ Two Reasonsโ€  to implement TCPโ€™s full-duplex connection termination reliablyโ€  to allow old duplicate segments to expire in the network

โ€ข Port Number (IANA)โ€“ well-known ports : 0 ~ 1023โ€“ registered port : 1024 ~ 49151โ€“ dynamic or private ports : 49152 ~ 65535

โ€ข Socket Pairโ€“ local IP add., local TCP port, foreign IP add., foreign port

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

18

http://www.kwanghee.net/http://www.kwanghee.net/

Concurrent ServerConcurrent ServerConcurrent ServerConcurrent Server

206.62.226.35206.62.226.66

Server

server(child 1)

server(child 1)

server(child 2)

server(child 2)

{ *. 21, *.*}

{ 206.62.226.35.21,198.69.10.2.1500}

{ 206.62.226.35.21,198.69.10.2.1501}

listeningsocket

connectedsocket

connectedsocket

198.69.10.2

client 1client 1

client 1client 1

{ 198.69.10.2.1500,206.62.226.35.21}

{ 198.69.10.2.1501,206.62.226.35.21}

connection

connection

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

19

http://www.kwanghee.net/http://www.kwanghee.net/

์˜๋ฌธ์ ์˜๋ฌธ์  (from Java Tutorial)(from Java Tutorial)์˜๋ฌธ์ ์˜๋ฌธ์  (from Java Tutorial)(from Java Tutorial)

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request. On the client-side: The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. To make a connection request, the client tries to rendezvous with the server on the server's machine and port.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a the server gets a

new socket bound to a different portnew socket bound to a different port. It needs a new socket (and consequently a different port number) so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the

client can use the socket to communicate with the server. Note that the socket on the client side is not bound to the port number used to rendezvous with the server. Rather, the client is assigned a port number local to the machine on which the client is running.

The client and server can now communicate by writing to or reading from their sockets.

๊ทธ๊ฒƒ์„ ์•Œ๊ณ  ์‹ถ๋‹ค ????

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

20

http://www.kwanghee.net/http://www.kwanghee.net/

TCP OutputTCP Output(Steps and buffers involved when application writes to a TCP socket)(Steps and buffers involved when application writes to a TCP socket)

TCP OutputTCP Output(Steps and buffers involved when application writes to a TCP socket)(Steps and buffers involved when application writes to a TCP socket)

application

TCP

IP

Output Queuedata link

user process

kernel

application buffer(any size)

socket send buffer(SO_SNDBUF)

MSS-sized TCP segmentsMSS normally MTU-40(IPv4) or MTU-60 (IPv6)

MTU-sized IPv4 or IPv6 packets

์ด๋ด ~ ์ˆœ์„œ๋Œ€๋กœ ๋„ฃ์–ด์„œ ๋ณด๋‚ด์•ผ

ํ•œ๋‹ค๊ตฌ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

21

http://www.kwanghee.net/http://www.kwanghee.net/

UDP OutputUDP Output(Steps and buffers involved when application writes to a UDP socket)(Steps and buffers involved when application writes to a UDP socket)

UDP OutputUDP Output(Steps and buffers involved when application writes to a UDP socket)(Steps and buffers involved when application writes to a UDP socket)

application

UDP

IP

Output Queuedata link

user process

kernel

application buffer(any size)

socket send buffer(SO_SNDBUF)

UDP datagram

MTU-sized IPv4 or IPv6 packets

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

22

http://www.kwanghee.net/http://www.kwanghee.net/

UNIX Network Programming UNIX Network Programming (chapter 3 ~ 5) (chapter 3 ~ 5) UNIX Network Programming UNIX Network Programming (chapter 3 ~ 5) (chapter 3 ~ 5)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

23

http://www.kwanghee.net/http://www.kwanghee.net/

โ—† Socket Address Structures

โ—† Socket Functions

โ—† TCP Socket

โ—† POSIX ์‹ ํ˜ธ์ฒ˜๋ฆฌ โ—† Server Source Example

โ—† Client Source Example

AgendaAgendaAgendaAgenda

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

24

http://www.kwanghee.net/http://www.kwanghee.net/

struct in6_addr {

uint8_t s6_addr[16]; /* 128 bit IPv6 */

};

struct sockaddr_in6 {

uint8_t sin6_len; /* 16 */

sa_family_t sin6_family;

in_port_t sin6_port;

uint32_t sin6_flowinfo; /* priority & flow */

struct in6_addr sin6_addr; /* 128 bit IPv6 */

};

struct in6_addr {

uint8_t s6_addr[16]; /* 128 bit IPv6 */

};

struct sockaddr_in6 {

uint8_t sin6_len; /* 16 */

sa_family_t sin6_family;

in_port_t sin6_port;

uint32_t sin6_flowinfo; /* priority & flow */

struct in6_addr sin6_addr; /* 128 bit IPv6 */

};

IPv6struct in_addr {

in_addr_t s_addr; /* 32 bit IPv4 */

};

struct sockaddr_in {

uint8_t sin_len; /* 16 */

sa_family_t sin_family;

in_port_t sin_port;

struct in_addr sin_addr; /* 32 bit IPv4 */

char sin_zero[8]; /* unused */

};

struct in_addr {

in_addr_t s_addr; /* 32 bit IPv4 */

};

struct sockaddr_in {

uint8_t sin_len; /* 16 */

sa_family_t sin_family;

in_port_t sin_port;

struct in_addr sin_addr; /* 32 bit IPv4 */

char sin_zero[8]; /* unused */

};

IPv4struct in_addr {

in_addr_t s_addr; /* 32 bit IPv4 */

};

struct sockaddr_in {

uint8_t sin_len; /* value = 16 */

sa_family_t sin_family;

in_port_t sin_port; /* 16 bit */

struct in_addr sin_addr; /* 32 bit IPv4 */

char sin_zero[8]; /* unused */

};

struct in_addr {

in_addr_t s_addr; /* 32 bit IPv4 */

};

struct sockaddr_in {

uint8_t sin_len; /* value = 16 */

sa_family_t sin_family;

in_port_t sin_port; /* 16 bit */

struct in_addr sin_addr; /* 32 bit IPv4 */

char sin_zero[8]; /* unused */

};

IPv4

struct sockaddr {

uint8_t sa_len; /* for variable socket address structure */

sa_family_t sa_family; /* address family */

char sa_data[14]; /* protocol-specific address */

};

struct sockaddr {

uint8_t sa_len; /* for variable socket address structure */

sa_family_t sa_family; /* address family */

char sa_data[14]; /* protocol-specific address */

};

Basic

Socket Address StructuresSocket Address StructuresSocket Address StructuresSocket Address Structures

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

25

http://www.kwanghee.net/http://www.kwanghee.net/

int socket( int family, int type, int protocol );

int bind( int sockfd, struct sockaddr *addrptr, int addrlen );

int connect( int sockfd, struct sockaddr *addrptr, int addrlen );

int listen( int sockfd, int backlog );

int accept( int sockfd, struct sockaddr *addrptr, int *addrlen );

int close( int sockfd );

int getsocketname( int sockfd, struct sockaddr *loacladdr, socklen_t *addrlen );

int getpeername ( int sockfd, struct sockaddr *peeraddr, socklen_t *addrlen );

void bzero( void #dest, size_t nbytes );

void bcopy( const void *src, void *dest, size_t nbytes );

int bcmp( const void *ptr1, const void *ptr2, size_t nbytes );

๋ฐ”์ดํŠธ ์กฐ์ž‘ ํ•จ์ˆ˜

์ฃผ์†Œ ๋ณ€ํ™˜ ํ•จ์ˆ˜int inet_pton( int family, const char *strptr, void *addrptr );

const char *inet_ntop( int family, const void *addrptr, char *strptr, size_t len );

int inet_aton( const char *strptr, struct in_addr *addrptr );

char *inet_ntoa( struct in_addr inaddr );

IPv4

IPv4 and IPv6

๋’ค์— ์ž์„ธํžˆ๋ด…์‹œ๋‹ค .

Socket address์ •๋ณด๋ฅผ ์–ป๋Š” ํ•จ์ˆ˜

Socket Functions (1)Socket Functions (1)Socket Functions (1)Socket Functions (1)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

26

http://www.kwanghee.net/http://www.kwanghee.net/

uint32_t htonl( uint32_t hostlong );

uint32_t ntohl( uint32_t netlong );

uint16_t htons( uint16_t hostshort );

uint16_t ntohs( uint16_t hostshort );

ssize_t readn( int filedes, void *buff, size_t nbytes );

ssize_t writen( int filedes, const void *buff, size_t nbytes );

ssize_t readline( int filedes, void buff, size_t maxlen );

๋ฐ”์ดํŠธ ์ˆœ์„œ ํ•จ์ˆ˜

์ž…์ถœ๋ ฅ ํ•จ์ˆ˜

Network byte ์ˆœ์„œ๋Š”Big-endian ์ด๋‹ค .

Socket Functions (2)Socket Functions (2)Socket Functions (2)Socket Functions (2)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

27

http://www.kwanghee.net/http://www.kwanghee.net/

sock

et(

)

bind

( )

list

en(

)

acce

pt(

)

read

( )

wri

te(

)

read

( )

clos

e( )

conn

ect(

)

sock

et(

)

wri

te(

)

read

( )

clos

e( )

TC

P C

lien

t

TC

P S

erve

r

bloc

ks u

ntil

con

nect

ion

from

cli

ent

Pro

cess

req

uest

wel

l-kn

own

port

Con

nect

ion

esta

blis

hmen

t

(TC

P th

ree-

way

han

dsha

ke)

data

(req

uest

)

data

(rep

ly)

data

(req

uest

)

end-

of-f

ile

noti

fica

tion

TCP SocketTCP SocketTCP SocketTCP Socket

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

28

http://www.kwanghee.net/http://www.kwanghee.net/

family Description

AF_INETAF_INET6AF_LOCALAF_ROUTEAF_KEY

IPv4 protocolsIPv6 protocolsUnix domain protocolsRouting socketsKey sockets

type Description

SOCK_STREAMSOCK_DGRAMSOCK_RAW

stream socketdatagram socketraw socket

TCP TCP Yes

UDP UDP Yes

IPv4 IPv6 Yes Yes

SOCK_STREAM

SOCK_DGRAM

SOCK_RAW

AF_INET AF_INET6 AF_LOCAL AF_ROUTE AF_KEY

< Address family >

< Socket Type >

int socket( int family, int type, int protocol );

โ˜ž protocol argument ๋Š” raw socket ์„ ์ œ์™ธํ•˜๊ณ ๋Š” 0 ์œผ๋กœ ์ •ํ•œ๋‹ค .

โ˜ž key socket : kernel ์˜ ์•”ํ˜ธํ™” key table ์—์˜ interface ์ด๋‹ค .

โ˜ž raw socket : TCP ๋‚˜ UDP ์˜ header ์—†์ด ๋ฐ”๋กœ IP header ๋ฅผ ๋ถ™์—ฌ์„œ ์‚ฌ์šฉํ•œ๋‹ค .

socket()socket()socket()socket()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

29

http://www.kwanghee.net/http://www.kwanghee.net/

int connect( int sockfd, const struct sockaddr *servaddr, socklen_t addrlen );

โ˜ž client ๊ฐ€ remote socket ํ˜น์€ server ๋กœ ์—ฐ๊ฒฐ์„ ์„ค์ •ํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์‚ฌ์šฉ

โ˜ž three-way handshake ์‚ฌ์šฉ

int bind( int sockfd, const struct sockaddr *myaddr, socklen_t addrlen );

โ˜ž ์ƒ์„ฑ๋œ socket ์— myaddr ๊ตฌ์กฐ์ฒด๋กœ ์ฃผ์–ด์ง„ ์ฃผ์†Œ๋ฅผ ๋ถ€์—ฌ

โ˜ž ๋ณดํ†ต server ๊ฐ€ ์ž์‹ ์ด ์ œ๊ณตํ•˜๋Š” service port ๋ฅผ ์ง€์ •ํ•˜๊ธฐ ์œ„ํ•˜์—ฌ ์‚ฌ์šฉ

โ˜ž client ์˜ ๊ฒฝ์šฐ bind() ์‹œ์Šคํ…œ ํ˜ธ์ถœ์„ ์‚ฌ์šฉํ•˜์ง€ ์•Š์œผ๋ฉด kernel ์ด ์‚ฌ์šฉํ•˜์ง€ ์•Š๋Š” port ๋ฅผ ์ž๋™์ ์œผ๋กœ ํ• ๋‹น

์ผ๋ฐ˜์ ์œผ๋กœ binding ํ•˜์ง€ ์•Š๋Š”๋‹ค .

Process specifies

IP address port

wildcardwildcard

local IP addresslocal IP address

0nonzero

0nonzero

Result

kernel chooses IP address and portkernel chooses IP address, process specifies portprocess specifies IP address, kernel chooses portprocess specifies IP address and port

connect(), bind()connect(), bind()connect(), bind()connect(), bind()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

30

http://www.kwanghee.net/http://www.kwanghee.net/

int listen( int sockfd, int backlog );

โ˜ž server ์˜ ๊ฒฝ์šฐ๋งŒ ์‚ฌ์šฉ

โ˜ž server program ์˜ ๊ฒฝ์šฐ ์ž์‹ ์ด server ๋กœ ๋™์ž‘ํ•˜๋Š” socket ์„ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ์Œ์„ listen() system call ์„ ์‚ฌ์šฉํ•˜์—ฌ kernel ์— ์•Œ๋ฆฐ๋‹ค .

server

TCP

3WHS

complete

arriving SYN

accept

sum of both queues cannot exceed backlog

completed connection queue (ESTABLISHED state)

incompleted connection queue (SYN_RCVD state)

listen()listen()listen()listen()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

31

http://www.kwanghee.net/http://www.kwanghee.net/

int accept( int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen );

โ˜ž incoming connection request ๋ฅผ ์ ‘์ˆ˜

โ˜ž cliaddr ์— accept ๋œ client ์˜ ์ฃผ์†Œ๋ฅผ ๋ฐ›์•„์˜จ๋‹ค .

int close( int sockfd );

โ˜ž socket ์„ ์ •์ƒ์ ์ธ ์ข…๋ฃŒ ๋ฐฉ์‹์œผ๋กœ ์ข…๋ฃŒํ•œ๋‹ค .

accept(), close()accept(), close()accept(), close()accept(), close()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

32

http://www.kwanghee.net/http://www.kwanghee.net/

pid_t fork( void );

โ˜ž process ๊ฐ€ ์ž์‹ ์˜ ๋ณต์‚ฌ๋ณธ์„ ๋งŒ๋“ค์–ด์„œ ๊ฐ๊ธฐ ๋‹ค๋ฅธ ์ผ์„ ์ฒ˜๋ฆฌํ•˜๋„๋ก ํ•œ๋‹ค .

server client

listenfdconnect( )

connectionrequest

listenfd

connfd

server

connect( )

client

connection

listenfd

connfd

server (parent)

connect( )

client

connection

listenfd

connfd

server (child)

fork

conn

ectio

n

listenfd

server (parent)

connect( )

client

connfd

server (child)

conn

ectio

n

* listenfd : listening socket

connfd : connected socket

fork ()fork ()fork ()fork ()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

33

http://www.kwanghee.net/http://www.kwanghee.net/

โ˜ž ๋ชจ๋“  ์‹ ํ˜ธ๋Š” ์ž์‹ ๊ณผ ์—ฐ๊ณ„๋œ disposition ์„ ๊ฐ€์ง€๋ฉฐ , ๋•Œ๋กœ๋Š” ์ด๋ฅผ action ์ด๋ผ๊ณ ๋„ ๋ถ€๋ฅธ๋‹ค .

โ˜ž ์‹ ํ˜ธ์˜ disposition ์„ sigaction ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜์—ฌ ์„ค์ •ํ•œ๋‹ค .

1) ํŠน์ • ์‹ ํ˜ธ๊ฐ€ ๋ฐœ์ƒํ•  ๋•Œ๋งˆ๋‹ค ํ˜ธ์ถœํ•  ํ•จ์ˆ˜๋ฅผ ์ œ๊ณตํ•œ๋‹ค . SIGKILL ๊ณผ SIGSTOP ์€ ํฌ์ฐฉํ•  ์ˆ˜ ์—†๋Š” ๋‘ ๊ฐœ์˜ ์‹ ํ˜ธ์ด๋‹ค .

2) ๊ณ„ํš์„ SIG_IGN ์œผ๋กœ ์„ค์ •ํ•จ์œผ๋กœ์จ ์‹ ํ˜ธ๋ฅผ ๋ฌด์‹œํ•  ์ˆ˜ ์žˆ๋‹ค . SIGKILL ๊ณผ SIGSTOP ์€ ๋ฌด์‹œํ•  ์ˆ˜ ์—†๋‹ค .

3) ๊ณ„ํš์„ SIG_DFL ๋กœ ์„ค์ •ํ•จ์œผ๋กœ์จ ์‹ ํ˜ธ์˜ default disposition ์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค . ๊ธฐ๋ณธ์€ ๋ณดํ†ต ์‹ ํ˜ธ๋ฅผ ๋ฐ›์œผ๋ฉด process ๋ฅผ ์ข…๋ฃŒ์‹œํ‚ค๋Š” ๊ฒƒ์ด๋ฉฐ , ์–ด๋–ค ์‹ ํ˜ธ์—์„œ๋Š” process ์˜ memory ๋‚ด์šฉ์„ ๊ทธ๋Œ€๋กœ ํ˜„์žฌ์˜ working directory ์— ์˜ฎ๊ฒจ๋†“๊ธฐ๋„ ํ•œ๋‹ค .

typedef void Sigfunc( int );Sigfunc *signal( int signo, Sigfunc *func );{

struct sigaction act, oact;

act.sa_handler = func;sigemptyset( &act.sa_mask );act.sa_flags = 0;

if ( sigaction( signo, &act, &oact ) < 0 )return ( SIG_ERR );

return ( oact.sa_handler );}signo = signal ์ด๋ฆ„func = ํ•จ์ˆ˜๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” ์ง€์‹œ์ž ๋˜๋Š” SIG_IGN , SIG_DFL

POSIX POSIX ์‹ ํ˜ธ์ฒ˜๋ฆฌ์‹ ํ˜ธ์ฒ˜๋ฆฌPOSIX POSIX ์‹ ํ˜ธ์ฒ˜๋ฆฌ์‹ ํ˜ธ์ฒ˜๋ฆฌ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

34

http://www.kwanghee.net/http://www.kwanghee.net/

โ˜ž Process ๊ฐ€ ์ข…๋ฃŒ๋  ๋•Œ๋งˆ๋‹ค kernel ์ด ์ข…๋ฃŒํ•˜๋Š” process ์˜ parent ์—๊ฒŒ ๋ณด๋‚ด๋Š” ๊ฒƒ์ด๋‹ค .

โ˜ž zombie ์ƒํƒœ์˜ child ๋ฅผ ์ œ๊ฑฐํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” wait ํ•จ์ˆ˜๋ฅผ ์ˆ˜ํ–‰ํ•ด์•ผ ํ•˜๊ณ  ๋งŒ์•ฝ server ์™€ ์—ฌ๋Ÿฌ ์—ฐ๊ฒฐ์„ ์„ค์ •ํ•œ ๊ฒฝ์šฐ๋Š” waitpid ํ•จ์ˆ˜๋กœ ๊ฐ๊ฐ์„ ์ง€์ •ํ•˜์—ฌ ์ข…๋ฃŒ๋˜๋„๋ก ํ•œ๋‹ค .

pid_t wait( int *statloc );

pid_t waitpid( pid_t pid, int *statloc, int options );

option ์˜ ๊ฒฝ์šฐ โ€œ WNOHANGโ€ ์„ ์ผ๋ฐ˜์ ์œผ๋กœ ์„ ํƒํ•˜๋Š”๋ฐ ์ด๋Š” kernel ์—๊ฒŒ ์ข…๋ฃŒ๋  child process ๊ฐ€ ์—†์œผ๋ฉด blocking ํ•˜์ง€ ๋ง๋„๋ก ํ•˜๋ฉฐ , ์•„์ง ์ข…๋ฃŒ๋˜์ง€ ์•Š์€ child process ๊ฐ€ ์žˆ์œผ๋ฉด waitpid ๊ฐ€ blocking ํ•˜์ง€ ์•Š๋„๋ก ํ•œ๋‹ค .

4 3 2 1 0Serverparent

Serverchild #1

Serverchild #2

Serverchild #3

Serverchild #4

Serverchild #5

PID TT STAT TIME COMMAND

21282 p1 S 0:00.09 ./tcpserv03

21284 p1 Z 0:00.00 (tcpserv03)

21285 p1 Z 0:00.00 (tcpserv03)

21286 p1 Z 0:00.00 (tcpserv03)

21287 p1 Z 0:00.00 (tcpserv03)

< wait ์‚ฌ์šฉ์‹œ >

clientexit

FIN

SIGCHLD

SIGCHLD signalSIGCHLD signalSIGCHLD signalSIGCHLD signal

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

35

http://www.kwanghee.net/http://www.kwanghee.net/

โ˜ž sever ๊ฐ€ ๋จผ์ € ์ข…๋ฃŒ๋˜์–ด ๋ฒ„๋ฆฐ ๊ฒฝ์šฐ server TCP ๊ฐ€ client ๋กœ๋ถ€ํ„ฐ data ๋ฅผ ๋ฐ›์œผ๋ฉด process ๊ฐ€ ์ข…๋ฃŒ๋˜์—ˆ๊ธฐ ๋•Œ๋ฌธ์— RST์„ ๋ณด๋‚ธ๋‹ค .

โ˜ž process ๊ฐ€ RST ์„ ๋ฐ›์€ socket ์— data ๋ฅผ ์“ฐ๋ฉด write ๋Š” EPIPE ๋ฅผ ๋Œ๋ ค์ค€๋‹ค .

โ˜ž ์ด๋ฅผ ์ ์ ˆํžˆ ์ฒ˜๋ฆฌํ•ด ์ฃผ์ง€ ์•Š์œผ๋ฉด โ€œ server terminated prematurelyโ€ ์™€ ๊ฐ™์€ error message ์™€ ํ•จ๊ป˜ ์ข…๋ฃŒ๋œ๋‹ค ..

SIGPIPE signalSIGPIPE signalSIGPIPE signalSIGPIPE signal

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

36

http://www.kwanghee.net/http://www.kwanghee.net/

int main( int argc, char **argv ){ int listenfd, connfd; pid_t childpid; socklen_t clilen; struct sockaddr_in cliaddr, seraddr; void sig_chld( int );

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( SERV_PORT );

Bind( listenfd, (SA *)&servaddr, sizeof(servaddr) ); Listen( listenfd, LISTENQ ); Signal( SIGCHLD, sig_chld );

for ( ; ; ) { clilen = sizeof (cliaddr );

server ์˜ ์ฃผ์†Œ๋“ฑ๋ก

SERV_PORT ๋Š” ์ง€์ •๋œ port number

child process ์ข…๋ฃŒ์‹œ ์ˆ˜์‹ ๋˜๋Š” SIGCHLD signal ์„ ํ•˜๋„๋ก ์„ค์ •

Server source example (1)Server source example (1)Server source example (1)Server source example (1)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

37

http://www.kwanghee.net/http://www.kwanghee.net/

if ( (connfd = accept( listenfd, (SA *)&cliaddr, &clilen ) ) < 0 ) { if ( errno == EINTR ) continue; else err_sys( โ€œaccept errorโ€ ); } if ( (childpid = Fork() ) == 0 ) { Close( listenfd ); /* child closes listening socket */ str_echo( connfd ); /* do it all */ exit(0); } Close( connfd ); /* parent closes connected socket */ }}

void sig_chld( int signo ){ pid_t pid; int stat; while ( ( pid = waitpid( -1, &stat, WNOHANG ) ) > 0 )

printf( โ€œchild %d terminated\nโ€, pid ); return;}

slow system call( ์—ฌ๊ธฐ์„œ๋Š” accept)์ด EINTR( ์ผ์‹œ ์ค‘์ง€๋œ ์‹œ์Šคํ…œํ˜ธ์ถœ )

์„ ๋Œ๋ ค์ฃผ๋Š”๋ฐ ๊ทธ๊ฑธ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌ

Server source example (2)Server source example (2)Server source example (2)Server source example (2)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

38

http://www.kwanghee.net/http://www.kwanghee.net/

int main( int argc, char **argv ){ int i, sockfd[5]; struct sockaddr_in seraddr; if ( argc != 2 ) err_quit( โ€œusage: tcpcli <IPaddress>โ€ );

for ( i=0; i<5; i++ ) { sockfd[i] = Socket( AF_INET, SOCK_STREAM, 0 );

bzero( &servaddr, sizeof(servaddr) ); servaddr.sin_family = AF_INET; servaddr.sin_port = htons( SERV_PORT ); Inet_pton( AF_INET, argv[1], &servaddr.sin_addr );

Connect( sockfd[i], (SA *)&servaddr, sizeof( servaddr ) ); }

str_cli( stdin, sockfd[0] ); /* do it all */ exit(0);}

์ ‘์†ํ•  server ์ฃผ์†Œ๋ฅผ ๋“ฑ๋กํ•œ๋‹ค .

Client source exampleClient source exampleClient source exampleClient source example

http://www.kwanghee.net/http://www.kwanghee.net/

Chapter 6 Chapter 6 I/O Multiplexing: TheI/O Multiplexing: The selectselect andand pollpoll FunctionsFunctionsChapter 6 Chapter 6 I/O Multiplexing: TheI/O Multiplexing: The selectselect andand pollpoll FunctionsFunctions

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

40

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข I/O Multiplexing ์€ select, poll, pselect ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ์ œ๊ณต๋จโ€ข I/O Multiplexing ์ด ์‚ฌ์šฉ๋˜๋Š” ์˜ˆ

โ€“ client ๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ descriptor( ์˜ˆ๋ฅผ ๋“ค๋ฉด , interactive input ๊ณผ network socket) ์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒฝ์šฐ

โ€“ client ๊ฐ€ ๋™์‹œ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ socket ์„ ๊ด€๋ฆฌํ•ด์•ผ ํ•˜๋Š” ๊ฒฝ์šฐโ€“ TCP ์„œ๋ฒ„๊ฐ€ listening socket ๊ณผ connected socket ์„ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒฝ์šฐโ€“ ์„œ๋ฒ„๊ฐ€ TCP ์™€ UDP ๋ฅผ ๋™์‹œ์— ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐโ€“ ์„œ๋ฒ„๊ฐ€ ๋™์‹œ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์„œ๋น„์Šค์™€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ”„๋กœํ† ์ฝœ์„ ๊ด€๋ฆฌํ•ด์•ผ

ํ•˜๋Š” ๊ฒฝ์šฐ ( ์˜ˆ : inetd)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

41

http://www.kwanghee.net/http://www.kwanghee.net/

I/O ModelsI/O ModelsI/O ModelsI/O Models

โ€ข blocking I/Oโ€ข nonblocking I/Oโ€ข I/O multiplexing (select and poll)โ€ข signal-driven I/O (SIGIO)โ€ข asynchronous I/O (Posix.1 aio_ functions)

โ€ป ๊ฐ I/O ๋ชจ๋ธ์— ๋Œ€ํ•œ ์„ค๋ช…์€ Text ์˜ Fig 6.1~6.6 ์„ ์ฐธ๊ณ 

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

42

http://www.kwanghee.net/http://www.kwanghee.net/

selectselect Function Functionselectselect Function Function

โ€ข Allows the process to instruct the kernel to wait for any one of multiple events to occur and to wake up the process only when one or more of these events occurs or when a specified amount of time has passed.

#include <sys/select.h>#include <sys/time.h>

int select(int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, const struct timeval *timeout);

Returns: positive count of ready descriptors, 0 on timeout, -1 on error

1. Wait forever: timeout = NULL2. Wait up to a fixed amount time: timeout specified in the timeval structure3. Donโ€™t wait at all: timeout = 0

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

43

http://www.kwanghee.net/http://www.kwanghee.net/

selectselect Function (contโ€™d) Function (contโ€™d)selectselect Function (contโ€™d) Function (contโ€™d)

โ€ข fd_set ์ œ์–ด ๋งคํฌ๋กœโ€“ void FD_ZERO(fd_set *fdset);โ€“ void FD_SET(int fd, fd_set *fdset);โ€“ void FD_CLR(int fd, fd_set *fdset);โ€“ int FD_ISSET(int fd, fd_set *fdset);

โ€ข Under What Conditions Is a Descriptor Ready?โ€“ Ready for reading ifโ€ฆ

โ€  ์†Œ์ผ“์˜ receive buffer ์˜ ๋ฐ์ดํ„ฐ ๋ฐ”์ดํŠธ์ˆ˜ โ‰ฅ low-water mark for receive buf. ( ๋””ํดํŠธ 1) (read ์—ฐ์‚ฐ์˜ return ๊ฐ’ > 0)

โ€  ์—ฐ๊ฒฐ์˜ read-half ๊ฐ€ ๋‹ซํžŒ ๊ฒฝ์šฐ (read ์—ฐ์‚ฐ์˜ return ๊ฐ’ = 0)โ€  listening socket ์ธ ๊ฒฝ์šฐ , ์™„๋ฃŒ๋œ ์—ฐ๊ฒฐ์˜ ์ˆ˜๊ฐ€ 0 ์ด์ƒ์ธ ๊ฒฝ์šฐโ€  pending error ๋ฐœ์ƒ (read ์—ฐ์‚ฐ์˜ ๋ฆฌํ„ด ๊ฐ’ = -1)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

44

http://www.kwanghee.net/http://www.kwanghee.net/

selectselect Function (contโ€™d) Function (contโ€™d)selectselect Function (contโ€™d) Function (contโ€™d)

โ€“ Ready for writing ifโ€ฆโ€  socket ์˜ send buffer ์˜ ๋ฐ์ดํ„ฐ ๋ฐ”์ดํŠธ์ˆ˜ โ‰ฅ low-water mark for send buf.

( ๋””ํดํŠธ 2048) ์ด๊ณ  , ์†Œ์ผ“์ด ์—ฐ๊ฒฐ ์ค‘์ด๊ฑฐ๋‚˜ UDP ์ธ ๊ฒฝ์šฐ (write ์—ฐ์‚ฐ์˜ ๋ฆฌํ„ด ๊ฐ’ > 0)

โ€  ์—ฐ๊ฒฐ์˜ write-half ๊ฐ€ ๋‹ซํžŒ ๊ฒฝ์šฐ (write ์—ฐ์‚ฐ ๋•Œ SIGPIPE ๋ฐœ์ƒ )โ€  pending error ๋ฐœ์ƒ (write ์—ฐ์‚ฐ์˜ ๋ฆฌํ„ด ๊ฐ’ = -1)

โ€“ Exception condition ifโ€ฆโ€  ์†Œ์ผ“์— Out-of-band data ๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ (Chap. 21 ์—์„œ ์„ค๋ช… ..)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

45

http://www.kwanghee.net/http://www.kwanghee.net/

shutdownshutdown Function Functionshutdownshutdown Function Function

โ€ป howto ์ธ์ˆ˜ : SHUT_RD / SHUT_WR / SHUT_RDWR

#include <sys/socket.h>

int shutdown (int sockfd, int howto); Returns: 0 if OK, -1 on error

client serverdata

data

data

data

FIN

FIN

ack of data and FIN

ack of data and FIN

write

write

SHUTDOWN(SHUT_WR)

read returns>0

read returns>0

read returns 0

write

write

close

read returns>0

read returns>0

read returns 0

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

46

http://www.kwanghee.net/http://www.kwanghee.net/

Example (Example (str_clistr_cli Functionโ€“Revisited) Functionโ€“Revisited)Example (Example (str_clistr_cli Functionโ€“Revisited) Functionโ€“Revisited)

1 #include "unp.h" 2 3 void 4 str_cli(FILE *fp, int sockfd) 5 { 6 int maxfdp1, stdineof; 7 fd_set rset; 8 char sendline[MAXLINE], recvline[MAXLINE]; 9 10 stdineof = 0; 11 FD_ZERO(&rset); 12 for ( ; ; ) { 13 if (stdineof == 0) 14 FD_SET(fileno(fp), &rset); 15 FD_SET(sockfd, &rset); 16 maxfdp1 = max(fileno(fp), sockfd) + 1; 17 Select(maxfdp1, &rset, NULL, NULL, NULL); 18 19 if (FD_ISSET(sockfd, &rset)) { /* socket is readable */ 20 if (Readline(sockfd, recvline, MAXLINE) == 0) { 21 if (stdineof == 1) 22 return; /* normal termination */ 23 else 24 err_quit("str_cli: server terminated prematurely"); 25 }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

47

http://www.kwanghee.net/http://www.kwanghee.net/

Example (Example (str_clistr_cli Functionโ€“Revisited) Functionโ€“Revisited)Example (Example (str_clistr_cli Functionโ€“Revisited) Functionโ€“Revisited)

26 27 Fputs(recvline, stdout); 28 } 29 30 if (FD_ISSET(fileno(fp), &rset)) { /* input is readable */ 31 if (Fgets(sendline, MAXLINE, fp) == NULL) { 32 stdineof = 1; 33 Shutdown(sockfd, SHUT_WR); /* send FIN */ 34 FD_CLR(fileno(fp), &rset); 35 continue; 36 } 37 38 Writen(sockfd, sendline, strlen(sendline)); 39 } 40 } 41 }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

48

http://www.kwanghee.net/http://www.kwanghee.net/

pselectpselect and and pollpoll Functions Functionspselectpselect and and pollpoll Functions Functions

#include <sys/select.h>#include <signal.h>#include <time.h>

int pselect (int maxfdp1, fd_set *readset, fd_set *writeset, fd_set *exceptset, const struct timespec *timeout, const sigset_t *sigmask);

Returns: count of ready descriptors, 0 on timeout, -1 on error

#include <poll.h>

int poll (struct pollfd *fdarray, unsigned long nfds, int timeout);

Returns: count of ready descriptors, 0 on timeout, -1 on error

http://www.kwanghee.net/http://www.kwanghee.net/

Chapter 7 Chapter 7 Socket OptionsSocket OptionsChapter 7 Chapter 7 Socket OptionsSocket Options

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

50

http://www.kwanghee.net/http://www.kwanghee.net/

Socket OptionSocket Option ์„ ์„ get/setget/set ํ•˜๋Š” ํ•จ์ˆ˜ํ•˜๋Š” ํ•จ์ˆ˜Socket OptionSocket Option ์„ ์„ get/setget/set ํ•˜๋Š” ํ•จ์ˆ˜ํ•˜๋Š” ํ•จ์ˆ˜

โ€ข getsockopt and setsockopt functions

โ€ข fnctl functionโ€ข ioctl function

โ€ป getsockopt, setsockopt ํ•จ์ˆ˜๊ฐ€ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ ์†Œ์ผ“ ์˜ต์…˜ ์ •๋ฆฌ (Fig. 7.1 of text)

#include <sys/socket.h>

int getsockopt(int sockfd, int level, int optname, void *optval, socklen_t *optlen);int setsockopt(int sockfd, int level, int optname, const void *optval, socklen_t *optlen);

Both return: 0 if OK, -1 on error

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

51

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket OptionsGeneric Socket OptionsGeneric Socket OptionsGeneric Socket Options

โ€ข SO_BROADCASTโ€“ enable/disable the ability of the processto send broadcast messagesโ€“ supported for only datagram socketsโ€“ broadcast message ๊ฐœ๋…์„ ์ง€์›ํ•˜๋Š” ๋„คํŠธ์› (Ethernet, Token ring ๋“ฑ ) ์—์„œ๋งŒ ์ง€์›๋จ

โ€“ ์ด ์˜ต์…˜์ด ์„ธํŒ…๋˜์–ด ์žˆ์ง€ ์•Š์„ ๊ฒฝ์šฐ , destination address ๊ฐ€ broadcast address ์ด๋ฉด EACCES ๋ฆฌํ„ด๋จ

โ€ข SO_DEBUGโ€“ TCP ์—์„œ๋งŒ ์ง€์›โ€“ ์ปค๋„์ด TCP ์— ์˜ํ•ด ๋ณด๋‚ด๊ณ  / ๋ฐ›๋Š” ๋ชจ๋“  ํŒจํ‚ท๋“ค์— ๋Œ€ํ•œ ์ƒ์„ธ ์ •๋ณด๋ฅผ ci

rcular buffer ์— ๊ธฐ๋กโ€“ trpt program ์œผ๋กœ ๋‚ด์šฉ ์กฐ์‚ฌ ๊ฐ€๋Šฅโ€ฆ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

52

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

โ€ข SO_DONTROUTEโ€“ ๋ผ์šฐํŒ… ํ…Œ์ด๋ธ”์„ ๊ฑด๋„ˆ๋›ฐ๊ฒŒ ํ•จโ€“ destination ์ด point-to-point link๋‚˜ , shared network ์ด ์•„๋‹Œ ๊ฒฝ์šฐ์—๋Š”

ENETUNREACH๊ฐ€ ๋ฆฌํ„ด๋จโ€“ ๊ฐ๊ฐ์˜ datagram ์— MSG_DONTROUTE flag ๋ฅผ ์„ธํŒ…ํ•˜์—ฌ send/sendt

o/sendmsg ํ•จ์ˆ˜๋กœ ๋ณด๋‚ด๋Š” ๊ฒƒ๊ณผ ๋™์ผโ€ข SO_ERROR

โ€“ pending error ๋ฐœ์ƒ์‹œ ์—๋Ÿฌ ๊ฐ’ (Exxx) ์„ ์–ป์–ด์˜ค๊ธฐ ์œ„ํ•จโ€“ pending error ๊ฐ€ ์ธ์ง€๋˜๋Š” 2 ๊ฐ€์ง€ ๋ฐฉ๋ฒ•

โ€  select call ์—์„œ block ๋˜์–ด ์žˆ๋‹ค๊ฐ€ โ€“ 1 ๊ฐ’์œผ๋กœ return ํ•จโ€  signal-driven I/O ์ธ ๊ฒฝ์šฐ์—๋Š” SIGIO ์‹œ๊ทธ๋„์ด ๋ฐœ์ƒํ•จ

โ€“ getsockopt ์— ์˜ํ•ด ๋ฆฌํ„ด๋˜๋Š” ์ •์ˆ˜ ๊ฐ’์ด socket ์— ๋Œ€ํ•œ pending error์ด๊ณ  , 1ํšŒ ํ˜ธ์ถœ ํ›„ ์ปค๋„ ๋‚ด์˜ so_error ์˜ ๊ฐ’์€ 0 ์œผ๋กœ ๋ฆฌ์…‹๋จ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

53

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

โ€ข SO_KEEPALIVEโ€“ ์ด ์˜ต์…˜์ด ์„ธํŒ…๋˜์–ด ์žˆ๋Š” ๊ฒฝ์šฐ , ํ•œ ๋ฐฉํ–ฅ์œผ๋กœ 2 ์‹œ๊ฐ„ ๋™์•ˆ ๋ฐ์ดํ„ฐ๊ฐ€ ์ „์†ก๋˜์ง€

์•Š๋Š” ๊ฒฝ์šฐ TCP ๊ฐ€ ์ž๋™์œผ๋กœ keepalive probe ๋ฅผ ์ „์†ก1. ์ƒ๋Œ€๋ฐฉ์œผ๋กœ๋ถ€ํ„ฐ ๊ธฐ๋Œ€ํ•œ ACK ๋ฅผ ๋ฐ›์Œ : Everything is OK!2. ์ƒ๋Œ€๋ฐฉ์œผ๋กœ๋ถ€ํ„ฐ RST ๋ฅผ ๋ฐ›์Œ : ์ƒ๋Œ€ํŽธ ํ˜ธ์ŠคํŠธ๊ฐ€ crashํ›„ reboot ๋จ . pending error

๊ฐ€ ECONNRESET ์œผ๋กœ ์„ธํŒ…๋˜๊ณ  ์†Œ์ผ“์ด ๋‹ซํž˜3. ์ƒ๋Œ€๋ฐฉ์œผ๋กœ๋ถ€ํ„ฐ ์‘๋‹ต์„ ๋ฐ›์ง€ ๋ชปํ•จ : 75 ์ดˆ๋งˆ๋‹ค 8ํšŒ์˜ probe ๋ฅผ ๋‹ค์‹œ ๋ณด๋ƒ„ . ์ฒซ pro

be ๋กœ๋ถ€ํ„ฐ 11๋ถ„ 15 ์ดˆ๊ฐ„ ์‘๋‹ต์ด ์—†์œผ๋ฉด , pending error ๊ฐ€ ETIMEDOUT ์œผ๋กœ ์„ธํŒ…๋˜๊ณ  , ์†Œ์ผ“์ด ๋‹ซํž˜

โ€“ KEEPALIVE ํŒŒ๋ผ๋ฏธํ„ฐ๋ฅผ ์ˆ˜์ • ?โ€  TCP_KEEPALIVE ์˜ต์…˜ : ๊ตฌํ˜„๋˜์ง€ ์•Š์€ ๊ฒฝ์šฐ๊ฐ€ ๋งŽ์Œโ€  TCPv1 ์˜ Appendix E (pp. 530-535): socket ๋ณ„๋กœ ์„ค์ •์€ ๋ถˆ๊ฐ€๋Šฅ

# ndd /dev/tcp tcp_keepalive_interval7200000 default is 7200000 ms (2 hours)# ndd โ€“set /dev/tcp tcp_keepalive_interval value

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

54

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

โ€ข SO_LINGERโ€“ Connection oriented protocol ์—์„œ close function ์ด ์ž‘๋™ํ•˜๋Š”

๋ฐฉ๋ฒ•์„ ๋ช…์‹œํ•จ struct linger { int l_onoff; /* 0=off, nonzero=on */ int l_linger; /* linger time, units as seconds */

client serverdataFIN

ack of data and FIN

FIN

ack of data and FIN

writeclose

close returns

data queued by TCP

close

application reads queued data and FIN

client serverdataFIN

ack of data and FIN

FIN

ack of data and FIN

writeclose

close returns

data queued by TCP

close

application reads queued data and FIN

Default operation of close close with SO_LINGER option

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

55

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

โ€ข SO_OOBINLINEโ€“ out-of-band data ์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ : ์ด ์˜ต์…˜์ด ์„ธํŒ…๋˜์–ด ์žˆ์œผ๋ฉด OOB data ๋ฅผ no

rmal input queue ์— ๋‘ โ€ข SO_RCVBUF / SO_SNDBUF

โ€“ ๊ฐ ์†Œ์ผ“์˜ send buffer ์™€ receive buffer ์˜ ํฌ๊ธฐ๋ฅผ ์กฐ์ ˆโ€“ receive buffer ์˜ ํฌ๊ธฐ๋Š” TCP ์˜ flow control ์— ํ•„์š”

โ€ข SO_RCVLOWAT / SO_SNDLOWATโ€“ select function ์—์„œ ์‚ฌ์šฉ๋˜๋Š” receive/send low-water mark ๊ฐ’์„ ์„ค์ •ํ•จโ€“ receive low-water mark ์˜ default ๊ฐ’์€ 1โ€“ send low-water mark ์˜ default ๊ฐ’์€ 2048

โ€ข SO_RCVTIMEO / SO_SNDTIMEOโ€“ send/receive ์‹œ์˜ ํƒ€์ž„์•„์›ƒ ๊ฐ’์„ ์„ค์ •โ€“ receive timeout affects: read, readv, recv, recvfrom, recvmsgโ€“ send timeout affects: write, writev, send, sendto, sendmsg

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

56

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

โ€ข SO_REUSEADDR / SO_REUSEPORTโ€“ SO_REUSEADDR ์˜ต์…˜์€ 4 ๊ฐ€์ง€์˜ ๋‹ค๋ฅธ ์šฉ๋„๋กœ ์‚ฌ์šฉ๋จ

1. ํ•œ ํฌํŠธ๋กœ ์ „์— ์ฒด๊ฒฐ๋œ ์—ฐ๊ฒฐ์ด ์žˆ๋”๋ผ๋„ listening server ๊ฐ€ ๊ทธ ํฌํŠธ๋กœ binding ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•จ

์ด์™€ ๊ฐ™์€ ๊ฒฝ์šฐ SO_REUSEADDR ์˜ต์…˜์ด ์„ค์ •๋˜์–ด ์žˆ์ง€ ์•Š์œผ๋ฉด , (d) ๊ณผ์ •์—์„œ bind๊ฐ€ ์‹คํŒจํ•จ

2. ๊ฐ๊ฐ์˜ instance ๊ฐ€ ๋‹ค๋ฅธ ๋กœ์ปฌ IP ์ฃผ์†Œ๋กœ bind ํ•˜๋Š” ๊ฒฝ์šฐ , ๊ฐ™์€ ์„œ๋ฒ„์˜ ์—ฌ๋Ÿฌ ๊ฐœ์˜ instance ๊ฐ€ ์กด์žฌํ•  ์ˆ˜ ์žˆ๋„๋ก ํ—ˆ์šฉโ€ป TCP ์—์„œ completely duplicate binding ์€ ํ—ˆ์šฉ๋˜์ง€ ์•Š์Œ .

์‹œ๋‚˜๋ฆฌ์˜ค(a) listening server ๊ฐ€ ์‹œ์ž‘(b) ์—ฐ๊ฒฐ ์š”์ฒญ์ด ๋„์ฐฉํ•˜๊ณ  , ๊ทธ client ๋ฅผ ์ฒ˜๋ฆฌํ•  ์ž์‹ ํ”„๋กœ์„ธ์Šค๊ฐ€ ์ƒ์„ฑ๋จ(c) listening server ๊ฐ€ ์ข…๋ฃŒ๋˜๊ณ  , ์ž์‹ ํ”„๋กœ์„ธ์Šค๋Š” ๊ธฐ์กด ์—ฐ๊ฒฐ๋กœ ์„œ๋น„์Šค๋ฅผ ๊ณ„์†ํ•จ(d) listening server ๊ฐ€ ์žฌ์‹œ์ž‘

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

57

http://www.kwanghee.net/http://www.kwanghee.net/

Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)Generic Socket Options (contโ€™d)

3. ๊ฐ๊ฐ์˜ bind ๊ฐ€ ๋‹ค๋ฅธ ๋กœ์ปฌ IP ์ฃผ์†Œ๋ฅผ ์ง€์ •ํ•˜๋Š” ๊ฒฝ์šฐ , ํ•˜๋‚˜์˜ ํ”„๋กœ์„ธ์Šค๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ์†Œ์ผ“์„ ํ•˜๋‚˜์˜ ํฌํŠธ๋กœ binding ํ•˜๋„๋ก ํ•จ

4. UDP ์†Œ์ผ“์˜ ๊ฒฝ์šฐ completely duplicate binding ์„ ๊ฐ€๋Šฅํ•˜๋„๋ก ํ•จ

โ€“ SO_REUSEPORT (4.4BSD)โ€  multicasting ์— ๋Œ€ํ•œ ์ง€์›์ด ์ถ”๊ฐ€ (4.4BSD)โ€  ๊ฐ™์€ IP ์™€ ํฌํŠธ๋กœ binding ํ•˜๊ณ ์ž ํ•˜๋Š” ๋ชจ๋“  ์†Œ์ผ“์ด SO_REUSEPORT ์˜ต์…˜์„ ์„ธํŒ…ํ•œ ๊ฒฝ์šฐ , completely duplicate binding ์„ ํ—ˆ์šฉ

โ€  IP ์ฃผ์†Œ๊ฐ€ multicast address ์ด๋ฉด , SO_REUSEADDR ๋Š” SO_REUSEPORT์™€ ๋™์ผ

โ€ข SO_TYPEโ€“ ์†Œ์ผ“ ์ข…๋ฅ˜๋ฅผ ๋ฆฌํ„ดํ•จ (SOCK_STREAM, SOCK_DGRAM, etc)

โ€ข SO_USELOOPBACK (AF_ROUTE ์—์„œ๋งŒ ์‚ฌ์šฉ )โ€“ ์†Œ์ผ“์—์„œ ๋ณด๋‚ด์ง€๋Š” ๋ชจ๋“  ํŒจํ‚ท์˜ ์‚ฌ๋ณธ์„ ๋ฐ›๊ฒŒ ๋จ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

58

http://www.kwanghee.net/http://www.kwanghee.net/

fnctl / ioctlfnctl / ioctl Functions Functionsfnctl / ioctlfnctl / ioctl Functions Functions

Operation fnctl ioctl Routing socket

Posix.1g

set socket for nonblocking I/O F_SETFL, O_NONBLOCK FIONBIO fnctl

set socket for signal-driven I/O F_SETFL, O_ASYNC FIOASYNC fnctl

set socket owner F_SETOWNSIOCSPGRP or FIOSETOWN

fnctl

get socket owner F_GETOWNSIOCGPGRP or FIOGETOWN

fnctl

get #bytes in socket receive buffer FIONREAD

test for socket at out-of-bank mark SIOCATMARK sockatmark

obtain interface list SIOCGIFCONF sysctl

interface operations SIOC[GS]Ifxxx

ARP cache operations SIOCxARP RTM_xxx

routing table operations SIOCxxxRT RTM_xxx

โ€ข fnctl, ioctl, routing socket operation ์— ๋Œ€ํ•œ ์ •๋ฆฌ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

59

http://www.kwanghee.net/http://www.kwanghee.net/

fnctl fnctl ํ•จ์ˆ˜ ์‚ฌ์šฉ ์˜ˆํ•จ์ˆ˜ ์‚ฌ์šฉ ์˜ˆfnctl fnctl ํ•จ์ˆ˜ ์‚ฌ์šฉ ์˜ˆํ•จ์ˆ˜ ์‚ฌ์šฉ ์˜ˆ

โ€ข Nonblocking I/O ๋กœ ์„ค์ •ํ•˜๋Š” ์˜ˆint flags;

/* Set socket nonblocking */if ( (flags = fnctl (fd, F_GETFL, 0)) < 0 )

err_sys(โ€œF_GETFL errorโ€);flags |= O_NONBLOCK;if ( (fnctl(fd, F_SETFL, flags) < 0 )

err_sys(โ€œF_SETFL errorโ€);

โ€ข Nonblocking I/O ๋ฅผ ํ•ด์ œํ•˜๋Š” ์˜ˆโ€ฆโ€ฆflags &= ~O_NONBLOCK;if ( (fnctl(fd, F_SETFL, flags) < 0 )

err_sys(โ€œF_SETFL errorโ€);

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network Unix Network ProgrammingProgrammingUnix Network Unix Network ProgrammingProgramming

Chapter 8Elementary UDP Socket

UDP ๋„ค ์ง‘

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

61

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข recvfrom and sendto functionsโ€ข UDP Echo Server : main Functionโ€ข UDP Echo Server : dg_echo Functionโ€ข UDP Echo Client : main Functionโ€ข UDP Echo Client : dg_cli Functionโ€ข Lost Diagramsโ€ข Verifying Received Responseโ€ข Server Not Runningโ€ข Summary of UDP exampleโ€ข connect Function with UDPโ€ข dg_cli Function(Revisited)โ€ข Lack of Flow Control with UDPโ€ข Determining Outgoing Interface with UDPโ€ข TCP and UDP Echo Server Using selectโ€ข Summary

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

62

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข connectionless, unreliable, datagram protocol

UDP clientUDP Server

socket()

sendto()

recvfrom()

close()

socket()

bind()

recvfrom()

sendto()

blocks until datagram received from a client

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

63

http://www.kwanghee.net/http://www.kwanghee.net/

recvfromrecvfrom and and sendtosendto Functions Functionsrecvfromrecvfrom and and sendtosendto Functions Functions

โ€ข #include <sys/socket.h>

โ€ข ssized_t recvfrom(int sockfd, void *buff, size_T nbytes, int flags,

struct sockaddr *from, socklen_t *addrlen);

โ€ข ssized_t sendto(int sockfd, const void *buff, size_t nbytes, int flags,

const struct sockaddr *to, socklen_t addrlen);

both return : # of byte read or written if OK, -1 on error

13์žฅ์—์„œ ์„ค๋ช… . recv, send, recvmsg & sendmsg์šฐ์„  0 ์œผ๋กœ๋งŒ ์‚ฌ์šฉ

accept

connect

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

64

http://www.kwanghee.net/http://www.kwanghee.net/

UDP Echo ServerUDP Echo ServerUDP Echo ServerUDP Echo Server

1. #include "unp.h"2. int main(int argc, char **argv)3. { int sockfd;4. struct sockaddr_in servaddr, cliaddr;5. sockfd = Socket(AF_INET, SOCK_DGRAM, 0);6. bzero(&servaddr, sizeof(servaddr));7. servaddr.sin_family = AF_INET;8. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);9. servaddr.sin_port = htons(SERV_PORT);10. Bind(sockfd, (SA *) &servaddr, sizeof(servaddr));11. dg_echo(sockfd, (SA *) &cliaddr, sizeof(cliaddr)); }12. void dg_echo(int sockfd, SA *pcliaddr, socklen_t clilen){13. int n;14. socklen_t len;15. char mesg[MAXLINE];16. for ( ; ; ) {17. len = clilen;18. n = Recvfrom(sockfd, mesg, MAXLINE, 0, pcliaddr, &len);19. Sendto(sockfd, mesg, n, 0, pcliaddr, len);20. }}

Never terminatedIterative Server

SO_RCVBUF Socket Option

server

UDP

client

UDP

client

UDPdatatgram

socket received buffer

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

65

http://www.kwanghee.net/http://www.kwanghee.net/

UDP Echo ClientUDP Echo ClientUDP Echo ClientUDP Echo Client

1. #include "unp.h"2. int main(int argc, char **argv)3. {4. int sockfd;5. struct sockaddr_in servaddr;6. if (argc != 2)7. err_quit("usage: udpcli <IPaddress>");8. bzero(&servaddr, sizeof(servaddr));9. servaddr.sin_family = AF_INET;10. servaddr.sin_port = htons(SERV_PORT);11. Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);12. sockfd = Socket(AF_INET, SOCK_DGRAM, 0);13. dg_cli(stdin, sockfd, (SA *) &servaddr, sizeof(servaddr));14. exit(0);15. }16. void17. dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)18. {19. int n;20. char sendline[MAXLINE], recvline[MAXLINE + 1];21. while (Fgets(sendline, MAXLINE, fp) != NULL) {22. Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);23. n = Recvfrom(sockfd, recvline, MAXLINE, 0, NULL, NULL);24. recvline[n] = 0; /* null terminate */25. Fputs(recvline, stdout);26. } }

Not asked the kernel to assign

an ephemeral port to its socket

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

66

http://www.kwanghee.net/http://www.kwanghee.net/

Lost DatamgramsLost DatamgramsLost DatamgramsLost Datamgrams

โ€ข Our UDP client-server example is not reliable.โ€ข If a client is lost, the client will block forever in its call to recvfrom

in the function dg_cli, waiting for a server reply.โ€ข Only way to prevent this is to place a timeout on the clientโ€™s call t

o recvfrom.(13.2)โ€“ connent with a Timeout Using SIGALRMโ€“ recvfrom with a Timeout Using SIGALRM

โ€ข Reliability to a UDP client-server in 20.5 p542

์‹ ๋ขฐ

๋„

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

67

http://www.kwanghee.net/http://www.kwanghee.net/

Verifying Received ResponseVerifying Received ResponseVerifying Received ResponseVerifying Received Response

1. #include "unp.h"2. void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)3. {4. int n;5. char sendline[MAXLINE], recvline[MAXLINE + 1];6. socklen_t len;7. struct sockaddr *preply_addr;8. preply_addr = Malloc(servlen);9. while (Fgets(sendline, MAXLINE, fp) != NULL) {10. Sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen);11. len = servlen;12. n = Recvfrom(sockfd, recvline, MAXLINE, 0, preply_addr, &len);13. if (len != servlen || memcmp(pservaddr, preply_addr, len) != 0) {14. printf("reply from %s (ignored)\n",15. Sock_ntop(preply_addr, len));16. continue;17. }18. recvline[n] = 0; /* null terminate */19. Fputs(recvline, stdout);20. }21. }

์ž๋„จ ์•„๋‹ˆ๊ตฐ .

IF man

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

68

http://www.kwanghee.net/http://www.kwanghee.net/

Server Not RunningServer Not RunningServer Not RunningServer Not Running

โ€ข Asynchronous errorโ€“ errors that are reported some time after the packet was

sent.โ€“ ICMP port unreachableโ€“ TCP : always report these errors to the application.

๋„Œ ์—ฐ๊ฒฐ๋„ ์•ˆํ•˜๊ณ  ์“ฐ๋ƒ ?๊ทธ๋Ÿฌ๋‹ˆ๊น , ๊ทธ๋ ‡์ง€

๋ถˆ๋Ÿ‰ UDP client

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

69

http://www.kwanghee.net/http://www.kwanghee.net/

Connect Function with UDP(1)Connect Function with UDP(1)Connect Function with UDP(1)Connect Function with UDP(1)

โ€ข unconnected UDP Socketโ€“ the default when we create a UDP socket

โ€ข connected UDP Socketโ€“ the result of calling connect on a UDP socket

1. Does not use sendto but use write or send instead.

2. Does not use recvfrom but use read or recv instead.3. Asynchronous errors are returned to the process for a connected UDP

socket. The corollary, as we previously described, is that an unconnected UDP socket does not receive any asynchronous errors

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

70

http://www.kwanghee.net/http://www.kwanghee.net/

connect Function with UDP(2)connect Function with UDP(2)connect Function with UDP(2)connect Function with UDP(2)

application

UDP

peer

UDPstores peer IP addressand port# from connect

UDP datagram

UDP datagram

read write

UDP datagram fromsome other IP addr and /or port #

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

71

http://www.kwanghee.net/http://www.kwanghee.net/

dg_client Functiondg_client Functiondg_client Functiondg_client Function

1. #include "unp.h"

2. void3. dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen)4. {5. int n;6. char sendline[MAXLINE], recvline[MAXLINE + 1];

7. Connect(sockfd, (SA *) pservaddr, servlen);

8. while (Fgets(sendline, MAXLINE, fp) != NULL) {

9. Write(sockfd, sendline, strlen(sendline));

10. n = Read(sockfd, recvline, MAXLINE);

11. recvline[n] = 0; /* null terminate */12. Fputs(recvline, stdout);13. }14. }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

72

http://www.kwanghee.net/http://www.kwanghee.net/

Lack of Flow Control with UDPLack of Flow Control with UDPLack of Flow Control with UDPLack of Flow Control with UDP

โ€ข UDP has no flow control and unreliableโ€“ ex) UDP sender to overrun the receiver.

โ€ข UDP Socket Receive Bufferโ€“ can change receive Buffer : SO_RCVBUFโ€“ default : 41,600 bytes(BSD/OS)

โ€  actual limit : 246,723 bytes

Buffer ๊ฐ€ ๋‹ค ์ฐผ์–ด์—ฌ

~~UDP buffer ํ˜ธ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

73

http://www.kwanghee.net/http://www.kwanghee.net/

TCP and UDP Echo Server Using TCP and UDP Echo Server Using selectselectTCP and UDP Echo Server Using TCP and UDP Echo Server Using selectselect

1. int main(int argc, char **argv) {2. int listenfd, connfd, udpfd, nready, maxfdp1;3. char mesg[MAXLINE];4. pid_t childpid;5. fd_set rset;6. ssize_t n;7. socklen_t len;8. const int on = 1;9. struct sockaddr_in cliaddr, servaddr;10. void sig_chld(int);11. /* create listening TCP socket */12. listenfd = Socket(AF_INET, SOCK_STREAM, 0);13. bzero(&servaddr, sizeof(servaddr));14. servaddr.sin_family = AF_INET;15. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);16. servaddr.sin_port = htons(SERV_PORT);17. Setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(o

n));18. Bind(listenfd, (SA *) &servaddr, sizeof(servaddr));19. Listen(listenfd, LISTENQ);20. /* create UDP socket */21. udpfd = Socket(AF_INET, SOCK_DGRAM, 0);22. bzero(&servaddr, sizeof(servaddr));23. servaddr.sin_family = AF_INET;24. servaddr.sin_addr.s_addr = htonl(INADDR_ANY);25. servaddr.sin_port = htons(SERV_PORT);26. Bind(udpfd, (SA *) &servaddr, sizeof(servaddr));

28. /* include udpservselect02 */29. Signal(SIGCHLD, sig_chld); /* must call waitpid() */30. FD_ZERO(&rset);31. maxfdp1 = max(listenfd, udpfd) + 1;32. for ( ; ; ) {33. FD_SET(listenfd, &rset);34. FD_SET(udpfd, &rset);35. if ( (nready = select(maxfdp1, &rset, NULL, NULL, NULL)) < 0) {36. if (errno == EINTR) continue; /* back to for() */37. else err_sys("select error"); }38. if (FD_ISSET(listenfd, &rset)) {39. len = sizeof(cliaddr);40. connfd = Accept(listenfd, (SA *) &cliaddr, &len);41. if ( (childpid = Fork()) == 0) { /* child process */42. Close(listenfd); /* close listening socket */43. str_echo(connfd); /* process the request */44. exit(0); }45. Close(connfd); /* parent closes connected socket */ }46. if (FD_ISSET(udpfd, &rset)) {47. len = sizeof(cliaddr);48. n = Recvfrom(udpfd, mesg, MAXLINE, 0, (SA *) &cliaddr, &len);49. Sendto(udpfd, mesg, n, 0, (SA *) &cliaddr, len);50. }51. }52. }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

74

http://www.kwanghee.net/http://www.kwanghee.net/

/etc/services /etc/services ์ค‘์—์„œ์ค‘์—์„œ/etc/services /etc/services ์ค‘์—์„œ์ค‘์—์„œ

โ€ข tcpmux 1/tcpโ€ข echo 7/tcpโ€ข echo 7/udpโ€ข discard 9/tcp sink nullโ€ข discard 9/udp sink nullโ€ข systat 11/tcp usersโ€ข daytime 13/tcpโ€ข daytime 13/udpโ€ข netstat 15/tcpโ€ข chargen 19/tcp ttytst sourceโ€ข chargen 19/udp ttytst sourceโ€ข ftp-data 20/tcpโ€ข ftp 21/tcpโ€ข telnet 23/tcpโ€ข smtp 25/tcp mailโ€ข time 37/tcp timserverโ€ข time 37/udp timserverโ€ข name 42/udp nameservername 42/udp nameserverโ€ข whois 43/tcp nicname # usually to sri-nicโ€ข domain 53/udpโ€ข domain 53/tcpโ€ข bootps 67/udp # BOOTP/DHCP serverโ€ข bootpc 68/udp # BOOTP/DHCP client

1 port ์—UDP/TCP ๋™์‹œ์—

์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ƒ๊ฐ๋ณด๋‹ค ๋งŽ๊ตฐ

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network Unix Network ProgrammingProgrammingUnix Network Unix Network ProgrammingProgramming

Chapter 9.

Elementary Name and Address Conversions

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

76

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข Domain Name Systemโ€ข gethostbyname Functionsโ€ข RES_USE_INET6 Resolver Optionโ€ข gethostbyname2 Function and IPV6 Supportโ€ข gethostbyaddr Functionโ€ข uname Functionโ€ข gethostname Functionโ€ข getservbyname and getservbyport Functionsโ€ข Other Networking Informationโ€ข Summary

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

77

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข So far, we used numeric addresses for the hostโ€ข User names instead of numbers for numerous reasons

โ€“ names are easier to rememberโ€  gethostbyname, gethostbyaddr (hostnames -> IP addr)โ€  getservbyname, getservbyport(service names -> port )

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

78

http://www.kwanghee.net/http://www.kwanghee.net/

Domain Name SystemDomain Name SystemDomain Name SystemDomain Name System

โ€ข DNS is used primarily to map between hostnames and IP addresses.

โ€ข Resource Recordsโ€“ A : 32bit IPv4 addressโ€“ AAAA : 128bit IPv6 addressโ€“ PTR : pointer recordsโ€“ MX : mail exchangerโ€“ CNAME : canonical name (ftp, www,..)

A ์™€ CNAME ๋งŒ ์•Œ๋ฉด ๋˜์—ฌ .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

79

http://www.kwanghee.net/http://www.kwanghee.net/

Typical arrangement of clients, resolvers, and name serversTypical arrangement of clients, resolvers, and name serversTypical arrangement of clients, resolvers, and name serversTypical arrangement of clients, resolvers, and name servers

application

resolver code

functioncall

functionreturn

resolverconfiguration

files

localname server

othernameserver

UDP request

UDP reply

๊ฑฐ 114์ฃ  ?

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

80

http://www.kwanghee.net/http://www.kwanghee.net/

gethostbynamegethostbyname function functiongethostbynamegethostbyname function function

โ€ข #include <netdb.h>โ€ข struct hostent *gethostbyname(const char *hostname);

Returns : nonull pointer if OK, NULL on error with h_errorno set

โ€ข #include <netdb.h>โ€ข struct hostent *gethostbyname(const char *hostname);

Returns : nonull pointer if OK, NULL on error with h_errorno set

struct hotent {

char *h_name;

char **h_aliases;

int h_addrtype;

int h_length;

char **h_addr_list;

};

#define h_addr h_addr_list[0];

page 242 ๋ฅผ ๋ณด์‹œ๋ฉด , ๊ตฌ์กฐ์ฒด๊ฐ€ ์–ด๋–ป๊ฒŒ์ƒ๊ฒผ๋Š”์ง€ ์•Œ ์ˆ˜

์žˆ์Šด๋‹ค .IPv6 ์šฉ 9.4, 9.5์ ˆ์€

๊ด€์‹ฌ์žˆ๋Š” ๋ถ„์€๊ฐœ๋ณ„์ ์œผ๋กœ ์ฝ์–ด๋ณด์„ธ์—ฌ .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

81

http://www.kwanghee.net/http://www.kwanghee.net/

gethostbyaddrgethostbyaddr Function / Function /uname Functionuname Functiongethostbyaddrgethostbyaddr Function / Function /uname Functionuname Function

โ€ข #include <netdb.h>โ€ข struct hostent *gethostbyaddr(const char *addr, size_t len, int family)

Returns : nonull pointer if OK, NULL on error with h_errno set

AF_INET or

AF_INET6

โ€ข #include <sys/utsname.h>โ€ข int uname(struct utsname *name)

Returns : nonnegative value is OK, -1 on error#define _UTS_NAMESIZE 16#define _UTS_NODESIZE 256struct utsname{

char sysname[_UTS_NAMESIZE]; /* os name */char nodename[_UTS_NODESIZE]; /* node name */char nodename[_UTS_NODESIZE]; /* node name */char release[_UTS_NAMESIZE]; /* O.S. release level */char version[_UTS_NAMESIZE]; /* O.S. version level */char machine[_UTS_NAMESIZE]; /*hardware type */

}

uname() ํ•จ์ˆ˜๋กœ local

IP ๋Š” ์•Œ์ˆ˜์žˆ๊ตฐ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

82

http://www.kwanghee.net/http://www.kwanghee.net/

getservbyname / getservbyportgetservbyname / getservbyportgetservbyname / getservbyportgetservbyname / getservbyport

โ€ข /etc/services ์„ ์ฐธ์กฐํ•ด์„œ , local machine ์˜ ์ œ๊ณต๋˜๋Š” server ์˜ ์ด๋ฆ„์ด๋‚˜ , ๊ทธ๊ฒƒ์ด ์‚ฌ์šฉํ•˜๋Š” port ๋ฅผ ์ถœ๋ ฅํ•ด์ค€๋‹ค .

Information Data file Structure keyed lookup function

hosts /etc/hosts hostent gethostbyaddr, gethostbyname

networks /etc/networks netentgetnetbyaddr,getnetbyname

protocols /etc/protocols protoentgetprotobyname,getprotobynumber

services /etc/services serventgetservbyname,getservbyport

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

83

http://www.kwanghee.net/http://www.kwanghee.net/

SummarySummarySummarySummary

โ€ข resolverโ€“ to convert a hostname into an IP address and vice v

ersaโ€ข gethostbyname / getthostbyaddr

โ€“ IPV6 ์šฉ : gethostname2(), RES_USE_INET6โ€ข getservbyname

โ€“ commonly used function dealing with services names and port

๋‹ค์Œ๋ถ€ํ„ฐ๋Š”Advanced Socket Part์ž„๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

84

http://www.kwanghee.net/http://www.kwanghee.net/

UNIX Network Programming( chap 10 - chap 11 )

UNIX Network Programming( chap 10 - chap 11 )

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

85

http://www.kwanghee.net/http://www.kwanghee.net/

IPv4 and IPv6 Interoperability ( chap.10 )

โ˜ž IPv6 Server on dual-stack host

โ˜ž Processing of sever on dual-stack host

โ˜ž Dual stack host

โ˜ž Processing of client requests

โ˜ž IPv4-mapped IPv6

Agenda

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

86

http://www.kwanghee.net/http://www.kwanghee.net/

Advanced Name and Address Conversions ( chap.11 )

โ˜ž Why use getaddrinfo( ) & getnameinfo( ) ?

โ˜ž getaddrinfo( )

โ˜ž Action and Result of getaddrinfo( )

โ˜ž getnameinfo( )

โ˜ž Reentrant functions

Agenda

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

87

http://www.kwanghee.net/http://www.kwanghee.net/

IPv6client

TCP

IPv6

datalink

IPv4client

TCP

IPv4

datalink

IPv6server

TCP

IPv4 IPv6

datalink

Enethdr

IPv4hdr

TCPhdr

TCPdata

Enethdr

IPv4hdr

TCPhdr

TCPdata

type0800

dport8888

dport8888

type86dd

Enethdr

IPv4hdr

TCPhdr

TCPdata

Enethdr

IPv4hdr

TCPhdr

TCPdata

type0800

dport8888

dport8888

type86dd

IPv4-mapped IPv6 address

206.62.226.4251f1b:df00:ce3e:e20020:8000:2b37:6426

IPv6 address

IPv6 listening socket,bound to 0::0, port 8888

IPv6 Server on dual-stack host

IPv4 frame์ž„์„์•Œ๋ ค์ค€๋‹ค .

IPv6 frame ์ž„์„์•Œ๋ ค์ค€๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

88

http://www.kwanghee.net/http://www.kwanghee.net/

TCP UDP

IPv4 IPv6

AF_INETSOCK_STREAMsockaddr_in

AF_INET6SOCK_STREAMsockaddr_in6

AF_INET6SOCK_DGRAMsockaddr_in6

AF_INETSOCK_DGRAMsockaddr_in

IPv4 datagram IPv6 datagram

IPv6IPv4IPv4

IPv6 IPv4

IPv4-mappedIP

v4-

map

ped

addressreturned byaccept orrecvfrom

IPv6 sockets

IPv4 sockets

Processing of server on dual-stack host

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

89

http://www.kwanghee.net/http://www.kwanghee.net/

Dual-stack host

Listening socket rules

1. A listening IPv4 socket can accept incoming connections from only IPv4 clients.

2. If a server has a listening IPv6 socket that has bound the wildcard address, that socket can accept incoming connections from either IPv4 clients or IPv6 clients. For a connection from an IPv4 client the serverโ€™s local address for the connections will be the corresponding IPv4-mapped IPv6 address.

3. If a server has a listening IPv6 socket that has bound an IPv6 address other than an IPv4-mapped IPv6 address, that socket can accept incoming connections from IPv6 clients only

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

90

http://www.kwanghee.net/http://www.kwanghee.net/

TCP UDP

IPv4 IPv6

AF_INETSOCK_STREAMsockaddr_in

AF_INET6SOCK_STREAMsockaddr_in6

AF_INET6SOCK_DGRAMsockaddr_in6

AF_INETSOCK_DGRAMsockaddr_in

IPv4 datagram IPv6 datagram

IPv6IPv4IPv4

IPv6 IPv4

IPv4-mappedIP

v4-

map

p ed

address forconnect or

sendto

IPv6 sockets

IPv4 sockets

Processing of client requests

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

91

http://www.kwanghee.net/http://www.kwanghee.net/

IPv6 server

IPv4 IPv4-mapped IPv6 : kernel ์— ์˜ํ•ด์„œ ์ˆ˜ํ–‰๋œ๋‹ค .accept ๋˜๋Š” recvfrom ์— ์˜ํ•ด์„œ application ์œผ๋กœ ํˆฌ๋ช…ํ•˜๊ฒŒ ์ „๋‹ฌ๋œ๋‹ค .

IPv6 client

IPv6 IPv4-mapped IPv6 : resolver ์— ์˜ํ•ด์„œ ์ˆ˜ํ–‰๋œ๋‹ค .( resolver ex: gethostbyname, gethostbyaddr etc )application ์— ์˜ํ•ด connect ๋˜๋Š” sendto ๋กœ ํˆฌ๋ช…ํ•˜๊ฒŒ ์ „๋‹ฌ๋œ๋‹ค .

IPv4-mapped IPv6

DNS records example

solaris IN A 206.62.226.33 IN AAAA 5f1b:df00:c33e:e200:0020:0800:2078:e3e3

aix IN A 206.62.226.43 IN A 5f1b:df00:c33e:e200:0020:0800:5afc:2b36

bsdi2 IN A 206.62.226.34

IPv4-mapped IPv6 address example

return address - 0::ffff:206.62.226.34

DNS records example

solaris IN A 206.62.226.33 IN AAAA 5f1b:df00:c33e:e200:0020:0800:2078:e3e3

aix IN A 206.62.226.43 IN A 5f1b:df00:c33e:e200:0020:0800:5afc:2b36

bsdi2 IN A 206.62.226.34

IPv4-mapped IPv6 address example

return address - 0::ffff:206.62.226.34

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

92

http://www.kwanghee.net/http://www.kwanghee.net/

Summary of interoperability

IPv4 severIPv4-only host

(A only)

IPv6 severIPv6-only host(AAAA only)

IPv4 severdual-stack host(A and AAAA)

IPv6 severdual-stack host(A and AAAA)

IPv4 client, IPv4-only host

IPv6 client, IPv6-only host

IPv4 client, dual-stack host

IPv6 client, dual-stack host

IPv4 X IPv4 IPv4

X IPv6 X IPv6

IPv4 X IPv4 IPv4

IPv4 IPv6 X* IPv6

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

93

http://www.kwanghee.net/http://www.kwanghee.net/

Why use getaddrinfo( ) & getnameinfo( ) ?

gethostbyname( ) ๊ณผ gethostbyaddr( ) ์€ protocol ์— ์˜์กด์ ์ด๋‹ค .

address family ๋ฅผ ์ธ์ˆ˜๋กœ์„œ ๊ฐ€์ง„๋‹ค .

int getaddrinfo( const char *hostname, const char *service, const struct addrinfo *hints, struct addrinfo **result );

int getnameinfo( const struct sockaddr *sockaddr, socklen_t addrlen, char *host, size_t hostlen, char *serv, size_t servlen, int flags );

Because of !!protocol independence

of our application

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

94

http://www.kwanghee.net/http://www.kwanghee.net/

getaddrinfo( )

hostname : host name or address string

service : service name or decimal port number string

struct addrinfo { // define at <netdb.h>

int ai_flags; /* AI_PASSIVE, AI_CANONNAME */

int ai_family; /* AF_xxx */

int ai_socktype; /* SOCK_xxx */

int ai_protocol; /* 0 or IPPROTO_xxx, TCP or UDP */

size_t ai_addrlen; /* length of ai_addr, IPv4:16, IPv6:24 */

char *ai_canonname; /* ptr to canonical name for host */

struct sockaddr *ai_addr; /* ptr to socket address structure */

struct addrinfo *ai_next; /* ptr to next structure in linked list */

};

struct addrinfo hints, *res;

bzero( &hints, sizeof(hints) );

hints.ai_flags = AI_CANONNAME;

hints.ai_family = AF_INET;

getaddrinfo( โ€œbdsiโ€, โ€œdomainโ€, &hints, &res );

Ex)์˜ˆ๋ฅผ๋ด…์‹œ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

95

http://www.kwanghee.net/http://www.kwanghee.net/

ai_f

lags

ai_f

amil

yai

_soc

ktyp

eai

_pro

toco

lai

_add

rlen

ai_c

anon

nam

eai

_add

rai

_nex

t

addr

info

{}

ai_f

lags

ai_f

amil

yai

_soc

ktyp

eai

_pro

toco

lai

_add

rlen

ai_c

anon

nam

eai

_add

rai

_nex

t

addr

info

{}

ai_f

lags

ai_f

amil

yai

_soc

ktyp

eai

_pro

toco

lai

_add

rlen

ai_c

anon

nam

eai

_add

rai

_nex

t

addr

info

{}

ai_f

lags

ai_f

amil

yai

_soc

ktyp

eai

_pro

toco

lai

_add

rlen

ai_c

anon

nam

eai

_add

rai

_nex

t

addr

info

{}

sock

addr

_in{

}

sock

addr

_in{

}

sock

addr

_in{

}

sock

addr

_in{

}

bsdi

.koh

ala.

com

\0

๋‘๊ฐœ์˜ IP address ๊ฐ€์ง„ ๊ฒฝ์šฐ์˜ ๊ฒฐ๊ณผ

16,A

F_IN

ET

,53

206.

62.2

26.3

5

16,A

F_IN

ET

,53 20

6.62

.226

.35 16

,AF_

INE

T,5

3 206.

62.2

26.6

6 16,A

F_IN

ET

,53 20

6.62

.226

.66

SOC

K_S

TR

EA

MA

F_IN

ET

0 16 NU

LL

SOC

K_S

TR

EA

MA

F_IN

ET

0 16 SOC

K_S

TR

EA

MA

F_IN

ET

0 16 NU

LL

SOC

K_S

TR

EA

MA

F_IN

ET

0 16 NU

LL

NU

LL

res:

dyna

mic

ally

all

ocat

ed b

y ge

tadd

rinf

o

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

96

http://www.kwanghee.net/http://www.kwanghee.net/

Action and Result of getaddrinfo( )

Hostnamespecifiedby caller

Address familyspecifiedby caller

Hostnamestring

containsResult Action

hostname

hex string

dotted decimal

all AAAA records returned as sockaddr_in6{}sand all A records returned as sockaddr_in{}s

two DNS searches :gethostbyname2(AF_INET6) with RES_USE_INET6 offgethostbyname2(AF_INET) with RES_USE_INET6 off

one sockaddr_in6{} inet_pton(AF_INET6)

one sockaddr_in{} inet_pton(AF_INET)

AF_UNSPEC

hostname

hex string

dotted decimal

all AAAA records returned as sockaddr_in6{}selse all A records returned as IPv4-mapped IPv6 as sockaddr_in{}s

gethostbyname() with RES_USE_INET6 on

one sockaddr_in6{} inet_pton(AF_INET6)

error : EAI_ADDRFAMILY

AF_INET6

hostname

hex string

dotted decimal

all A records returned as sockaddr_in{}s

gethostbyname() with RES_USE_INET6 off

error : EAI_ADDRFAMILY

one sockaddr_in{} inet_pton(AF_INET)

AF_INET

nonnull hostname string; active or passive

Continue ...

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

97

http://www.kwanghee.net/http://www.kwanghee.net/

Hostnamespecifiedby caller

Address familyspecifiedby caller

Hostnamestring

containsResult Action

implied 0::0implied 0.0.0.0

implied 0::0

implied 0.0.0.0

one sockaddr_in6{}s andone sockaddr_in{}s

inet_pton(AF_INET6)inet_pton(AF_INET)

one sockaddr_in6{} inet_pton(AF_INET6)

one sockaddr_in{} inet_pton(AF_INET)

AF_UNSPECnull hostname string; passive

AF_INET6

AF_INET

implied 0::1implied 127.0.0.1

implied 0::1

implied 127.0.0.1

one sockaddr_in6{}s andone sockaddr_in{}s

inet_pton(AF_INET6)inet_pton(AF_INET)

one sockaddr_in6{} inet_pton(AF_INET6)

one sockaddr_in{} inet_pton(AF_INET)

AF_UNSPEC

AF_INET6

AF_INET

null hostname string; active

getaddrinfo( ) ์™€ getnameinfo( ) ์˜ ๊ตฌํ˜„์€

text ์˜ 11.16์ ˆ์„ ์ฐธ๊ณ ํ•ด ์ฃผ์„ธ์š” .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

98

http://www.kwanghee.net/http://www.kwanghee.net/

getnameinfo( )

Socket address ๋ฅผ ๊ฐ€์ง€๊ณ  host ์™€ service ์— ๋Œ€ํ•œ string ์„ ๊ฐ๊ฐ ๋Œ๋ ค์ค€๋‹ค .

DNS ์™€ ๋ฌด๊ด€ํ•˜๊ฒŒ ๋‚˜ํƒ€๋‚ผ ์ˆ˜ ์žˆ๋Š” IP address( IPv4 ์—์„œ๋Š” dotted decimal, IPv6 ์—์„œ๋Š” hex string) ์™€

port number ๋ฅผ ๋Œ๋ ค์ค€๋‹ค .

host ์™€ service ์— ๋Œ€ํ•œ name or numeric ๊ฐ’์„ ๋Œ๋ ค์ค€๋‹ค .

sock_ntop

getnameinfo

Constant Description

NI_DGRAMNI_NAMEREQDNI_NOFQDNNI_NUMERICHOSTNI_NUMERICSERV

inform datagram servicereturn an error if name cannot be resolved from addressreturn only hostname portion of FQDNreturn numeric string for hostnamereturn numeric string for service name

< flags for getnameinfo( ) >

๋‘˜๋‹ค protocolindependenceํ•˜์ง€๋งŒ โ€ฆ !

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

99

http://www.kwanghee.net/http://www.kwanghee.net/

Reentrant Functions (1)

static struct hostent host; /* result stored here */

struct hostent *gethostbyname( const char *hostname ){ return( gethostbyname2( hostname, family ) );}

struct hostent *gethostbyname2( const char *hostname, int family ){ /* call DNS functions for A or AAAA query */ /* fill in host structure */ return( &host );}

struct hostent *gethostbyaddr( const char *addr, size_t len, int family ){ /* call DNS functions for PTR query in in-addr.arpa domain */ /* fill in host structure */ return( &host );}

์ด static ๋ณ€์ˆ˜ (host) ์˜๊ณต์œ ๋กœ ์ธํ•˜์—ฌ ๋ฌธ์ œ๊ฐ€

๋ฐœ์ƒ๋  ์ˆ˜ ์žˆ๋‹ค .

์ด static ๋ณ€์ˆ˜ (host) ์˜๊ณต์œ ๋กœ ์ธํ•˜์—ฌ ๋ฌธ์ œ๊ฐ€

๋ฐœ์ƒ๋  ์ˆ˜ ์žˆ๋‹ค .

Problem Problem

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

100

http://www.kwanghee.net/http://www.kwanghee.net/

Reentrant Functions (2)

Method Method

1. static structure ๋ฅผ ์ฑ„์šฐ๊ณ  ๋Œ๋ ค์ฃผ๋Š” ๋Œ€์‹ ์— , ํ˜ธ์ถœ์ž๋Š” structure ์— ๋Œ€ํ•œ memory ๋ฅผ ๋จผ์ € ํ• ๋‹นํ•˜๊ณ  reentrant function ์ด ํ˜ธ์ถœ์ž์˜ ๊ตฌ์กฐ๋ฅผ ์ฑ„์šด๋‹ค .

- getnameinfo ๊ฐ€ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ๋ฒ•

- ๊ธฐ๋ฒ•์ด ์•„์ฃผ ๋ณต์žกํ•˜๊ณ  ๋งŽ์€ ๋‹ค๋ฅธ ์ •๋ณด๋ฅผ ์‚ฌ์šฉํ•˜๊ณ  ๊ด€๋ฆฌํ•ด์•ผ ํ•œ๋‹ค .

2. reentrant function ์€ malloc ์„ ํ˜ธ์ถœํ•˜์—ฌ memory ๋ฅผ ๋™์ ์œผ๋กœ ํ• ๋‹นํ•œ๋‹ค .

- getaddrinfo ๊ฐ€ ์‚ฌ์šฉํ•˜๋Š” ๊ธฐ๋ฒ•

- ๋™์ ์œผ๋กœ ํ• ๋‹น๋œ memory ๋ฅผ ํ•ด์ œํ•˜๊ธฐ ์œ„ํ•ด์„œ freeaddrinfo() ๋ฅผ ํ˜ธ์ถœํ•ด์„œ ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ถœ์„ ๋ฐฉ์ง€ํ•ด์•ผ ํ•œ๋‹ค .

๋‘˜ ๋‹ค ๋ฌธ์ œ์ ์€๋‚จ์•„์žˆ๊ตฐโ€ฆ ..chap 23 ์—์„œ๋‹ค์‹œ ๋ณด์ž ~!

Continue example โ€ฆ.

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

101

http://www.kwanghee.net/http://www.kwanghee.net/

#include <netdb.h>

struct hostent *gethostbyname_r( const char *hostname, struct hostent *result, char *buf, int buflen, int *h_errnop );

struct hostent *gethostbyaddr_r( const char *addr, int len, int type, struct hostent *result, char *buf, int buflen, int *h_errnop );

both return : nonnull pointer if OK, NULL on error

result ๋Š” ํ˜ธ์ถœ์ž์— ์˜ํ•ด ๋ฉ”๋ชจ๋ฆฌ๊ฐ€ ํ• ๋‹น๋œ ํ›„ ํ•จ์ˆ˜ ๋‚ด์—์„œ ๊ฐ’์ด ์ฑ„์›Œ์ง„๋‹ค .์ด ๊ฐ’์„ return ๋ฐ›๋Š”๋‹ค .

buf ๋Š” ํ˜ธ์ถœ์ž๊ฐ€ ํ• ๋‹นํ•œ ๋ฒ„ํผ๋กœ ์‹ค์ œ ๊ฐ’๋“ค์„ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฉฐ result ์˜ pointer ๋“ค์€ ์ด ๋ฒ„ํผ ์•ˆ์˜ ๊ฐ’๋“ค์„ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค .Buffer ์˜ ํฌ๊ธฐ๋Š” ์ตœ๊ทผ 8192 byte ๊ฐ€ ์ ๋‹นํ•˜๋‹ค๊ณ  ํ•œ๋‹ค .

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 12 Chap. 12 Daemon Processes Daemon Processes and and inetd inetd SuperserverSuperserverChap. 12 Chap. 12 Daemon Processes Daemon Processes and and inetd inetd SuperserverSuperserver

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

103

http://www.kwanghee.net/http://www.kwanghee.net/

What is Daemon?What is Daemon?What is Daemon?What is Daemon?

โ€ข Daemon is โ€ฆโ€“ a process that runs in the backgroundโ€“ independent of control from all terminals

โ€ข Daemon ์„ ์ž‘๋™์‹œํ‚ค๋Š” ๋ฐฉ๋ฒ•โ€“ ์‹œ์Šคํ…œ์˜ startup ์‹œ์— system initialization script ๋ฅผ ํ†ตํ•ด์„œ ์ž‘๋™ (/e

tc ๋˜๋Š” /etc/rc* ๋””๋ ‰ํ† ๋ฆฌ )โ€“ inetd superserver ๋ฅผ ํ†ตํ•ด ์ž‘๋™โ€“ cron daemon ์— ์˜ํ•ด ์ˆ˜ํ–‰โ€“ at command ๋กœ๋ถ€ํ„ฐ ์ง€์ •๋˜์–ด ์ž‘๋™โ€“ user terminal ๋กœ๋ถ€ํ„ฐ ์ž‘๋™

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

104

http://www.kwanghee.net/http://www.kwanghee.net/

daemon_init Functiondaemon_init Functiondaemon_init Functiondaemon_init Function

1 #include "unp.h" 2 #include <syslog.h> 3 #define MAXFD 64 4 extern int daemon_proc; /* defined in error.c */ 5 void 6 daemon_init(const char *pname, int facility) 7 { 8 int i; 9 pid_t pid; 10 if ( (pid = Fork()) != 0) 11 exit(0); /* parent terminates */ 12 /* 1st child continues */ 13 setsid(); /* become session leader */ 14 Signal(SIGHUP, SIG_IGN); 15 if ( (pid = Fork()) != 0) 16 exit(0); /* 1st child terminates */ 17 /* 2nd child continues */ 18 daemon_proc = 1; /* for our err_XXX() functions */ 19 chdir("/"); /* change working directory */ 20 umask(0); /* clear our file mode creation mask */ 21 for (i = 0; i < MAXFD; i++) 22 close(i); 23 openlog(pname, LOG_PID, facility); 24 }

process ๊ฐ€ foreground ๋กœ ์ˆ˜ํ–‰๋œ ๊ฒฝ์šฐ์ž๋™์œผ๋กœ background ๋กœ ์ „ํ™˜๋˜์–ด ์ˆ˜ํ–‰

The purpose of this 2nd fork is to guarantee that the daemon canโ€™t automatically acquire a controlling terminal should it open a terminal device in the future

์ƒˆ๋กœ์šด ๊ทธ๋ฃน์˜ ๊ทธ๋ฃน ๋ฆฌ๋”๊ฐ€ ๋จ๊ณผ ๋™์‹œ์— ,controlling terminal ์ด ์—†๋Š” ์ƒํƒœ๊ฐ€ ๋œ๋‹ค .

syslogd ๋ฅผ ํ†ตํ•ด logging ์ด ๊ฐ€๋Šฅํ•˜๋„๋กํ•œ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

105

http://www.kwanghee.net/http://www.kwanghee.net/

Example: Daytime Server as a DaemonExample: Daytime Server as a DaemonExample: Daytime Server as a DaemonExample: Daytime Server as a Daemon

1 #include "unp.h" 2 #include <time.h> 3 int main(int argc, char **argv) 4 { 5 int listenfd, connfd; 6 socklen_t addrlen, len; 7 struct sockaddr *cliaddr; 8 char buff[MAXLINE]; 9 time_t ticks; 10 daemon_init(argv[0], 0); 11 if (argc == 2) 12 listenfd = Tcp_listen(NULL, argv[1], &addrlen); 13 else if (argc == 3) 14 listenfd = Tcp_listen(argv[1], argv[2], &addrlen); 15 else 16 err_quit("usage: daytimetcpsrv2 [ <host> ] <service or port>"); 17 cliaddr = Malloc(addrlen); 18 for ( ; ; ) { 19 len = addrlen; 20 connfd = Accept(listenfd, cliaddr, &len); 21 err_msg("connection from %s", Sock_ntop(cliaddr, len)); 22 ticks = time(NULL); 23 snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); 24 Write(connfd, buff, strlen(buff)); 25 Close(connfd); 26 } 27 }

getaddrinfo() + socket() + bind() + listen()

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

106

http://www.kwanghee.net/http://www.kwanghee.net/

inetd Daemoninetd Daemoninetd Daemoninetd Daemon

โ€ข inetd daemon = internet superserverโ€ข ์žฅ์ 

โ€“ inetd ์— ์˜ํ•ด daemon ์ดˆ๊ธฐํ™”์— ๊ด€๋ จ๋œ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋ฏ€๋กœ ๊ฐ๊ฐ์˜ daemon ํ”„๋กœ๊ทธ๋žจ์ด ๊ฐ„๋žตํ•ด์ง

โ€“ ์—ฌ๋Ÿฌ ์„œ๋น„์Šค๋“ค์— ๋Œ€ํ•œ client request ์˜ ๋Œ€๊ธฐ๋ฅผ ํ•˜๋‚˜์˜ ํ”„๋กœ์„ธ์Šค (inetd) ์—์„œ ์ˆ˜ํ–‰ํ•˜์—ฌ , ์‹œ์Šคํ…œ์˜ ์ด ํ”„๋กœ์„ธ์Šค ์ˆ˜๋ฅผ ๊ฐ์†Œ์‹œํ‚ฌ์ˆ˜ ์žˆ์Œ

โ€ข /etc/inetd.conf fileโ€“ ftp stream tcp nowait root /usr/sbin/in.ftpd in.ftpdโ€“ telnet stream tcp nowait root /usr/sbin/in.telnetd in.telnetdโ€“ login stream tcp nowait root /usr/sbin/in.rlogind in.rlogindโ€“ tftp dgram udp wait root /usr/sbin/in.tftpd in.tftpd -s /tftpbo

otโ€ข /etc/services file

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

107

http://www.kwanghee.net/http://www.kwanghee.net/

inetdinetd ์˜ ๋™์ž‘์˜ ๋™์ž‘inetdinetd ์˜ ๋™์ž‘์˜ ๋™์ž‘socket()

bind()

listen()(if TCP socket)

select()for readability

accept()(if TCP socket)

fork()

close connected socket (if TCP)

close connected socket (if TCP)

dup socket to descriptor 0,1,2;

close socket

setgid()setuid()

(if user not root)

exec() server

parent child

For each service listed in the/etc/inetd.conf file

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 13 Chap. 13 Advanced I/O FunctionsAdvanced I/O FunctionsChap. 13 Chap. 13 Advanced I/O FunctionsAdvanced I/O Functions

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

109

http://www.kwanghee.net/http://www.kwanghee.net/

Socket TimeoutsSocket TimeoutsSocket TimeoutsSocket Timeouts

โ€ข I/O operation ์—์„œ timeout ์„ ์ด์šฉํ•˜๋Š” 3 ๊ฐ€์ง€ ๋ฐฉ๋ฒ•โ€“ alarm ํ•จ์ˆ˜ ์ด์šฉ : ํŠน์ • ์‹œ๊ฐ„ ํ›„์— SIGALRM ์‹œ๊ทธ๋„ ๋ฐœ์ƒโ€“ select ํ•จ์ˆ˜ ์ด์šฉ : Block waiting for I/Oโ€“ SO_RCVTIMEO, SO_SNDTIMEO ์†Œ์ผ“ ์˜ต์…˜ ์ด์šฉ

โ€ข connect with a Timeout Using SIGALRMint connect_timeo(int sockfd, const SA *saptr, socklen_t salen, int nsec){ โ€ฆ sigfunc = Signal(SIGALRM, connect_alarm); if (alarm(nsec) != 0) err_msg("connect_timeo: alarm was already set");

if ( (n = connect(sockfd, (struct sockaddr *) saptr, salen)) < 0) { close(sockfd); if (errno == EINTR) errno = ETIMEDOUT; } alarm(0); /* turn off the alarm */ Signal(SIGALRM, sigfunc); /* restore previous signal handler */ return(n);}

static voidconnect_alarm(int signo){ return; /* just interrupt the connect() */}

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

110

http://www.kwanghee.net/http://www.kwanghee.net/

recv and send Functionsrecv and send Functionsrecv and send Functionsrecv and send Functions

#include <sys/socket.h>ssize_t recv(int sockfd, void *buff, size_t nbyte, int flags);ssize_t send(int sockfd, const void *buff, size_t nbytes, int flags);

Both return: number of bytes read or written if OK, -1 on error

โ€ป flags ์ธ์ˆ˜๋ฅผ ์ œ์™ธํ•˜๊ณ ๋Š” read / write ํ•จ์ˆ˜์™€ ๋™์ผflags Description recv send

MSG_DONTROUTEMSG_DONTWAITMSG_OOBMSG_PEEKMSG_WAITALL

bypass routing table lookuponly this operation is nonblockingsend or receive out-of-band datapeek at incoming messagewait for all the data

โ—โ—โ—โ—

โ—โ—โ—

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

111

http://www.kwanghee.net/http://www.kwanghee.net/

readv and writev / recvmsg and sendmsg Functireadv and writev / recvmsg and sendmsg Functionsonsreadv and writev / recvmsg and sendmsg Functireadv and writev / recvmsg and sendmsg Functionsons

#include <sys/socket.h>ssize_t readv(int filedes, const struct iovec *iov, int iovcnt);ssize_t writev(int filedes, const struct iovec *iov, int iovcnt);

Both return: number of bytes read or written if OK, -1 on error

#include <sys/socket.h>ssize_t recvmsg(int sockfd, struct msghdr *msg, int flags);ssize_t sendmsg(int sockfd, struct msghdr *msg, int flags);

Both return: number of bytes read or written if OK, -1 on error

struct iovec { void *iov_base; /* starting addr. of buf. */ size_t iov_len; /* size of buffer */};

struct msghdr { void *msg_name; /* protocol address */ socklen_t msg_namelen; /* size of protocol addr. */ struct iovec *msg_iov; /* scatter/gather array */ size_t msg_iovlen; /* # elements in msg_iov */ void *msg_control; /* ancillary data */ socklen_t msg_controllen; /* len. of ancillary data */ int msg_flags /* flags returned by recvmsg() */};

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

112

http://www.kwanghee.net/http://www.kwanghee.net/

Sockets and Standard I/OSockets and Standard I/OSockets and Standard I/OSockets and Standard I/O

โ€ข Example: str_echo Function Using Standard I/O

1 #include "unp.h" 2 3 void 4 str_echo(int sockfd) 5 { 6 char line[MAXLINE]; 7 FILE *fpin, *fpout; 8 9 fpin = Fdopen(sockfd, "r"); 10 fpout = Fdopen(sockfd, "w"); 11 12 for ( ; ; ) { 13 if (Fgets(line, MAXLINE, fpin) == NULL) 14 return; /* connection closed by other end */ 15 16 Fputs(line, fpout); 17 } 18 }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

113

http://www.kwanghee.net/http://www.kwanghee.net/

T/TCP: TCP for TransactionsT/TCP: TCP for TransactionsT/TCP: TCP for TransactionsT/TCP: TCP for Transactions

โ€ข can avoid 3-way handshake between hosts that have communicated with each other recently

โ€ข can combine the SYN, FIN, and data into a single segment

client server

socketsendto

read(blocks)

read returns

socket, bind, listenaccept (blocks)

accept returnsread request<server processes request>

send reply close

SYN, FIN, data (request)

SYN, FIN, data (reply)

ack of clientโ€™s FIN

ack of serverโ€™s FIN

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

114

http://www.kwanghee.net/http://www.kwanghee.net/

T/TCP: comparison to general TCPT/TCP: comparison to general TCPT/TCP: comparison to general TCPT/TCP: comparison to general TCP

Client Serversocket, bind, listenLISTEN(passive open)accept(blocks)

socketconnect(blocks)(active open)SYN_SENT

SYN j, mss=1460

SYN_RCVDSYN k, ack j+1, mss = 1024

ESTABLISHEDconnect returns ack K+1

ESTABLISHEDaccept returnsread(blocks)write

read(blocks)data(request)

read returns<server processes request>

read returns

data(replay)ack of request

ack of reply

close

CLOSE_WAIT(passive close)read return 0

FIN M(active close) FIN_WAIT_1

ack M+1FIN_WAIT_2

FIN N

ack N+1

closeLAST_ACK

CLOSEDTIME_WAIT

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 14 Chap. 14 Unix Domain ProtocolsUnix Domain ProtocolsChap. 14 Chap. 14 Unix Domain ProtocolsUnix Domain Protocols

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

116

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Domain ProtocolsUnix Domain ProtocolsUnix Domain ProtocolsUnix Domain Protocols

โ€ข Unix domain protocol ์€ IPC ๋Œ€์šฉ์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œโ€“ stream socket (similar to TCP)โ€“ datagram socket (similar to UDP)

โ€ข Unix Domain Socket Address Structure

struct sockaddr_un { uint8_t sun_len; sa_family_t sun_family; /* AF_LOCAL */ char sun_path[104]; /* null-terminated pathname */};

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

117

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Domain Steram Protocol Echo ServerUnix Domain Steram Protocol Echo ServerUnix Domain Steram Protocol Echo ServerUnix Domain Steram Protocol Echo Server

1 #include "unp.h"

2 int

3 main(int argc, char **argv)

4 {

โ€ฆ /* ๋ณ€์ˆ˜ ์ดˆ๊ธฐํ™” ๋ถ€๋ถ„ ์ƒ๋žต */

10 listenfd = Socket(AF_LOCAL, SOCK_STREAM, 0);

11 unlink(UNIXSTR_PATH);

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

13 servaddr.sun_family = AF_LOCAL;

14 strcpy(servaddr.sun_path, UNIXSTR_PATH);

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

16 Listen(listenfd, LISTENQ);

17 Signal(SIGCHLD, sig_chld);

18 for ( ; ; ) {

19 clilen = sizeof(cliaddr);

20 if ( (connfd = accept(listenfd, (SA *) &cliaddr, &clilen)) < 0) {

21 if (errno == EINTR)

22 continue; /* back to for() */

23 else

24 err_sys("accept error");

25 }

26 if ( (childpid = Fork()) == 0) { /* child process */

27 Close(listenfd); /* close listening socket */

28 str_echo(connfd); /* process the request */

29 exit(0);

30 }

31 Close(connfd); /* parent closes connected socket */

32 }

33 }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

118

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Domain Steram Protocol Echo ClientUnix Domain Steram Protocol Echo ClientUnix Domain Steram Protocol Echo ClientUnix Domain Steram Protocol Echo Client

1 #include "unp.h"

2

3 int

4 main(int argc, char **argv)

5 {

6 int sockfd;

7 struct sockaddr_un servaddr;

8

9 sockfd = Socket(AF_LOCAL, SOCK_STREAM, 0);

10

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

12 servaddr.sun_family = AF_LOCAL;

13 strcpy(servaddr.sun_path, UNIXSTR_PATH);

14

15 Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));

16

17 str_cli(stdin, sockfd); /* do it all */

18

19 exit(0);

20 }

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

119

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Domain Protocol ExamplesUnix Domain Protocol ExamplesUnix Domain Protocol ExamplesUnix Domain Protocol Examples

โ€ข Passing Descriptors

[0] [1]

program1

[0] [1]

forkexec

program1 program2

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network ProgrammingUnix Network ProgrammingUnix Network ProgrammingUnix Network Programming

Chapter 15Nonblocking I/O

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

121

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข Nonblocking Reads and Writes :

โ€“ str_cli functionโ€ข Nonblocking connect

โ€“ Daytime Clientโ€“ Web Clientโ€“ accept

โ€ข Summary

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

122

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข By default, sockets are blocking.โ€ข ์ฃผ์š” blocking ๋˜๋Š” ๋ถ€๋ถ„

โ€“ Input Operationsโ€  read(), readv(), recv(), recvfrom()

โ€“ Output operationsโ€  write(), writev(), send(), sendto()

โ€“ Accepting incoming connectionsโ€  accept()

โ€“ Initiating outgoing connectionsโ€  connect()

โ€ข Chapter 6 : various I/O model was learned

Nonblocking I/O

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

123

http://www.kwanghee.net/http://www.kwanghee.net/

Nonblocking Read and WritesNonblocking Read and WritesNonblocking Read and WritesNonblocking Read and Writes

โ€ข Goal in this section is to develop a version of this function that uses nonblocking I/O

โ€ข Unfortunately the addition of nonblocking I/O complicates the functionโ€™s buffer management noticeably.

โ€ข Is it worth the effort to code an application using nonblocking I/O, given the complexity of the resulting code?

nonblocking I/O

์†Œ์Šค๊ฐ€ ๋„˜ ๋ณต์žกํ•ด !!Writer recommend the simple Approach !!!!

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

124

http://www.kwanghee.net/http://www.kwanghee.net/

Nonblocking connectNonblocking connectNonblocking connectNonblocking connect

โ€ข There are 3 uses for nonblocking connectโ€“ Overlap other processing with the 3-way handshakingโ€“ Establish multiple connections at the same timeโ€“ Specify a time limit for select()

75 ์ดˆ๊ฐ€ ๋ณดํ†ต ๊ธฐ๋ณธ์ด๋ž๋‹ˆ๋‹ค .

75 ์ดˆ๊ฐ€ ๋ณดํ†ต ๊ธฐ๋ณธ์ด๋ž๋‹ˆ๋‹ค .โ€ข Even though the socket is nonblocking, if the server to which we are

connecting is on the same host, the connection establishment normally takes place immediately when we call connect()โ€ข Berkeley-derived implementations have the following 2 rules regarding select() and nonblocking connects (1) when the connection completes successfully, the descriptor becomes writable, and (2) when the connection establishment encounters an error, the descriptor becomes both readable and writable

Must handled !!!

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

125

http://www.kwanghee.net/http://www.kwanghee.net/

Daytime ClientDaytime ClientDaytime ClientDaytime Client

1. int connect_nonb(int sockfd, const SA *saptr, socklen_t salen, int nsec)2. { int flags, n, error; socklen_t len; fd_set rset, wset; struct timeval tval;3. flags = Fcntl(sockfd, F_GETFL, 0);4. Fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);5. error = 0;6. if ( (n = connect(sockfd, (struct sockaddr *) saptr, salen)) < 0)7. if (errno != EINPROGRESS)8. return(-1);9. /* Do whatever we want while the connect is taking place. */10. if (n == 0)11. goto done; /* connect completed immediately */12. FD_ZERO(&rset);13. FD_SET(sockfd, &rset);14. wset = rset;15. tval.tv_sec = nsec;16. tval.tv_usec = 0;17. if ( (n = Select(sockfd+1, &rset, &wset, NULL, nsec ? &tval : NULL)) == 0) {18. close(sockfd); /* timeout */19. errno = ETIMEDOUT;20. return(-1); }21. if (FD_ISSET(sockfd, &rset) || FD_ISSET(sockfd, &wset)) {22. len = sizeof(error);23. if (getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &len) < 0)24. return(-1); /* Solaris pending error */ } else25. err_quit("select error: sockfd not set");26. done:27. Fcntl(sockfd, F_SETFL, flags); /* restore file status flags */28. if (error) {29. close(sockfd); /* just in case */30. errno = error;31. return(-1); }32. return(0); }

Set socket noblocking

Overlap processing with connection establishment

Check for immediate completion

Call select

Check for readability or writabilty

Turn off nonblocking and return

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

126

http://www.kwanghee.net/http://www.kwanghee.net/

WebClientWebClientWebClientWebClient

โ€ข Performance of simulation Connections

# simultaneous connections

clock time (sec)nonblocking

Clock timethreads

1 6.0 6.3

2 4.1 4.2

3 3.0 3.1

4 2.8 3.0

5 2.5 2.7

6 2.4 2.5

7 2.3 2.3

8 2.2 2.3

9 2.0 2.2

๋ณต์žก๋งŒํ•˜์ง€ ,๊ทธ๋ฆฌ ๋น ๋ฅด์ง€

์•Š๊ตฐ ..์ •๋ง ๋น ๋ฅธ ๊ณณ๋งŒ ์จ์•ผ

๊ฒ ๊ตฐ ..

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

127

http://www.kwanghee.net/http://www.kwanghee.net/

Nonblocking acceptNonblocking acceptNonblocking acceptNonblocking accept

1. #include "unp.h"2. int3. main(int argc, char **argv)4. {5. int sockfd;6. struct linger ling;7. struct sockaddr_in servaddr;8. if (argc != 2)9. err_quit("usage: tcpcli <IPaddress>");10. sockfd = Socket(AF_INET, SOCK_STREAM, 0);11. bzero(&servaddr, sizeof(servaddr));12. servaddr.sin_family = AF_INET;13. servaddr.sin_port = htons(SERV_PORT);14. Inet_pton(AF_INET, argv[1], &servaddr.sin_addr);15. Connect(sockfd, (SA *) &servaddr, sizeof(servaddr));16. ling.l_onoff = 1; /* cause RST to be sent on close() */17. ling.l_linger = 0;18. Setsockopt(sockfd, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling));19. Close(sockfd);20. exit(0);21. }

Set SO_LINGER socket Option

linger v. 1. to stay somewhere longer or to take longerto do something than usual2. also linger on to be slow to disappear

tcp ๋ฌธ์ œ์ ์€ ์—ฐ๊ฒฐ์„ ํ•˜๋ ค๋Š” ๋“ฏํ•˜๋‹ค๊ฐ€ ์—ฐ๊ฒฐ์„ํ•˜์ง€ ์•Š์„ ๊ฒฝ์šฐ , ์—ฐ๊ฒฐ์ด ๋Š์–ด์กŒ๋Š”๋ฐ๋„ ๋ถˆ๊ตฌ๊ณ„์†ํ•ด์„œ 3way ์•…์ˆ˜๋ฅผ ํ•˜๊ธฐ๋•Œ๋ฌธ์— , nonblocking I/O ๋ฅผ ํ• ๋•Œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด socket option ์„ ์ด์šฉํ•ด์•ผ ํ•จ๋‹ค .

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network ProgrammingUnix Network ProgrammingUnix Network ProgrammingUnix Network Programming

Chapter 16ioctl Operation

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

129

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข ioctl Functionโ€ข Socket Operationsโ€ข File Operationsโ€ข Interface Configurationโ€ข get_fif_info Functionget_fif_info Functionโ€ข Interface Operationsโ€ข ARP Cache Operationsโ€ข Routing Table Operationsโ€ข Summary

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

130

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข ioctl() has traditionally been the system interface used for everything that didnโ€™t fit into some other nicely defined category.

โ€ข This remain for implementation-dependent features related to network programmingโ€“ obtaining the interface informationโ€“ accessing the the routing tableโ€“ accessing the ARP cache

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

131

http://www.kwanghee.net/http://www.kwanghee.net/

ioctl Functionioctl Functionioctl Functionioctl Function

โ€ข socket operationsโ€ข file operationsโ€ข interface operationsโ€ข ARP cache operationsโ€ข routing table operationsโ€ข stream system(Chapter 33)

#include <unistd.h>

int ioctl(int fd, int request, โ€ฆ./*void *arg */ );

Returns : 0 if OK, -1 on error

#include <unistd.h>

int ioctl(int fd, int request, โ€ฆ./*void *arg */ );

Returns : 0 if OK, -1 on error

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

132

http://www.kwanghee.net/http://www.kwanghee.net/

Socket OperationSocket OperationSocket OperationSocket Operation

โ€ข SIOCATMARKโ€“ socketโ€™s read pointer is currently at the out-of-band mark, or a zero val

ue if the read pointer is not at the out-of-band mark.โ€ข SIOCGPGRP

โ€“ PID or the process group IDโ€ข SIOCSPGRP

โ€“ set either the PID or the process tourp IDchapter 7fcntl() ๊ด€๋ จ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

133

http://www.kwanghee.net/http://www.kwanghee.net/

File OperationsFile OperationsFile OperationsFile Operations

โ€ข FIONBIOโ€“ nonblocking flag for the socket is cleared or turned on, depending whe

ther the third argument to ioct() points to a zero or nonzero valueโ€ข FIOASYNC

โ€“ governs the receipt of asynchronous I/O signals(SIGIO)โ€ข FIONREAD

โ€“ the number of bytes in the socket receive buffer โ€ข FIOSETOWN

โ€“ same as SIOCSPGRPโ€ข FIOGETOWN

โ€“ same as SIOCGPGRP

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

134

http://www.kwanghee.net/http://www.kwanghee.net/

Interface OperationsInterface OperationsInterface OperationsInterface Operations

โ€ข SIOCGIFADDRโ€“ Return the unicast address

โ€ข SIOCSIFADDRโ€“ Sets the interface address

โ€ข SIOCGIFFLAGSโ€“ Return the interface flags

โ€ข SIOCSIFFLAGSโ€“ Set the interface flags

โ€ข SICGIFDSTTADDRโ€“ Return the point-to-point address

โ€ข SICSIFDSTADDRโ€“ Set the point-to-point address

โ€ข SIOCSIFBRDADDRโ€“ Set the broadcast address

โ€ข SIOCGIFNETMASKโ€“ Return the subnet mask

โ€ข SIOCSIFNETMASKโ€“ Set the subnet mask

โ€ข SIOCGIFMETRICโ€“ Return the interface metric

โ€ข SIOCIFMETRICโ€“ Set the interface routing metric

G ๋Š” get ์ด๊ณ S ๋Š” Set ์ด๊ตฌ๋‚˜ ~

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

135

http://www.kwanghee.net/http://www.kwanghee.net/

ARP Cache OperationsARP Cache OperationsARP Cache OperationsARP Cache Operations

1. #include <net/if_arp.h>2. int main(int argc, char **argv)3. {4. int family, sockfd;5. char str[INET6_ADDRSTRLEN];6. char **pptr;7. unsigned char *ptr;8. struct arpreq arpreq;9. struct sockaddr_in *sin;10. pptr = my_addrs(&family);11. for ( ; *pptr != NULL; pptr++) {12. printf("%s: ", Inet_ntop(family, *pptr, str, sizeof(str)));13. switch (family) {14. case AF_INET:15. sockfd = Socket(AF_INET, SOCK_DGRAM, 0);16. sin = (struct sockaddr_in *) &arpreq.arp_pa;17. bzero(sin, sizeof(struct sockaddr_in));18. sin->sin_family = AF_INET;19. memcpy(&sin->sin_addr, *pptr, sizeof(struct in_addr));20. Ioctl(sockfd, SIOCGARP, &arpreq);21. ptr = &arpreq.arp_ha.sa_data[0];22. printf("%x:%x:%x:%x:%x:%x\n", *ptr, *(ptr+1),23. *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5));24. break;25. default:26. err_quit("unsupported address family: %d", family);27. } } exit(0);}

get list of address and loop through each one

Print IP address

Issue ioctl and print hardware address

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

136

http://www.kwanghee.net/http://www.kwanghee.net/

Routing Table OperationsRouting Table OperationsRouting Table OperationsRouting Table Operations

โ€ข TWO ioctl() requests providedโ€“ SIOCADDRT

โ€  Add an entry to the routing tableโ€“ SIOCDELRT

โ€  Delete an entry from the routing table

์ง€๊ธˆ๊นŒ์ง€โ€ข Socket Operationโ€ข file operationโ€ข interface operationโ€ข ARP table operationโ€ข routing table operation

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

137

http://www.kwanghee.net/http://www.kwanghee.net/

UNIX Network Programming( chap 17 - chap 18 )

UNIX Network Programming( chap 17 - chap 18 )

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

138

http://www.kwanghee.net/http://www.kwanghee.net/

Chap.17 - Routing Socket

โ˜ž Routing table ๋กœ์˜ ์ ‘๊ทผ ๋ฐฉ๋ฒ•

โ˜ž Message Types

โ˜ž Structure Types

โ˜ž Constants in routing messages

โ˜ž RMT_GET example

โ˜ž sysctl Operations

Contents

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

139

http://www.kwanghee.net/http://www.kwanghee.net/

We must study โ€ฆ ?

Network ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•œ Routing table ๋กœ์˜ ์ ‘๊ทผ๋ฐฉ๋ฒ• (2 ๊ฐ€์ง€ ) ๊ณผ ์‚ฌ์šฉ๋ฒ•

1. Routing socket ์‚ฌ์šฉ (superuser)

2. sysctl ์‚ฌ์šฉ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

140

http://www.kwanghee.net/http://www.kwanghee.net/

Routing table ๋กœ์˜ ์ ‘๊ทผ ๋ฐฉ๋ฒ•

1. Use ioctl command

2. Use netstat program

3. Use routing daemon ( only superuser )- monitor ICMP redirection message by

creating a raw ICMP socket- routing domain ์—์„œ ์ง€์›๋˜๋Š” ์œ ์ผํ•œ socket

type ์€ raw socket ์ด๋‹ค .

4. Use sysctl command

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

141

http://www.kwanghee.net/http://www.kwanghee.net/

Message Types

Message typeFromkernel

Structuretype

Tokernel

Description

RTM_ADDRTM_CHANGERTM_DELADDRRTM_DELETERTM_GETRTM_IFINFORTM_LOCKRTM_LOSINGRTM_MISSRTM_NEWADDRRTM_REDIRECTRTM_RESOLVE

โ€ขโ€ข

โ€ขโ€ข

โ€ข

โ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ขโ€ข

add routechange gateway, metrics, or flagsaddress being removed from interfacedelete routereport metrics and other route informationinterface going up, down etc.lock specified metricskernel suspects route is failinglookup failed on this addressaddress being added to interfacekernel told to use different routerequest to resolve destination to link layer address

rt_msghdrrt_msghdrifa_msghdrrt_msghdrrt_msghdrif_msghdrrt_msghdrrt_msghdrrt_msghdrifa_msghdrrt_msghdrrt_msghdr

โ˜ž Routing table ์— ์“ฐ๊ณ  / ์ฝ๋Š” ๋ช…๋ น์˜ Message type - <net/route.h>

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

142

http://www.kwanghee.net/http://www.kwanghee.net/

type

def

stru

ct r

t_m

sghd

r {

ush

ort_

t rtm

_msg

len;

/*

to s

kip

over

non

-und

erst

ood

mes

sage

s */

uch

ar_t

rtm

_ver

sion

; /

* fu

ture

bin

ary

com

pati

bili

ty *

/

u

char

_t r

tm_t

ype;

/* m

essa

ge ty

pe *

/

u

shor

t_t r

tm_i

ndex

;

/* in

dex

for

asso

ciat

ed if

p */

int

r

tm_f

lags

;

/* f

lags

, inc

l. ke

rn &

mes

sage

, e.g

. DO

NE

*/

in

t

rtm

_ad

drs

;

/*

bit

mas

k id

enti

fyin

g so

ckad

drs

in m

sg *

/

p

id_t

rtm

_pid

;

/*

iden

tify

sen

der

*/

i

nt

rtm

_seq

;

/*

for

sen

der

to id

enti

fy a

ctio

n */

int

r

tm_e

rrno

;

/* w

hy f

aile

d */

int

r

tm_u

se;

/* f

rom

rte

ntry

*/

uin

t_t

rt

m_i

nits

;

/* w

hich

met

rics

we

are

init

iali

zing

*/

str

uct

rt

_met

rics

rtm

_rm

x; /*

met

rics

them

selv

es *

/}

rt_m

sghd

r_t;

type

def

stru

ct if

_msg

hdr

{

u

shor

t_t i

fm_m

sgle

n;

/* to

ski

p ov

er n

on-u

nder

stoo

d m

essa

ges

*/

u

char

_t i

fm_v

ersi

on;

/*

futu

re b

inar

y co

mpa

tabi

lity

*/

uch

ar_t

ifm

_typ

e;

/*

mes

sage

type

*/

in

t

ifm

_ad

drs

;

/*

lik

e rt

m_a

dd

rs *

/

i

nt

ifm

_fla

gs;

/*

val

ue o

f if

_fla

gs *

/

u

shor

t_t i

fm_i

ndex

;

/* in

dex

for

asso

ciat

ed if

p */

str

uct

if

_dat

a if

m_d

ata;

/* s

tati

stic

s an

d ot

her

data

abo

ut if

*/

} if

_msg

hdr_

t;

type

def

stru

ct if

a_m

sghd

r {

ush

ort_

t ifa

m_m

sgle

n;

/* to

ski

p ov

er n

on-u

nder

stoo

d m

essa

ges

*/

u

char

_t i

fam

_ver

sion

; /*

fut

ure

bina

ry c

ompa

tabi

lity

*/

uch

ar_t

ifa

m_t

ype;

/* m

essa

ge ty

pe *

/

i

nt

if

am_a

dd

rs;

/*

lik

e rt

m_a

dd

rs *

/

i

nt

ifam

_fla

gs;

/*

rou

te f

lags

*/

ush

ort_

t ifa

m_i

ndex

; /

* in

dex

for

asso

ciat

ed if

p */

int

if

am_m

etri

c;

/* v

alue

of

ipif

_met

ric

*/}

ifa_

msg

hdr_

t;

Structure Types

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

143

http://www.kwanghee.net/http://www.kwanghee.net/

Constants in routing messages

BitmaskSocket address structure containing

RTA_DSTRTA_GATEWAYRTA_NETMASKRTA_GENMASKRTA_IFPRTA_IFARTA_AUTHORRTA_BRD

destination addressgateway addressnetwork maskcloning maskinterface nameinterface addressauthor of redirectbroadcast or point-to-point

destination address

constant value

Array index

01234567

constant value

RTAX_DSTRTAX_GATEWAYRTAX_NETMASKRTAX_GENMASKRTAX_IFPRTAX_IFARTAX_AUTHORRTAX_BRD

0x010x020x040x080x100x200x400x80

Max #elementsRTAX_MAX 8

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

144

http://www.kwanghee.net/http://www.kwanghee.net/

#inc

lude

"un

prou

te.h

"

#def

ine

BU

FLE

N (

size

of(s

truc

t rt_

msg

hdr)

+ 5

12)

/*

8 *

siz

eof(

stru

ct s

ocka

ddr_

in6)

= 1

92 *

/#d

efin

e SE

Q

9

999

int

mai

n(in

t arg

c, c

har

**ar

gv)

{

int

soc

kfd;

cha

r

*buf

;

p

id_t

pi

d;

s

size

_t

n

;

s

truc

t rt_

msg

hdr

*rt

m;

str

uct s

ocka

ddr

*sa

, *rt

i_in

fo[R

TA

X_M

AX

];

s

truc

t soc

kadd

r_in

*sin

;

if

(arg

c !=

2)

e

rr_q

uit(

"usa

ge: g

etrt

<IP

addr

ess>

");

soc

kfd

= S

ocke

t(A

F_R

OU

TE

, SO

CK

_RA

W, 0

); /*

nee

d su

peru

ser

priv

ilege

s */

buf

= C

allo

c(1,

BU

FLE

N);

/*

and

initi

aliz

ed to

0 *

/

rtm

= (

stru

ct r

t_m

sghd

r *)

buf

;

r

tm->

rtm

_msg

len

= s

izeo

f(st

ruct

rt_

msg

hdr)

+ s

izeo

f(st

ruct

soc

kadd

r_in

);

r

tm->

rtm

_ver

sion

= R

TM

_VE

RSI

ON

;

r

tm->

rtm

_typ

e =

RT

M_G

ET

;

r

tm->

rtm

_add

rs =

RT

A_D

ST;

rtm

->rt

m_p

id =

pid

= g

etpi

d();

rtm

->rt

m_s

eq =

SE

Q;

sin

= (

stru

ct s

ocka

ddr_

in *

) (r

tm +

1);

sin

->si

n_fa

mily

= A

F_IN

ET

;

Ine

t_pt

on(A

F_IN

ET

, arg

v[1]

, &si

n->

sin_

addr

);

Wri

te(s

ockf

d, r

tm, r

tm->

rtm

_msg

len)

;

do

{

n =

Rea

d(so

ckfd

, rtm

, BU

FLE

N);

} w

hile

(rt

m->

rtm

_typ

e !=

RT

M_G

ET

|| r

tm->

rtm

_seq

!=

SE

Q ||

rtm

->rt

m_p

id !

= p

id);

rtm

= (

stru

ct r

t_m

sghd

r *)

buf

;

s

a =

(st

ruct

soc

kadd

r *)

(rt

m +

1);

get

_rta

ddrs

(rtm

->rt

m_a

ddrs

, sa,

rti_

info

);

i

f (

(sa

= r

ti_in

fo[R

TA

X_D

ST])

!=

NU

LL

)

pri

ntf(

"des

t: %

s\n"

, Soc

k_nt

op_h

ost(

sa, s

a->

sa_l

en))

; /*

sa_

len

= 1

6 or

24

*/

if

( (s

a =

rti_

info

[RT

AX

_GA

TE

WA

Y])

!=

NU

LL

)

pri

ntf(

"gat

eway

: %s\

n", S

ock_

ntop

_hos

t(sa

, sa-

>sa

_len

));

/* s

a_le

n =

16

or 2

4 */

if

( (s

a =

rti_

info

[RT

AX

_NE

TM

ASK

]) !

= N

UL

L)

p

rint

f("n

etm

ask:

%s\

n", S

ock_

mas

ktop

(sa,

sa-

>sa

_len

));

/* s

a_le

n =

0,5

,6,7

,8 *

/

if

( (s

a =

rti_

info

[RT

AX

_GE

NM

ASK

]) !

= N

UL

L)

p

rint

f("g

enm

ask:

%s\

n", S

ock_

mas

ktop

(sa,

sa-

>sa

_len

));

/* s

a_le

n =

0,5

,6,7

,8 *

/

exi

t(0)

;}

RMT_GET example (1)

Pag

e 4 5

4์ฐธ

์กฐ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

145

http://www.kwanghee.net/http://www.kwanghee.net/

netmasksocket address

structure

destinationsocket address

structure

RMT_GET example (2)

rt_msghdr{}

rtm_type = RTM_GET

destinationsocket address

structure

rt_msghdr{}

rtm_type = RTM_GET

gatewaysocket address

structure

genmasksocket address

structure

buffer sentto kernel

buffer returnedby kernel

RTA_DST RTA_DST

RTA_GATEWAY

RTA_NETMASK

RTA_GENMASK

Data-link socket address structure

struct sockaddr_dl { uint8_t sdl_len; sa_family_t sdl_family; /* AF_LINK */ uint16_t sdl_index; uint8_t sdl_type; uint8_t sdl_nlen; uint8_t sdl_alen; uint8_t sdl_slen; char sdl_data[12];}

Data-link socket address structure

struct sockaddr_dl { uint8_t sdl_len; sa_family_t sdl_family; /* AF_LINK */ uint16_t sdl_index; uint8_t sdl_type; uint8_t sdl_nlen; uint8_t sdl_alen; uint8_t sdl_slen; char sdl_data[12];}

Example >

bsdi # getrt 206.62.226.32dest : 206.62.226.32gateway : AF_LINK, index=2netmask : 255.255.255.224

Port ๊ฐ€ ํ•„์š” ์—†๋‹ค

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

146

http://www.kwanghee.net/http://www.kwanghee.net/

sysctl Operations (1)

routing table ๊ณผ interface list ๋ชจ๋‘๋ฅผ ์กฐ์‚ฌํ•œ๋‹ค .

๋ชจ๋“  process ๊ฐ€ ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•˜๋‹ค . โ†” cf) routing socket ์ƒ์„ฑ์€ superuser ๋งŒ์ด ๊ฐ€๋Šฅํ•˜๋‹ค .

#include <sys/param.h>#include <sys/sysctl.h>

int sysctl( int *name, u_int namelen, void *oldp, size_t *oldlenp,void *newp, size_t newlen );

return : 0 if OK, -1 on error

#include <sys/param.h>#include <sys/sysctl.h>

int sysctl( int *name, u_int namelen, void *oldp, size_t *oldlenp,void *newp, size_t newlen );

return : 0 if OK, -1 on error

CTL_NETCTL_MACHDEP CTL_USERCTL_KERN

AF_INET AF_LINK AF_ROUTE AF_UNSPEC

IPPROTO_ICMP IPPROTO_IP IPPROTO_TCP IPPROTO_UDP

๊ณ„์ธต์˜ ์˜ˆ๊ณ„์ธต์˜ ์˜ˆ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

147

http://www.kwanghee.net/http://www.kwanghee.net/

sysctl Operations (2)

name[]Return IPv4routing table

Return IPv4ARP cache

Return IPv4interface list

012345

CTL_NETAF_ROUTE0AF_INETNET_RT_DUMP0

CTL_NETAF_ROUTE0AF_INETNET_RT_FLAGSRTF_LLINFO

CTL_NETAF_ROUTE0AF_INETNET_RT_IFLIST0

if_msghdr{}

ifm_type =RTM_IFINFO

datalinksocket address

structure

ifa_msghdr{}

ifam_type =RTM_NEWADDR

netmasksocket address

structure

unicast addrsocket address

structure

broadcast addrsocket address

structure

buffer returnedby kernel

One per interface :interface name, index and hardware address

One per address configured for the interface

mib[0] = CTL_NET;mib[1] = AF_ROUTE;mib[2] = 0;mib[3] = family;mib[4] = NET_RT_IFLIST;mib[5] = flag /* interface index or 0*/sysctl( mib, 6, buff, lenp, NULL, 0 );

mib[0] = CTL_NET;mib[1] = AF_ROUTE;mib[2] = 0;mib[3] = family;mib[4] = NET_RT_IFLIST;mib[5] = flag /* interface index or 0*/sysctl( mib, 6, buff, lenp, NULL, 0 );

์ด๋ ‡๊ฒŒ์ •๋ณด๋ฅผ

์–ป๋Š”๊ตฐ ..

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

148

http://www.kwanghee.net/http://www.kwanghee.net/

Chap.18 - Broadcast

โ˜ž Broadcast support and address

โ˜ž Broadcast datagram flow example

โ˜ž Race Conditions

blocking and unblocking the signal

blocking and unblocking the signal with pselect

using sigsetjmp and siglongjmp

using IPC(Interprocess communication) from signal handler to function

Contents

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

149

http://www.kwanghee.net/http://www.kwanghee.net/

We must study โ€ฆ ?

Unicast ์™€ Broadcast ์˜ ์ฐจ์ด

Broadcast ์˜ ๊ฐœ๋…๊ณผ ๋ฐฉ๋ฒ•

Race condition ์˜ ์›์ธ๊ณผ ๊ทธ ํ•ด๊ฒฐ์ฑ… (4 ๊ฐ€์ง€ )

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

150

http://www.kwanghee.net/http://www.kwanghee.net/

NOW

1. Multicast ์ง€์›์€ IPv4 ์—์„œ๋Š” optional ํ•˜์ง€๋งŒ IPv6์—์„œ๋Š” ํ•„์ˆ˜์ ์ด๋‹ค .

2. Broadcast ์ง€์›์€ IPv6 ์—์„œ๋Š” ์ œ๊ณต๋˜์ง€ ์•Š๋Š”๋‹ค . IPv6์— ์„œ๋Š” broadcast ๋ฅผ multicast ๋กœ ๋‹ค์‹œ ์ž‘์„ฑํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค .

3. Broadcast ์™€ multicast ๋Š” UDP ๋ฅผ ์š”๊ตฌํ•˜๋ฉฐ TCP์—์„œ๋Š” ๋™ ์ž‘ํ•˜์ง€ ์•Š๋Š”๋‹ค .

1. Subnet-directed broadcast address : {netid, subnetid, -1 }

2. All-subnets-directed broadcast address : { netid, -1, -1 }

3. Network-directed broadcast address : { netid, -1 }

4. Limited broadcast address : { -1, -1, -1 }

Broadcast support and address

All bits โ€˜1โ€™

โ†’ Subnet ์ด ์—†๋Š” ๊ฒฝ์šฐ

โ†’ Router ๋‚ด์˜ ๋งํ˜„์žฌ๋Š” 1 ๋ฒˆ์œผ๋กœ ๋ณ€ํ™˜๋˜์–ด ์‚ฌ์šฉ๋˜๋Š” ๊ฒฝ์šฐ๋„ ์žˆ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

151

http://www.kwanghee.net/http://www.kwanghee.net/

Broadcast datagram flow example

sendingappl

UDP

IPv6

datalink

UDP

IPv4

datalink

Enethdr

IPv4hdr

TCPhdr

TCPdata

Enethdr

IPv4hdr

TCPhdr

TCPdata

receivingappl

UDP

IPv4

datalink

Broadcast ์˜ ๊ทผ๋ณธ์ ์ธ ๋ฌธ์ œ

ํ•„์š”์น˜ ์•Š์€ overload ๋ฐœ์ƒ

sendtodest IP = 128.7.6.255dest port = 520

subnet 128.7.6

Frame type = 0800

08:00:20:03:f6:42

128.7.6.99 = unicast128.7.6.255 = broadcast

Protocol = UDP

discard

Frame type = 0800

Protocol = UDP

Port = 520

128.7.6.5 = unicast128.7.6.255 = broadcast

dest IP = 128.7.6.255prtocol = UDP

dest port = 520dest Enet = ff:ff:ff:ff:ff:ffframe type = 0800

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

152

http://www.kwanghee.net/http://www.kwanghee.net/

Example continue ...

[54 feel:kjschaos ~/mywork/network/unpv12e/bcast ] udpcli03 150.150.55.127hifrom 150.150.55.52: Mon Jan 10 18:01:23 2000from 150.150.55.53: Mon Jan 10 18:04:38 2000from 150.150.55.55: Mon Jan 10 18:05:48 2000from 150.150.55.99: Mon Jan 10 17:50:41 2000from 150.150.55.10: ์˜คํ›„ 6:02:48 2000-01-10from 150.150.55.54: Mon Jan 10 18:06:23 2000

[55 feel:kjschaos ~/mywork/network/unpv12e/bcast ] udpcli03 255.255.255.255hifrom 150.150.55.52: Mon Jan 10 18:01:42 2000from 150.150.55.53: Mon Jan 10 18:04:57 2000from 150.150.55.55: Mon Jan 10 18:06:07 2000from 150.150.55.99: Mon Jan 10 17:51:00 2000from 150.150.55.10: ์˜คํ›„ 6:03:07 2000-01-10from 150.150.55.100: Mon Jan 10 06:20:44 2000from 150.150.55.54: Mon Jan 10 18:06:42 2000

[56 feel:kjschaos ~/mywork/network/unpv12e/bcast ] udpcli03 150.150.55.52hifrom 150.150.55.52: Mon Jan 10 18:02:01 2000

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

153

http://www.kwanghee.net/http://www.kwanghee.net/

Race Conditions (1)

์—ฌ๋Ÿฌ ๊ฐœ์˜ process ๊ฐ€ ๊ณต์œ ํ•˜๋Š” data ๋ฅผ ์ฐธ์กฐํ•  ๋•Œ

Signal ์„ ๋‹ค๋ฃฐ ๋•Œ

When happen ?When happen ?

Broadcast ์— ์˜ํ•œ ์‘๋‹ต์ด ์—ฌ๋Ÿฌ host ๋กœ๋ถ€ํ„ฐ ์˜ฌ ๊ฒฝ์šฐ signal ์—

์˜ํ•œ ์›ํ•˜์ง€ ์•Š๋Š” ๊ณณ์—์„œ์˜ ์˜์›ํ•œ blocking ์„ ์—ผ๋‘์— ๋‘๊ณ 

์ฒ˜๋ฆฌํ•ด ์ฃผ์–ด์•ผ ํ•œ๋‹ค .

Why concern ?Why concern ?

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

154

http://www.kwanghee.net/http://www.kwanghee.net/

์—ฌ๋Ÿฌ ๊ฐœ์˜ process ๊ฐ€ ๊ณต์œ ํ•˜๋Š” data ๋ฅผ ์ฐธ์กฐํ•  ๋•Œ

1) mutual exclusion variables( ์ƒํ˜ธ ๋ฐฐ์ œ ๋ณ€์ˆ˜ )

2) condition variables

Signal ์„ ๋‹ค๋ฃฐ ๋•Œ

1) blocking and unblocking the signal

2) blocking and unblocking the signal with pselect

3) using sigsetjmp and siglongjmp

4) using IPC(Interprocess communication) from signal handler to function

SolutionSolution

Race Conditions (2)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

155

http://www.kwanghee.net/http://www.kwanghee.net/

Race Conditions - Signal case (1)

void dg_cli( โ€ฆ ){ Setsockopt( sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) ); ... Sigemptyset( &sigset_alrm ); Sigaddset( &sigset_alrm, AIGALRM );

Signal( SIGALRM, recvfrom_alarm );

while ( โ€ฆ ) { Sendto( sockfd, โ€ฆ )

alarm(5); for ( ; ; ) {

Sigprocmask( SIG_UNBLOCK, &sigset_alrm, NULL );n = recvfrom( sockfd, recvline, โ€ฆ );Sigprocmask( SIG_BLOCK, &sigset_alrm, NULL );โ€ฆ

} }}

static vois recvfsrom_alarm( int signo ){ return;}

์‹ ํ˜ธ๊ฐ€ recvfrom ๊ณผ์‹ ํ˜ธ ์ฐจ๋‹จ ์‚ฌ์ด์—์„œ๋ฐœ์ƒํ•˜๋ฉด ๋‹ค์Œ๋ฒˆ์˜

recvfrom ํ˜ธ์ถœ์€์˜์›ํžˆ ๋ด‰์‡„๋ 

๊ฒƒ์ด๋‹ค .

problem

Alarm ์˜ ๋ชฉ์ ์€๋ด‰์‡„๋˜์–ด ์žˆ๋Š”

recvfrom ์„ ์ค‘์ง€์‹œํ‚ค๋Š” ๊ฒƒ์ด๋‹ค .

Alarm ์˜ ๋ชฉ์ ์€๋ด‰์‡„๋˜์–ด ์žˆ๋Š”

recvfrom ์„ ์ค‘์ง€์‹œํ‚ค๋Š” ๊ฒƒ์ด๋‹ค .

PointPoint

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

156

http://www.kwanghee.net/http://www.kwanghee.net/

Race Conditions - Signal case (2)

void dg_cli( โ€ฆ ){ Setsockopt( sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) ); ... Sigemptyset( &sigset_alrm ); Sigemptyset( &sigset_alrm ); Sigaddset( &sigset_alrm, AIGALRM );

Signal( SIGALRM, recvfrom_alarm );

while ( โ€ฆ ) { Sendto( sockfd, โ€ฆ ) Sigprocmask( SIG_BLOCK, &sigset_alrm, NULL );

alarm(5); for ( ; ; ) {

FD_SET( sockfd, &rset );n = pselect( sockfd+1, &rset, NULL, NULL, NULL, &sigset_empty );...

} }}

int pselect( ... ){ sigprocmask( SIG_SETMASK, signask, &savemask ); /* callerโ€™s mask */ n = select( โ€ฆ ); sigprocmask( SIG_SETMASK, &savemask, NULL ); /* restore maks */}

Posix.1 ์—์„œ์ƒˆ๋กœ์šด ๊ฒƒ์ด์•ผ .๋‹จ์ˆœํ•œ ํ•จ์ˆ˜

์˜ ๊ตฌํ˜„์ด๊ตฐ ..

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

157

http://www.kwanghee.net/http://www.kwanghee.net/

Race Conditions - Signal case (3)

void dg_cli( โ€ฆ ){ Setsockopt( sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) );

Signal( SIGALRM, recvfrom_alarm );

while ( โ€ฆ ) { Sendto( sockfd, โ€ฆ )

alarm(5); for ( ; ; ) {

if ( sigsetjmp( jmpbuf, 1 ) != 0 ); break;n = Recvfrom( sockfd, recvline, โ€ฆ );...

} }}

static vois recvfsrom_alarm( int signo ){ siglongjmp( jmpbuf, 1 );}

Siglongjmp ์—์˜ํ•ด์„œ sigsetjmp ๊ฐ€

๋‹ค์Œ๋ฒˆ ํ˜ธ์ถœ์‹œ์ข…๋ฃŒ๋  ์ˆ˜

์žˆ๋„๋ก ํ•œ๋‹ค .

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network ProgrammingUnix Network ProgrammingUnix Network ProgrammingUnix Network Programming

Chapter 19.Multicasting

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

159

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข Multicast Addressโ€ข Multicasting vs Broadcasting on A LANโ€ข Multicast Socket Optionsโ€ข mcast_join() and Related Functionsโ€ข dg_cli() Functions Using Multicastingโ€ข Receiving MBone Session Announcementsโ€ข Sending and Receivingโ€ข SNTP : Simple Network Time Protocolโ€ข SNTP(Continued)โ€ข Summary

๋ณ„์ฒจ ์ฐธ๊ณ 

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

160

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข Broadcasting is normally limited to a LANโ€ข Multicasting can be used on a LAN or across a WAN.โ€ข Five socket options

โ€“ 3 that affect the sending of UDP datagrams to a multicast address, and

โ€“ 2 that affect the hostโ€™s receptions of multicast datagrams

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

161

http://www.kwanghee.net/http://www.kwanghee.net/

Multicast AddressMulticast AddressMulticast AddressMulticast Address

โ€ข IPv4 Class D Addressโ€“ range : 224.0.0.0 ~ 239.255.255.255โ€“ low order bit 28 bits : multicast group IDโ€“ 32-bit address : group addressโ€“ IPv4 Ethernet multicast address : 01:00:5e

โ€ข IPv6 Multicast Addressโ€“ high-order byte of an IPv6 multicast address : ffโ€“ special IPv6 Multicast address

โ€  ff02::1 is all-node groupโ€  ff02::2 is the all-routers group

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

162

http://www.kwanghee.net/http://www.kwanghee.net/

Multicast Socket OptionsMulticast Socket OptionsMulticast Socket OptionsMulticast Socket Options

Command Datatype Descrption

IP_ADD_MEMBERSHIP struct ip_mreq join a multicast group

IP_DROP_MEMBERSHIP struct ip_mreq leave a multicast group

IP_MULTICAST_IF struct in_addr specify default interface for outgoing multicasts

IP_MULTICAST_TTL u_char specify TTL for outgoing multicasts

IP_MULTICAST_LOOP u_char enable or disable loopback of outgoing multicasts

IPV6_ADD_MEMBERSHIP struct ipv6_mreq join a multicast group

IPV6_DROP_MEMBERSHIP struct ipv6_mreq leave a multicast group

IPV6_MULTICAST_IF u_int specify default interface for outgoing multicasts

IPV6_MULTICAST_TTL int specify TTL for outgoing multicasts

IPV6_MULTICAST_LOOP u_int enable or disable loopback of outgoing multicasts

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

163

http://www.kwanghee.net/http://www.kwanghee.net/

Receiving MBone Session AnnouncementsReceiving MBone Session AnnouncementsReceiving MBone Session AnnouncementsReceiving MBone Session Announcements

โ€ข MBoneโ€“ multimedia conference

โ€ข SAPโ€“ Session Announcement Protocol

โ€ข SDPโ€“ Session Description Protocol

์šฉ์–ด ์ •๋ฆฌ๋งŒ ํ•˜๋Š”๊ตฐโ€ฆ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

164

http://www.kwanghee.net/http://www.kwanghee.net/

SNTPSNTP(Simple Network Protocol)(Simple Network Protocol)SNTPSNTP(Simple Network Protocol)(Simple Network Protocol)

โ€ข NTP(Network Time Protocol)โ€“ sophisticated protocol for synchronizing clocks across a WAN

or LAN, and โ€“ can often millisecond accuracy

โ€ข SNTPโ€“ common for a few hosts on a LAN to synchronize their clocks

across the Internet to other NTP hosts, andโ€“ then redistribute this time on the LAN using either

broadcasting or multicasting

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

165

http://www.kwanghee.net/http://www.kwanghee.net/

SummarySummarySummarySummary

โ€ข Multicast application starts by joining the multicast group assigned to the applicationโ€“ tell the IP layer to join the group

โ€ข Using hardware filtering reduces the load on all the other hosts that are not participating in the application

โ€ข 5 Five socket optionโ€“ join a multicast group on an interfaceโ€“ leave a multicast group,โ€“ set the default interface for outgoing multicasts,โ€“ set the TTL or hop limit for outgoing multicasts,โ€“ enable or disable loopback of multicasts

for receiving

for sending

http://www.kwanghee.net/http://www.kwanghee.net/

Unix Network ProgrammingUnix Network ProgrammingUnix Network ProgrammingUnix Network Programming

Chapter 20Advanced UDP Sockets

๋“œ๋””์–ด reliable UDP ์†Œ์ผ“์„

๋งŒ๋“œ๋Š” ์†Œ์‹์ด๋„ค์—ฌ ~

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

167

http://www.kwanghee.net/http://www.kwanghee.net/

ContentsContentsContentsContents

โ€ข Introductionโ€ข Receiving Flags, Destination IP address, and Interface Indexโ€ข Datagram Truncationโ€ข When to Use UDP Instead of TCPโ€ข Adding Reliability to a UDP ApplicationAdding Reliability to a UDP Applicationโ€ข Biding Interface Addressesโ€ข Concurrent UDP serversโ€ข IPV6 Packet Informationโ€ข Summary

UDP ์ „๋ฌธ๊ฐ€ ์ˆ˜์ค€

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

168

http://www.kwanghee.net/http://www.kwanghee.net/

Datagram TruncationDatagram TruncationDatagram TruncationDatagram Truncation

โ€ข When a UDP datagram arrives that arrives that is larger than the applicationโ€™s buffer, recvmsg sets the MSG_TRUNC flag.

โ€ข 3 ๊ฐ€์ง€ ๊ฐ€๋Šฅํ•œ ์‹œ๋‚˜๋ฆฌ์˜คโ€“ Discard the exess bytes and return the MSG_TRUNC flag to the applic

ation. This requires that the application call recvmsg to receive the flag

โ€“ Discard the excess bytes but do not tell the applicationโ€“ Keep the excess bytes and return them in subsequent read operations

on the socketsolaris 2.5

BSD/OS

early ver. of SVR4

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

169

http://www.kwanghee.net/http://www.kwanghee.net/

When to Use UDP Instead of TCPWhen to Use UDP Instead of TCPWhen to Use UDP Instead of TCPWhen to Use UDP Instead of TCP

โ€ข Advantages of UDPโ€“ support broadcasting & multicastingโ€“ has no connection setup or teardown

โ€  UDP : RTT+SPT (T/TCP ๋Š” UDP ์™€ ๋™์ผ )โ€  TCP : 2 X RTT + SPT

โ€ข only TCP Featureโ€“ Positive acknowledgments, retransmission of lost

packets, duplication detection, and sequencing of packets reordered by the network

โ€“ Windowed flow controlโ€“ Slow start and congestion avoidance

UDP ์™€ TCP ์˜ ์žฅ์ ์€

์ด๋Ÿฐ๊ฑฐ๊ตฐ

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

170

http://www.kwanghee.net/http://www.kwanghee.net/

When to Use UDPWhen to Use UDPWhen to Use UDPWhen to Use UDP

โ€ข Recommendationsโ€“ UDP must be used for broadcast or

multicast applicationโ€“ UDP can be used for simple request-

reply applications but error detection must be built into the application

โ€“ UDP should notnot be used for bulk data transfer

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

171

http://www.kwanghee.net/http://www.kwanghee.net/

Adding Reliability to a UDP ApplicationAdding Reliability to a UDP ApplicationAdding Reliability to a UDP ApplicationAdding Reliability to a UDP Application

โ€ข 2 features to our clientโ€“ TimeoutTimeout / RetransmissionRetransmission to handle datagrams

โ€  โ€“ Sequence numbersSequence numbers so the client can verify reply

โ€  ์‚ฌ์šฉ์˜ˆ ) DNS, SNMP, TFPT, RPC ๋“ฑ

โ€ข Retransmission ambiguity Problem

var4 rttsrttRTO

client serverrequest lost

reply

request

RTO

retransmit

lost request

request

reply

request

reply lost

request

reply

request

client server client server

RTO too short

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

172

http://www.kwanghee.net/http://www.kwanghee.net/

static sigjmp_buf jmpbuf;{ โ€ฆโ€ฆ form request signal(SIGALRM, sig_alrm); rtt_newpack();sendagain: sendto(); alarm(rtt_start()); if (sigsetjmp(jmpbuf, 1) !=0) { if (rtt_timeout() ) give up goto sendagain; } do { recvfrom(); } while(wrong sequence#); alarm(0); rtt_stop(); process reply(); โ€ฆโ€ฆ}void sig_alarm(int signo) { siglongjmp(jmpbuf, 1);}

Adding Reliability to a UDP Adding Reliability to a UDP ApplicationApplication

Adding Reliability to a UDP Adding Reliability to a UDP ApplicationApplication

Outline of RTT

functions

establish signal handler

initialize rexmt counter to 0set alarm for RTO seconds

double RTO, retransmitted enough?

Retransmit

turn off alarm

calculate RTT and update estimators

UDP reliable

์‰ฝ๊ตฌ๋งŒ ~

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

173

http://www.kwanghee.net/http://www.kwanghee.net/

Concurrent UDP Server(1)Concurrent UDP Server(1)Concurrent UDP Server(1)Concurrent UDP Server(1)

client

server(parent)

port 69

server(child)

port 2134

fork

1st datagram

from cli

ent

1st reply from server;all remaining datagramsbetween client & server

creates socket, bindsrecvfrom, blocks untilclient reqeust, fork,another recvfrom

create new socket, bind ephemeral port(2134), process clients request, exchange additional datagrams with client

์ด๊ฑด ํ•œ ํด๋ผ์ด์–ธํŠธ๊ฐ€

๋‘๊ฐœ์˜ request ๋ฅผ ๋™์‹œ์— ํ•˜๋ฉด ๋ฌธ์ œ๊ฐ€

๋ฐœ์ƒํ•˜๋Š”๊ตฐ

Process involved in stand-aloneconcurrent UDP server

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

174

http://www.kwanghee.net/http://www.kwanghee.net/

Concurrent UDP server(2)Concurrent UDP server(2)Concurrent UDP server(2)Concurrent UDP server(2)

client

inetd

port 69

TFTPserver

port 69

TFTPserver(child)

port 2134

1st data

gram fr

om clien

t

1st reply from server;all remaining datagramsbetween client & server

fork, exec

fork

create socket, binds well-known portwhen client request arrives, fork a childand turn off selectability on UDP 69

recvfrom of client datagram,fork a child, then exit

Create new socket, bind ephemeralport, process clientโ€™s request, exchangeadditional datagrams with client on new socket

์Œ ๋ฐ”๋กœ์ด ๋ฐฉ๋ฒ•์œผ๋กœ TFTP ๋Š”ํ•œ ํด๋ผ์ด์–ธํŠธ๊ฐ€ 2 ๊ฐœ์ด์ƒ๋ฌผ์–ด๋ณด๋Š” ๊ฒƒ์„ ํ•ด๊ฒฐํ•˜๋Š”๊ตฐ

UDP concurrent serverinvoked by inetd

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

175

http://www.kwanghee.net/http://www.kwanghee.net/

SummarySummarySummarySummary

โ€ข IP_RECVDSTADDR / IP_RECVIF socket options can be enabled to return this information as ancillary data with each datagrams

โ€ข UDPโ€“ broadcasting or multicastingโ€“ simple request-reply scenariosโ€“ Not used for bulk data transfer

โ€ข Added reliabilityโ€“ by detecting lost packets using a timeout and retransmissionโ€“ RTT / timestamp

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

176

http://www.kwanghee.net/http://www.kwanghee.net/

Race Conditions - Signal case (4)

void dg_cli( โ€ฆ ){ Setsockopt( sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on) );

Pipe( pipefd );

Signal( SIGALRM, recvfrom_alarm );

while ( โ€ฆ ) { Sendto( sockfd, โ€ฆ )

alarm(5); for ( ; ; ) {

FD_SET( sockfd, &rset );FD_SET( pipefd[0], &rset );if ( ( n=select( โ€ฆ ) ) < 0 ) { if ( errno == EINTR ) continue; else err_sys( โ€œselect errorโ€ );}if ( FD_ISSET( socfd, &rset ) ) { n = Recvfrom( sockfd, .. );}

โ€ฆโ€ฆ Continue

Continue โ€ฆ..if ( FD_ISSET( pipefd[0], &rset ) ) { Read( pipefd[0], &n, 1 ); /* timer expired */ break;}

} }}

static vois recvfsrom_alarm( int signo ){ Write( pipefd[1], โ€œโ€, 1 ); return;}

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 21 Chap. 21 Out-of-Band DataOut-of-Band DataChap. 21 Chap. 21 Out-of-Band DataOut-of-Band Data

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

178

http://www.kwanghee.net/http://www.kwanghee.net/

Out-of-Band DataOut-of-Band Data๋ž€โ€ฆ๋ž€โ€ฆ ? (1)? (1)Out-of-Band DataOut-of-Band Data๋ž€โ€ฆ๋ž€โ€ฆ ? (1)? (1)

โ€ข Out-of-band data ๋Š” normal(โ€œinbandโ€) data ๋ณด๋‹ค ๋†’์€ priority ๋ฅผ ๊ฐ€์ง

โ€ข TCP ๋Š” urgent mode ๋ฅผ ์ œ๊ณตโ€ฆ

1 Nsocket send buffer

send(fd, โ€œaโ€, 1, MSG_OOB);

1 Nsocket send buffer

OOB

TCP urgent pointer

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

179

http://www.kwanghee.net/http://www.kwanghee.net/

Out-of-Band DataOut-of-Band Data๋ž€โ€ฆ๋ž€โ€ฆ ? (2)? (2)Out-of-Band DataOut-of-Band Data๋ž€โ€ฆ๋ž€โ€ฆ ? (2)? (2)

1 Nsocket receive buffer

1. SIGURG ๋ฐœ์ƒ 2. select ์‚ฌ์šฉ์‹œ์—๋Š” except_set ready

1 Nsocket receive buffer

TCP urgent pointer

OOB

recv(fd, โ€ฆ, MSG_OOB);

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

180

http://www.kwanghee.net/http://www.kwanghee.net/

Example: Client-Server Heartbeat FunctionsExample: Client-Server Heartbeat FunctionsExample: Client-Server Heartbeat FunctionsExample: Client-Server Heartbeat Functions

client

sig_alrm(){ if (++cnt > 5) exit(); send(MSG_OOB); alarm(1);}

sig_urg(){ recv(MSG_OOB); cnt = 0;}

server

sig_alrm(){ if (++cnt > 5) exit(); alarm(1);}

sig_urg(){ recv(MSG_OOB); send(MSG_OOB); cnt = 0;}

once asecond

once asecond

data

echoed data

OOB byte

OOB byte

one TCP connection

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 22 Chap. 22 Signal-Driven I/OSignal-Driven I/OChap. 22 Chap. 22 Signal-Driven I/OSignal-Driven I/O

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

182

http://www.kwanghee.net/http://www.kwanghee.net/

Signal-Driven I/OSignal-Driven I/OSignal-Driven I/OSignal-Driven I/O

โ€ข 3 Steps to use signal-driven I/O with a socket (SIGIO)1. A signal handler must be established for the SIGIO signal

โ€ป signal(SIGIO, sigio_handler);2. The socket owner must be set

โ€ป fcntl(fd, F_SETOWN, getpid());3. Signal-driven I/O must be enabled for the socket

โ€ป fcntl(fd, O_ASYNC, on);

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

183

http://www.kwanghee.net/http://www.kwanghee.net/

When to drive SIGIOWhen to drive SIGIOWhen to drive SIGIOWhen to drive SIGIO

โ€ข SIGIO with UDP Socketsโ€“ a datagram arrives for the socketโ€“ an asynchronous error occurs on the socket

โ€ข SIGIO with TCP Socketsโ€“ a connection request has completed on a listening socketโ€“ a disconnect request has been initiatedโ€“ a disconnect request has completedโ€“ half of a connection has been shut downโ€“ data has arrived on a socketโ€“ data has been sent from a socket (i.e., the output buffer has free spa

ce)โ€“ an asynchronous error occurred

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 23 Chap. 23 ThreadsThreadsChap. 23 Chap. 23 ThreadsThreads

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

185

http://www.kwanghee.net/http://www.kwanghee.net/

What is Threads?What is Threads?What is Threads?What is Threads?

โ€ข Comparison to forkโ€ฆโ€“ fork is expensive (e.g., memory is copied, all descriptors are duplicated, and so onโ€ฆ)โ€“ IPC is required to pass info. between the parent and child

โ€ข Threadsโ€“ all threads within a process shareโ€ฆ

โ€  process instructionsโ€  most dataโ€  open files (e.g., descriptors)โ€  signal handlers and signal dispositionsโ€  current working dirโ€  user ID and group ID

โ€“ each thread has its ownโ€ฆโ€  thread IDโ€  set of registers, including PC and SPโ€  stackโ€  errnoโ€  signal maskโ€  priority

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

186

http://www.kwanghee.net/http://www.kwanghee.net/

Basic Thread FunctionsBasic Thread FunctionsBasic Thread FunctionsBasic Thread Functions

โ€ข int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void * (*func) (void *), void *arg);

โ€ข int pthread_join(pthread_t tid, void **status);โ€ข pthread_t pthread_self(void);โ€ข int pthread_detach(pthread_t tid);โ€ข void pthread_exit(void *status)

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

187

http://www.kwanghee.net/http://www.kwanghee.net/

TCP Echo Server Using ThreadsTCP Echo Server Using ThreadsTCP Echo Server Using ThreadsTCP Echo Server Using Threads

#include "unpthread.h"

static void *doit(void *); /* each thread executes this function */

intmain(int argc, char **argv){ int listenfd, *iptr; socklen_t addrlen, len; struct sockaddr *cliaddr;

if (argc == 2) listenfd = Tcp_listen(NULL, argv[1], &addrlen); else if (argc == 3) listenfd = Tcp_listen(argv[1], argv[2], &addrlen); else err_quit("usage: tcpserv01 [ <host> ] <service or port>");

cliaddr = Malloc(addrlen);

for ( ; ; ) { len = addrlen; iptr = Malloc(sizeof(int)); *iptr = Accept(listenfd, cliaddr, &len);

Pthread_create(NULL, NULL, &doit, iptr); }}

static void *

doit(void *arg)

{

int connfd;

connfd = *((int *) arg);

free(arg);

Pthread_detach(pthread_self());

str_echo(connfd); /* same function as before */

Close(connfd); /* we are done with connected socket */

return(NULL);

}

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

188

http://www.kwanghee.net/http://www.kwanghee.net/

More Else about ThreadsMore Else about ThreadsMore Else about ThreadsMore Else about Threads

โ€ข Thread-Specific Dataโ€“ int pthread_once(pthread_once_t *onceptr, void (*init)(void));โ€“ int pthread_key_create(pthread_key_t *keyptr, void (*destructor)(void

*value)โ€“ void *pthread_getspecific(pthread_key_t key);โ€“ int pthread_setspecific(pthread_key_t key, const void *value);

โ€ข Mutexes: Mutual Exclusionโ€“ int pthread_mutex_lock(pthread_mutex_t *mptr);โ€“ int pthread_mutex_unlock(pthread_mutex_t *mptr);

โ€ข Condition Variablesโ€“ int pthread_cond_wait(pthread_cond_t *cptr, pthread_mutex_t *mptr);โ€“ int pthread_cond_signal(pthread_cond_t *cptr);

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

189

http://www.kwanghee.net/http://www.kwanghee.net/

Chap.24 - IP Options

โ˜ž IP Options ์˜ ์ข…๋ฅ˜

โ˜ž IPv4 Source Route Options

โ˜ž IPv6 Extension Headers

โ˜ž IPv6 Routing Header

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

190

http://www.kwanghee.net/http://www.kwanghee.net/

We must study โ€ฆ ?

IP option ์˜ ์ข…๋ฅ˜

program ์˜ˆ๋ฅผ ๊ฐ€์ง€๊ณ  ์‚ฌ์šฉ๋ฒ•์„ ์•Œ์•„๋ณธ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

191

http://www.kwanghee.net/http://www.kwanghee.net/

IP Option ๋“ค์˜ํฌ๊ธฐ๋Š” 40byte ๋กœ

์ œํ•œ๋œ๋‹ค .(IPv4)

IP Option ์˜ ์ข…๋ฅ˜

1. NOP : no-operation, padding 1byte

2. EOL : end-of-list, indicate option end

3. LSRR : loose source and record route

4. SSRR : strict source and record route

5. Time stamp

6. Record route

7. Basic security

8. Extended security

9. Stream identifier

10. Router alert

getsockopt ์™€ setsockopt ํ•จ์ˆ˜์—์„œ

level = IPPROTO_IP, optname = IP_OPTIONS ๋กœ

ํ•˜์—ฌ ๊ฐ’์„ ์–ป์–ด ์˜ค๊ณ  ์„ค์ •ํ•œ๋‹ค .

getsockopt ์™€ setsockopt ํ•จ์ˆ˜์—์„œ

level = IPPROTO_IP, optname = IP_OPTIONS ๋กœ

ํ•˜์—ฌ ๊ฐ’์„ ์–ป์–ด ์˜ค๊ณ  ์„ค์ •ํ•œ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

192

http://www.kwanghee.net/http://www.kwanghee.net/

IPv4 source route option

โ˜ž ์†ก์‹ ๋‹จ์— ์˜ํ•ด ๋ช…์‹œ๋˜๋Š” IP ์ฃผ์†Œ๋ก๋“ค์˜ ๋ชฉ๋ก

โ˜ž ์ˆ˜์‹ ๋‹จ์ด ์ƒˆ ๋ชฉ๋ก์„ ๋ฐ›์„ ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๊ณ  , ์†ก์‹ ๋‹จ์œผ๋กœ ๋˜๋Œ์•„ ๊ฐ€๋Š” ๋ฐ˜๋Œ€ ๊ฒฝ๋กœ๋ฅผ ๋”ฐ๋ผ์„œ ๊ฑฐ๊พธ๋กœ ๊ฐˆ ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค .

SSRRdatagram ์€ ๋ฐ˜๋“œ์‹œ ๊ธฐ๋ก๋œ ๊ฐ๊ฐ์˜ node ๋“ค์„

ํ†ต๊ณผํ•ด์•ผํ•˜๊ณ  , ์˜ค์ง ๊ธฐ๋ก๋œ node ๋งŒ์„ ์ง€๋‚˜๊ฐˆ ์ˆ˜ ์žˆ๋‹ค .

LSRRdatagram ์€ ๊ธฐ๋ก๋œ ๊ฐ๊ฐ์˜ node ๋“ค์„ ํ†ต๊ณผํ•ด์•ผ

ํ•˜์ง€๋งŒ๊ธฐ๋ก๋˜์ง€ ์•Š์€ ๋‹ค๋ฅธ node ๋“ค์„ ํ†ต๊ณผํ•  ์ˆ˜๋„ ์žˆ๋‹ค .

โ€ป Kernel ์— ์˜ํ•ด์„œ ์ˆ˜์‹ ๋œ source route ์ˆœ์„œ์˜ ๋ฐ˜๋Œ€๋กœ IP address ๊ฐ€ ์ •๋ ฌ๋˜์–ด application ์œผ๋กœ ๋„˜์–ด์˜จ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

193

http://www.kwanghee.net/http://www.kwanghee.net/

NOP code len ptrIP addr #1 IP addr #2 โ€ขโ€ขโ€ขโ€ขโ€ขIP addr #3 dest IP addr

1 1 1 14 bytes 4 bytes 4 bytes 4 bytes

44 bytes

Send : to kernel by setsockoptSend : to kernel by setsockopt

1 1 1 1 4 bytes 4 bytes 4 bytes 4 bytes

44 bytes

Receive : to application by getsockoptReceive : to application by getsockopt

NOP code len ptr IP addr #1 IP addr #2 โ€ขโ€ขโ€ขโ€ขโ€ข IP addr #9 dest IP addr

code : LSRR - 0x83, SSRR - 0x89

len : code ~ dest IP addr ๊นŒ์ง€์˜ byte ์ˆ˜

ptr : ๊ฒฝ๋กœ์—์„œ ์ˆ˜ํ–‰๋  ๋‹ค์Œ ๋ฒˆ IP ์ฃผ์†Œ์˜ offset

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

194

http://www.kwanghee.net/http://www.kwanghee.net/

> tcpcli01 -g sejong -g cupid feelhihi

# tcpserv01received IP options, len = 16received LSRR: 150.150.55.52 150.150.55.53 150.150.55.55

> tcpcli01 -g cupid -g danwon -g sejong feelhihi

# tcpserv01received IP options, len = 20received LSRR: 150.150.55.52 150.150.55.55 150.150.55.54 150.150.55.53 child 21180 terminated

Example

์ถœ ๋ฐœ ์ง€ ๊ฒฝ ๋กœ

์ถœ๋ฐœ์ง€์™€ ๋ชฉ์ ์ง€๋Š”IP header ์—

์žˆ์œผ๋ฏ€๋กœ ๊ตณ์ด ์–ป์–ด๋‚ผํ•„์š”๊ฐ€ ์—†๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

195

http://www.kwanghee.net/http://www.kwanghee.net/

IPv6 extension headers

1. Hop-by-hop option(0) : currently non-defined

2. Destination option(60) : currently non-defined

3. Routing header(43) : source routing option

4. Fragmentation header(44)

5. Authentication header(51)

6. ESP(Encapsulating security payload) header(50)

IPv6 ๋Š” ์•„์ง๊ตฌ์ฒดํ™”๋œ ๊ฒƒ์ด ์—†์–ด .

์ข€ ๋‘๊ณ  ๋ด์•ผํ•  ๊ฒƒ ๊ฐ™์•„ ..

โ€ป ( ) : IP next header field value. if value is 59, no next header

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

196

http://www.kwanghee.net/http://www.kwanghee.net/

IPv6 routing header

Nextheader

Header extensionlength

Routing type = 0 Segments left

reserved 0 123

22

21

2 3 โ€ขโ€ขโ€ขโ€ขโ€ขโ€ข

Address 0 (128 bit)

โ€ขโ€ขโ€ขโ€ขโ€ขโ€ข

Address 1 (128 bit)

Address 23 (128 bit)

0 : loose hop , 1: strict hop

0 7 8 15 16 23 24 31

1 ~ 23 ์˜ ๊ฐ’

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

197

http://www.kwanghee.net/http://www.kwanghee.net/

Chap.25 - Raw Socket

โ˜ž Raw socketโ€™s features

โ˜ž Raw socket creation, output, input

โ˜ž Ping program

โ˜ž Traceroute program

โ˜ž ICMP message daemon

Contents

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

198

http://www.kwanghee.net/http://www.kwanghee.net/

We must study โ€ฆ ?

Raw socket ์˜ ํŠน์ง•

Raw socket ์„ ์ด์šฉํ•œ programming

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

199

http://www.kwanghee.net/http://www.kwanghee.net/

Raw socketโ€™s features

1. ICMPv4, IGMPv4, ICMPv6 packet ์„ ์ฝ๊ณ  ์“ธ ์ˆ˜ ์žˆ๊ฒŒ ํ•œ๋‹ค .

Ex) ping program

2. Kernel ์— ์˜ํ•ด ์ฒ˜๋ฆฌ๋˜์ง€ ์•Š๋Š” IPv4 protocol field ๋ฅผ ๊ฐ€์ง„ IPv4 datagram ์„ ์ฝ๊ณ  ์“ธ ์ˆ˜ ์žˆ๋‹ค .

Ex) OSPF routing protocol - protocol field โ€˜89โ€™cf) ICMP-1, IGMP-4, TCP-6, UDP-17

๊ด€๋ฆฌ์ž ํŠน๊ถŒ

๊ด€๋ฆฌ์ž ํŠน๊ถŒ์—์„œ์‚ฌ์šฉํ•  ๋งŒํ•œ ํŠน์ง•

์ด๊ตฌ๋‚˜

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

200

http://www.kwanghee.net/http://www.kwanghee.net/

Raw socket creation, output, input

์˜ค์ง ๊ด€๋ฆฌ์ž๋งŒ์ด raw socket ์„ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค .

sockfd = socket( AF_INET, SOCK_RAW, protocol )

IP_HDRINCL socket option ์„ค์ •

const int on = 1;if ( setsockopt( sockfd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on) ) < 0 )

error

Bind

local address ๋ฅผ ์„ค์ •ํ•œ๋‹ค .

Connect

์™ธ๋ถ€ ์ฃผ์†Œ๋ฅผ ์„ค์ •ํ•œ๋‹ค .

Creation

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

201

http://www.kwanghee.net/http://www.kwanghee.net/

์ •์ƒ์ ์ธ ์ถœ๋ ฅ์€ sendto๋‚˜ sendmsg ์ค‘ ํ•˜๋‚˜๋ฅผ ํ˜ธ์ถœํ•˜๊ณ  destination IP ์ฃผ์†Œ๋ฅผ ์ง€์ •ํ•˜์—ฌ ์ด๋ฃจ์–ด์ง„๋‹ค .

Ex] sendto( sockfd, sendbuf, len, 0, pr->sasend, pr->salen );

IP_HDRINCL ๊ฐ€ ์„ค์ •๋ผ ์žˆ์ง€ ์•Š์œผ๋ฉด kernel ์ด IP header ๋ฅผ ๋งŒ๋“ค๊ณ  process ๋กœ๋ถ€ํ„ฐ data ์— ์ฃผ์†Œ๋ฅผ ๋ง ๋ถ™์ด๊ธฐ ๋•Œ๋ฌธ์— data ์˜ ์‹œ์ž‘ ์ฃผ์†Œ๋Š” IP header ๋’ค์˜ ์ฒ˜์Œ byte ๋ฅผ ๋ช…์‹œํ•œ๋‹ค .

IP_HDRINC ๊ฐ€ ์„ค์ • ๋ผ ์žˆ์œผ๋ฉด ์“ฐ๋ ค๊ณ  ํ•˜๋Š” kernel ์„ ์œ„ํ•œ ์‹œ์ž‘ ์ฃผ์†Œ๋Š” IP header ์˜ ์ฒ˜์Œ byte ๋ฅผ ๋ช…์‹œํ•œ๋‹ค .

kernel ์€ ์ถœ๋ ฅ interface MTU ๋ฅผ ์ดˆ๊ณผํ•˜๋Š” ์ˆœ์ˆ˜ packet ์„ ์ž‘์€ ์กฐ๊ฐ์œผ๋กœ

๋งŒ๋“ ๋‹ค .

Output

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

202

http://www.kwanghee.net/http://www.kwanghee.net/

์ˆ˜์‹ ๋œ UDP packets ๊ณผ TCP packets ์€ ์ ˆ๋Œ€๋กœ raw socket ์œผ๋กœ ์ „๋‹ฌ๋˜์ง€ ์•Š๋Š”๋‹ค . Process ๊ฐ€ ์›ํ•œ๋‹ค๋ฉด data link ๊ณ„์ธต์—์„œ ์ฝํ˜€์ ธ์•ผ ํ•œ๋‹ค .

kernel ์ด ICMP message ๋ฅผ ์ฒ˜๋ฆฌํ•œ ํ›„์— ๋Œ€๋ถ€๋ถ„์˜ ICMP packet ๋“ค์€ raw socket ์œผ๋กœ ์ „๋‹ฌ๋œ๋‹ค . Echo, timestamp, ์ฃผ์†Œ ์„ ๋ณ„ ์š”์ฒญ์€ ์ „์ ์œผ๋กœ kernel ์— ์˜ํ•ด์„œ ์ฒ˜๋ฆฌ๋œ๋‹ค .

kernel ์ด IGMP message ๋ฅผ ์ฒ˜๋ฆฌํ•œ ํ›„์— ๋ชจ๋“  IGMP packet ๋“ค์€ raw socket ์œผ๋กœ ์ „๋‹ฌ๋œ๋‹ค .

kernel ์ด ์ดํ•ดํ•˜์ง€ ๋ชปํ•˜๋Š” protocol field ๋ฅผ ๊ฐ€์ง„ ๋ชจ๋“  IP datagram ์€ raw socket ์œผ๋กœ ์ „๋‹ฌ๋œ๋‹ค .

datagram ์ด fragment ๋˜์–ด์„œ ๋„์ฐฉ๋˜๋ฉด ๋ชจ๋“  ์กฐ๊ฐ๋“ค์ด ๋„์ฐฉํ•ด์„œ ์žฌ์กฐํ•ฉ๋  ๋•Œ๊นŒ์ง€ ์•„๋ฌด๊ฒƒ๋„ raw socket ์œผ๋กœ ์ „๋‹ฌ๋˜์ง€ ์•Š๋Š”๋‹ค .

input

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

203

http://www.kwanghee.net/http://www.kwanghee.net/

Ping program

mainmain

readloop

recvfrom proc_v4

proc_v6

or

sig_alrm (1sec)sig_alrm (1sec)

send_v4

send_v6

or

Establish signal handler

for SIGALRM

infinite receive loop send an echo request once a second

Function diagramFunction diagram

Raw socket ์ƒ์„ฑ ํ›„ data ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋ฉฐ

๋ฌดํ•œ loop

Raw socket ์ƒ์„ฑ ํ›„ data ๋ฅผ ๊ธฐ๋‹ค๋ฆฌ๋ฉฐ

๋ฌดํ•œ loop

Raw socket ์— ์ˆ˜์‹ ๋œ๋ชจ๋“  data ์ฝ์Œ

Raw socket ์— ์ˆ˜์‹ ๋œ๋ชจ๋“  data ์ฝ์Œ

ICMP message์ฒ˜๋ฆฌ์™€ ์ถœ๋ ฅ

ICMP echo requestmessage ์ƒ์„ฑ๊ณผ ์ „์†กICMP echo request

message ์ƒ์„ฑ๊ณผ ์ „์†ก

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

204

http://www.kwanghee.net/http://www.kwanghee.net/

Traceroute program โ˜ž Host ์—์„œ destination host ๋กœ์˜ datagram flow ๊ฒฝ๋กœ๋ฅผ trace

ํ•œ๋‹ค .

โ‘  TTL( ๋˜๋Š” hop count) ์„ 1 ๋กœ ์„ ์ •ํ•œ UDP datagram ์„ destination์œผ๋กœ ๋ณด๋‚ธ๋‹ค .

โ‘ก First hop router ๋กœ๋ถ€ํ„ฐ ICMP โ€˜time exceeded in transitโ€™ ์ˆ˜์‹ 

โ‘ข TTL ์„ ํ•˜๋‚˜์”ฉ ์ฆ๊ฐ€ ์‹œํ‚ค๋ฉด์„œ UDP datagram ์„ destination ์œผ๋กœ ๋ณด๋‚ธ๋‹ค .

โ‘ฃ โ‘ข์„ ๋ฐ˜๋ณตํ•˜๋ฉด ๊ณ„์† ์ค‘๊ฐ„ hop host ๋กœ๋ถ€ํ„ฐ ICMP โ€˜time exceeded in transitโ€™ ๊ฐ€ ์ˆ˜์‹ ๋œ๋‹ค .

โ‘ค Destination host ์— ๋„์ฐฉ์„ ํ•˜๋ฉด ICMP โ€˜port unreachableโ€™ ์ด ์ˆ˜์‹ ๋œ๋‹ค .

source destinationhop 1 hop 2

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

205

http://www.kwanghee.net/http://www.kwanghee.net/

ICMP Message daemon

icmpd

ICMPv4 ICMPv6

Listening Unix domain streamsocket, bound to /tmp/icmpd

raw socket raw socket

icmpd

ICMPv4 ICMPv6

Listening Unix domain streamsocket, bound to /tmp/icmpd

raw socketUDP socket

UDP

application

raw socket

Unix domain stream connection

โ‘ 

โ‘ก

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

206

http://www.kwanghee.net/http://www.kwanghee.net/

โ‘ข

icmpd

ICMPv4 ICMPv6

Listening Unix domain streamsocket, bound to /tmp/icmpd

UDP socket

UDP

application

raw socket

descriptor passing โ†’

Unix domain stream connection

getsockname ์„ ํ˜ธ์ถœํ•˜์—ฌ UDP socket ์˜port number ๋ฅผ ์•Œ์•„๋‚ธ๋‹ค .

๊ทธ๋ ‡๊ฒŒ ํ•จ์œผ๋กœ์จ icmp daemon ์ด UDP socket ์—๊ด€๋ จ๋œ icmp message ๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค .

getsockname ์„ ํ˜ธ์ถœํ•˜์—ฌ UDP socket ์˜port number ๋ฅผ ์•Œ์•„๋‚ธ๋‹ค .

๊ทธ๋ ‡๊ฒŒ ํ•จ์œผ๋กœ์จ icmp daemon ์ด UDP socket ์—๊ด€๋ จ๋œ icmp message ๋ฅผ ์ฒ˜๋ฆฌํ•œ๋‹ค .

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

207

http://www.kwanghee.net/http://www.kwanghee.net/

icmpd

ICMPv4 ICMPv6

Listening Unix domain streamsocket, bound to /tmp/icmpd

raw socketUDP socket

UDP

application

raw socket

Unix domain stream connection

โ‘ฃ

select ๋‚˜ poll ๋กœdata ๋ฅผ ๊ธฐ๋‹ค๋ฆฐ๋‹ค .select ๋‚˜ poll ๋กœ

data ๋ฅผ ๊ธฐ๋‹ค๋ฆฐ๋‹ค .

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 26 Chap. 26 Datalink AccessDatalink AccessChap. 26 Chap. 26 Datalink AccessDatalink Access

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

209

http://www.kwanghee.net/http://www.kwanghee.net/

IntroductionIntroductionIntroductionIntroduction

โ€ข Datalink access providesโ€ฆโ€“ The ability to watch the packets received by the datalink layerโ€“ The ability to run certain programs as normal applications instead of a

s part of the kernel(e.g., RARP server)โ€ข Common methods to access the datalink layer

โ€“ BSD Packet Filter(BPF)โ€“ SVR4 Data Link Provider Interface (DLPI)โ€“ Linux SOCK_PACKET interfaceโ€“ libpcap, the publicly available packet capture library

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

210

http://www.kwanghee.net/http://www.kwanghee.net/

Packet Capture Using BPFPacket Capture Using BPFPacket Capture Using BPFPacket Capture Using BPF

Application Application

process

kernel

buffer buffer

filter filter

BPF datalink

IPv4 IPv6

copy of received packet

copy of transmitted packet

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

211

http://www.kwanghee.net/http://www.kwanghee.net/

Packet Capture Using DLPIPacket Capture Using DLPIPacket Capture Using DLPIPacket Capture Using DLPI

Application Application

process

kernel

bufmod(buffer)

bufmod(buffer)

pfmod(filter)

pfmod(filter)

datalink

IPv4 IPv6

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

212

http://www.kwanghee.net/http://www.kwanghee.net/

Linux: SOCK_PACKETLinux: SOCK_PACKETLinux: SOCK_PACKETLinux: SOCK_PACKET

โ€ข fd = socket(AF_INET, SOCK_PACKET, htons( ETH_P_ALL ));

ETH_P_ALLETH_P_IP

ETH_P_ARPETH_P_IPV6

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

213

http://www.kwanghee.net/http://www.kwanghee.net/

libpcap Example:libpcap Example:Examining the UDP Checksum FieldExamining the UDP Checksum Fieldlibpcap Example:libpcap Example:Examining the UDP Checksum FieldExamining the UDP Checksum Field

main

open_pcap test_udp

udp_write

send_dns_query

calls:pcap_lookupdevpcap_open_livepcap_lookupnetpcap_compilepcap_setfilterpcap_datalink

udp_read

udp_read

next_pcap

pcap_next

pcap_dispatch

pcap_read

read getmsg recvfrom(BPF) (DLPI) (Linux)

process

kernel

appl.

libpcap

http://www.kwanghee.net/http://www.kwanghee.net/

Chap. 27 Chap. 27 Client-server Design AlternativesClient-server Design AlternativesChap. 27 Chap. 27 Client-server Design AlternativesClient-server Design Alternatives

๊ด‘ํฌ๋„ท๊ด‘ํฌ๋„ท

215

http://www.kwanghee.net/http://www.kwanghee.net/

Alternative TCP Server ModelsAlternative TCP Server ModelsAlternative TCP Server ModelsAlternative TCP Server Models

โ€ข Preforking serverโ€“ No Locking around accept (BSD only)โ€“ File Locking around acceptโ€“ Thread Locking around acceptโ€“ Descriptor Passing

parent

child N

child 3

child 2

child 1

โ€ฆ

fork

fork

fork

fork

client 2

client 1

pool ofavailablechildren

Prethreading serverโ€“ per-Thread accept

โ€“ Main Thread accept

END