Вы находитесь на странице: 1из 464

Linux

2001

www.books-shop.com

32.973.26
018.2.75
681.3.07
""

""
: info@williamspublishing.com, http://www.williamspublishing.com

, .
Linux. : . . . :
"", 2001. 464 .: . : . .
ISBN 5
8459
0193
6 (.)

Linux. ,
, . ,


( , HTTP),
UDP .
, TCP/IP,
.

Java C++.

RPC, SSL,
IPv6.
,
,

.
32.973.26
018.2.75

.

, ,

, Sams
Publishing.
Authorized translation from the English language edition published by Sams Publishing Copyright 2001
All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, elec

tronic or mechanical, including photocopying recording or by any information storage retrieval system, without
permission from the Publisher.
Russian language edition published by Williams Publishing House according to the Agreement with R&I En

terprises International, Copyright 2001

ISBN 5
8459
0193
6 (.)
ISBN 0
672
31935
7 (.)

"", 2001
Sams Publishing, 2001

www.books-shop.com


I.
1.

23
24

2. TCP/IP

41

3. Internet

58

4.

79

5.

99

II.
6.
7. :

115
116
131

8. 

167

9.

188

10.

213

III. 

231

11.

232

12. Java

248

13. C++
14. 

263
279

IV.
15. (RPC)

291
292

16.
308
17. , 326
18.

336

19. IPv6: IP

345

V.
.

357
358

379

. API

407

434

www.books-shop.com

19

I.
1.

: TCP/IP
:
socket()



:
.

2. TCP/IP
IP

Internet
,



IP




UNIX
: IP
3. Internet

version
header_len
serve_type
ID
dont_frag, more_frag frag_offset
time_to_live (TTL)
protocol
options
data




tcpdump

:
4. .
,


23
24
27
28
29
30
32
35
39
40
41
42
42
43
45
46
46
48
50
50
52
56
56
57
58
59
61
61
62
62
62
63
63
64
64
64
65
67
75
76
77
78
79
80
80
80
82

www.books-shop.com

: HTTP
HTTP
HTTP
,
,


/




UDP
UDP


.


:
:
5.




.
OSI
1:
2:
3:
4:
5:
'
6:
7:
Internet
1:
2: (IP)
2: (ICMP)
3: (UDP)
3: (TCP)
4:
OSI IP

:
II.
6.
:





84
84
84
85
86
87
88

'

89
90
92
93
94
94
95
96
96
97
97
98
99
100
100
102
103
104
105
105
106
107
107
107
108
108
108
108
109
110
110
111
112
112
113
113
115

,'

116
117
118
119
121
122
123
124

www.books-shop.com

?
?
?
?
?
?
?
?
?
: HTTP
:
7. :
:





_clone()

:


Pthreads



:

()

8. 
: ?
?






.


'


poll() select()

: 
9.



125
125
125
125
126
126
126
126
127
127
130
131
132
134
135
136
136
139
142
145
155
155
156
158
158
159
159
160
162
163
166
167
168
170
170
171
172
173
175
176
177
179
180
181
182
185
186
188
189
189
191
193

www.books-shop.com

select()
, ,

,.

select()

select()




IP
IPv6
TCP

:
.

 :
send()

recv()

10.



SIGPIPE
SIGURG
SIGCHLD
SIGHUP
SIGIO
SIGALRM


("")

,









:

195
195
196
197
198
199
200
201
203
205
206
206
207
208
208
208
209
209
212
213
214
215
217
218
219
219
220
220
220
221
221
221
223
223
223
224
224
225
226
227
228
228
229
230

III. 

231

11.

:
:
:
 :

232
233
233
234
235
235
236

www.books-shop.com

' .

.







: 
12. Java


UDP

 Java



. . .


.




'
13. C++
C++?


'


10

236
237
238
238
239
240
241
241
241
241
242
242
242
242
243
243
243
243
244
244
244
245
245
245
246
246
246
247
248
249
250
253
254
256
256
257
258
258
259
259
259
260
261
262
262
263
264
264
264
265
265
265
266

www.books-shop.com

.!





 
,


/


:
14. 







friend












:
.
IV.
15. (RPC)
OSI







RPC rpcgen
rpcgen







%RRNVVKRS

piracy@books-shop.com

267
269
271
274
275
277
278
278
278
278
279
280
280
281
281
282
282
282
283
283
284
284
284
285
285
286
286
287
287
288
288
289
291
292
293
294
294
295
297
298
298
299
300
300
300
302
304
305
305
305
306
306

11

: RPC
307
16.
308

309

309

310
Internet
310

311

311
TCP/IP
312

313

313

313

314

316

318

319

319

319
SSL
320
OpenSSL
320
SSL
321
SSL
323
:
324
17. , 326

327
IP
327

328

329

329

330

332

332

333

'
334
:
335
18.
336
'
337
ICMP
337
IP
337

338

338

339

339
ICMP
339

340
IP

341

341
ping
341
MyPing
342
MyPing
342

'
343
:
344

12

www.books-shop.com

19. IPv6: IP


IPv6
.
IPv4 IPv6?
IPv6


IPv4 IPv6
IPv6
ICMPv6

IPv6
Linux
:

345
346
346
346
348
348
348
349
349
351
352
352
354
354
355

V.

357

.
:
socket()
: socket()

Internet ( 100 )
HTTP 1.1
( get/setsockopt())

ICMP
IPv4
IPv6
Ko lCMPv6
IPv6
IPv6
.

socket()
bind()
listen()
accept()
connect()
socketpair()

send()
sendto()
sendmsg()
sendfile()
recv()
recvfrom()
recvmsg()

shutdown()

htons(),
htonl()
ntohs(),
ntohl()

358
359
363
364
365
366
368
372
' 374
375
375
376
377
378
379
380
380
381
382
383
384
385
386
387
388
389
390
391
393
394
395
395
396
396
397

13

www.books-shop.com

inet_addr()
inet_aton()
inet_ntoa()
inet_pton()
inet_ntop()

getpeername()
gethostname()
gethostbyname()
getprotobyname()

setsockopt()
getsockopt()
. API

fork()
_clone()
exec()
sched_yield()
wait(), waitpid()

pthread_create()
pthread_ join()
pthread exit()
pthread_detach()

pthread_mutex_init(), pthread_mutex_destroy()
pthread_mutex_lock(), pthread_mutex_trylock()
pthread_mutex_unlock()
~

signal()
sigaction()
sigprocmask()

bzero(), memset()
fcntl()
pipe()
poll()
read()
select()
write()
close()
.
C++
Exception ()
NetException ()
C++
SimpleString ()
HostAddress ()
C++
Message ( )
TextMessage ()
C++

14

397
398
399
399
400
401
401
402
403
404
405
405
406
407
408
408
409
410
412
413
415
415
416
416
417
418
418
419
420
421
421
422
423
424
424
425
427
427
429
430
432
433
434
435
435
435
436
436
436
437
437
437
438

www.books-shop.com

Socket()
SocketStream ()
SocketServer ()
SocketClient ()
Datagram ()
Broadcast ()
MessageGroup ()
Java
java.io.lOException ()
java.net.SocketException ()
Java
java.net.DatagramPacket ()
java.net.lnetAddress ()
 Java
java.io.lnputStream ( )
java.io.ByteArraylnputStream ()
java.io.ObjectlnputStream ()
java.io.OutputStream ( )
java.io.ByteArrayOutputStream ()
java.io.ObjectOutputStream ()
java.io.BufferedReader ()
java.io.PrintWriter ()
Java
java.netSocket ()
java.net.ServerSocket ()
java.net.DatagramSocket ()
java.net.MulticastSocket ()

438
440
440
440
441
441
442
442
442
443
443
443
444
444
445
445
445
446
447
447
448
449
450
450
451
452
453
454

15

www.books-shop.com

www.books-shop.com


1990 .

, ,

. 1988 .

.
,

BSD
. , Hewlett
Packard,
(PostScript PCL),
LaserJet 4 .
8052,

UNIX, Linux, HP
UX, Ultrix, SunOS
System V. ,

,

, .

, ,

, Java C++. 1998 .

Java
Java. Nationwide Enterprise

www.books-shop.com


.
, ,

.
, ,
.
,

Linux, ,

, . , ,

,
.

www.books-shop.com


,
, .
, ,

. ,
, .

, , ,


.
Linux (

) . ,

, .

.
,
, .

. ,
.

,

.
I, " "
,

, ,

.
II, " "
, ,

.
III, "

.



.
IV, " "
,

, , IPv6
.

19

www.books-shop.com

V,""
, .
,

.
.
Web

, HTML PDF, RFC

HTML.

.
: ,

, .
.
.


.
.
.

. "
" , ,

.
. , ,

, .
,

. , ,
.
. , ,
, (, , API

). .
,

, .

,
. , :
Java (

);
;
.
(

). Linux

. , ,
:

20

www.books-shop.com

, C++
Java;
;
;
.
,
.
, , ,
, ,

.
.

. ,

..
, .

Internet RFC
(Request For Comments

). ,
, [RFC875].

%RRNVVKRS

piracy@books-shop.com

21

www.books-shop.com

...
1.
2. TCP/IP
3. Internet
4. 

5.

www.books-shop.com

...

27

: TCP/IP

28

29

40

www.books-shop.com


. ! . !

.
CMOS! ! ?
, .
.
? , ?!

, . ,

. Internet

. , , ,

, , ..

.
.
,
.
, , ? ,
:
;
, , ;
, ,

;
, .
,
, .

, .
,

( ,
). ,

.

. ,
.
. :
() (). , ,
.
: ,
(
).
() (), .
,

(. /etc/services), ,
.

1.

25
www.books-shop.com

,
, , , ,
, : inetd . 
127.0.0.1 (a
). , Linux 
,
.

.
. , : "

?" ,

. :

. ,

.
: ,
, .
,
(. 1.1).
,

. 1.1. ,

.
1. . .
2.

26

().

. ,
( 9, "

").

I.

www.books-shop.com

3.

/ ().

IP
, . ,
IP

( 2, "
TCP/IP").

4.

/ ().

. ,
.

5. ().
: . ,

.
6.

/ ().

, , .

7.

. , :


, .
:




.
, UNIX UUCP (UNIX
to

UNIX ).
. ,

.
,

, .

.
Socket API (Application Programming
Interface) .

,

. ,

. ,

1.

27

www.books-shop.com

7, " :

", "" 10,


" ".
.

, .

II, " ".


Internet .
,

. , .
().
,
( )

,
. .
.
.

:
TCP/IP
.

,
.

.
TCP/IP (Transmission Control Protocol/Internet Protocol)

.
,
,

. , .
,
.
TCP/IP : ,
, , .
Socket API .

UNIX,

. , TCP/IP,
.
, , ,

, , on() (

) fopen () ( )

. (TCP/IP,

28

I.

www.books-shop.com

IPX, Rose) socket().


.
,

. ,

, .
, Internet, IP

, 32
.
, , .
TCP/IP .

, .
, ,

.
IP
: [0
255]. [0
255].[0
255].[0
255],

123.45.6.78. 0 255 .
,

( IP
2, "
TCP/IP"). :
[0255].[0255].[0255].[0255]:[065535]
, 128.34.26.101:9090 (IP
128.34.26.101, 9090)!

:
[0255].[0255].[0255].[0255].[065535]
, 6 4 . 3 . 2 4 . 2 4 . 9 9 9 9 (IP
64.3.24.24, 9999).

, .

IP
65000 ,
( 2, " TCP/IP").

:

,

, .
, ,
13. , Linux

, ,

/etc/inetd.conf. ,

BSD, HP
UX Solaris,

.
, .

Telnet 21 (FTP):

* telnet 127.0.0.1 21

1.

29
www.books-shop.com

. Telnet FTP
,

, 1.1.

, . .
1.1. TCP
/***********************************/
/*** ***/
/***********************************/



. ,
.

.
.
socket()
socket() ,


/ .
Linux/UNIX. n(),

,
socket () , .
,
. :
#include <sys/socket.h>
#include <resolv.h>
int socket(int domain, int type, int protocol);
.
, " ".
. 1.1.
1.1. socket ()

domain

PF_INET
PF_LOCAL

type

30

PF_IPX
PF_INET6
SOCK_STREAM

IPV4; TCP/IP
BSD;
,
Novell
'
IPv6; TCP/IP
( )
(TCP)

I.

www.books-shop.com

. 1.1
SOCK_RDM

(
)

SOCK_RDM

(
)

SOCK_DGRAM
(UDP  User Datagram Protocol)
SOCK_RAW
protocol



32
( 2, " TCP/IP").

: 0 (), SOCK_RAW
0 255

, ,

: domain=PF_INET, type=SOCK_STREAM, protocol=0.

PF_

AF_
" socket ()
PF_ (protocol family ).
F_ (address family ). 
, .
TCP :

int sd;
sd = socket(PF_INET, SOCK_5TREAM, 0);
sd ,

int fd;
fd = open(...);
socket ()
errno.
.
EPROTONOSUPPORT.

. protocol
.
EACCES. .
SOCK
RAW PF_PACKET
root.
EINVAL. .

domain type.
, ,
. Linux :

1.
%RRNVVKRS

piracy@books-shop.com

31

#include <sys/socket.h>
#include <sys/types.h>
#include <resolv.h>

/* */
/*
*/
/*
*/

sys/socket.h Socket API


( socket(), ). sys/types.h
, .

resolv.h, c
. , Mandrake
6.0
7.0 , sys/types.h (
netinet/in.h, , ).
, Linux UNIX .
socket () ,
. n(),

bind().
, ,
, . bind(),
connect( )
,
. (
bind(), ; 4,
" ").

connect ( ) , .
, ,

. IP
.

, IP
.
, ,

. ,
.
, , ,
.
,

.
,
. , ,

32

I.

www.books-shop.com

( )
.
connect () :
#include <sys/socket.h>
iinclude <resolv.h>
int connect(int sd, struct sockaddr *server, int addr_len);
(sd) ,
socket(). , ,
sockaddr, ,
. , socket()


.
socket () : PF_INET PF_IPX.
.
sockaddr.
connect(). (

, " ".

sockaddr .
sockaddr 8 ,
. ,
, sockaddr. 
. 
. ,
: push, (), () ..
sockaddr _family :
, . 16
.


PF_INET ( ):
struct sockaddr {
struct sockaddr_in {
unsigned short int sa_family;
sa_family_t
sin_family;
unsigned char sa_data[14];
unsigned short int sin_port;
};
struct in_addr
sin_addr;
unsigned char
_
pad[];

sockaddr
, socket ( ), , 
sockaddr ( :
PF_, AF_). , PF_INET6, 
AF_INET6,
.
' ,
: sa_family sin family
. , ,

1.

33

www.books-shop.com

. ,
( 2, " TCP/IP").

(sa_data _pad) .

sockaddr sockaddr_in
16 ( IPv6 sockaddr_in6 24 ),
.
, , , __pad[] .
,

, (

sockaddr_in ).
sockaddr_in .
, ,

, .

.
,
.

sin family
sin port
sin addr



IP

AF_INET
 13
127.0.0.1

connect(),

. 1.2 , (
Web
). , Linux
sockaddr_in sockaddr.
, .
sockaddr
UNIX sockaddr. 
. 
, , ( Linux 
).

1.2. connect ()
/***
/***

,
connect().

***/
***/

idefine PORT_TIME
13
struct sockaddr_in dest;
char *host  "127.0.0.1";
int sd;
/**** ****/

bzero(Sdest, sizeof(dest));
dest.sin_family = AF_INET;
34

/* */
/* */

I.

www.books-shop.com

dest.sin_port = htons ( PORT_TIME ) ;


inet_aton(host, &dest.sin_addr) ;

/* */
/* */

if ( connect (sd, &dest, sizeof (dest)) != 0 ) /* ! */


{
perror ( " socket connection " ) ;
abort();

.
sockaddr_in. ,
, .

, , ,
socket(). bzero() sockaddr_in .
sin_family AF_INET. IP

. htons () inet_aton(),

, 2, " TCP/IP".
, .

, connect().
, .
, sd,


, .

(, HTTP 1.0

). , ,
.

, , . .
,

. : "!"
.
,

read ( ) :
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
.

, (fd),
(sd). read( ):
int sd, bytes_read;
sd = socket (PF_INET, SOCK_STREAM, 0);

/* */

/**** ****/

1.

35

www.books-shop.com

bytes_read = read(sd, buffer, MAXBUF);


/* .*/
if ( bytes_read < 0 )
/* ; */
(FILE*),

.

, ,

f s c a n f ( ) (,
, ):
char Name[NAME], Address[ADDRESS], Phone[PHONE];
FILE *sp;
'

int sd;
sd = socket(PF_INET, SOCK_STREAM, 0);

/* */

/**** ****/
if ( (sp = fopen(sd, "r")) == NULL ) /*
FILE* */

perror("FILE* conversion failed");


else if ( fscanf(sp, "%*s, %*s,
%*s\n",

/*
*/
NAME, Nm, ADDRESS, Address,
PHONE, Phone) < 0)

perror("fscanf");

FILE*. : UDP
. ,

, .
, :
, . ,
FILE*, .
, . (
3, " Internet
".)
, ,

. ,
, :
, fprintf() f s c a n f ( ) . ,
,
fscanf ( ) , .


,
. 
. 
. .

36

I.

www.books-shop.com

read(), ,

.
EAGAIN.
,

. ,

.
EBADF. ,
. , socket ()
(
).
EINVAL. ,
.
read() , . Linux
, recv(),

:
/
#include <sys/socket.h>
#include <resolv.h>
int recv(int sd, void *buf, int len, unsigned int flags);
, read(),

(1 | 2 | ...). .
,
recv()? He read()? :
recv() ,
. , ,


.
,
. , "
".
MSG_OOB, .
. ,
:

. ,
( 10,
" ").
MSG_PEEK. .
, .

,
(, ;
" ").
MSG_WAITALL. ,

, "
". "" .
MSG _DONTWAIT. ,

. (
)

1.

37
www.books-shop.com

. ,
, , .
, , ,

, EWOULDBLK. (

Linux .
, ' f c n t l ( ) 0_NONBLOCK.

.)

. , 
.
recv(), . 
MSG_PEEK recv()
: , 500 , 750.
MSG_WAITALL.
recv() , read(). ,

( read()):
int bytes_read;
bytes_read = recv(sd, buffer, MAXBUF, 0);
:
int bytes_read;
bytes_read = recv(sd, buffer, MAXBUF, MSG_PEEK);
:
int bytes_read;
bytes_read = recv(sd, buffer, MAXBUF, MSG_OOB | MSG_PEEK);

. ,

.
.
, ?

, .
, .
recv() , read(),
.
ENOTCONN.
.
ENOTSOCK. ,

, socket().

38

I.
www.books-shop.com

, read() ,
, ,
, recv().

,
.
, .

close():

#include <unistd.h>
int close(int fd);
(fd) (sd)

0.

, . 
""
. , . 6 
,
.

close () .
EBADF. .
shutdown()

, .
, stdin
stdout.
shutdown
shutdown () shutdown (. 8 
UNIX), .
shutdown() ,
:
Iinclude <sys/socket.h>
int shutdown(int s, int how);
how .

0
1
2

1.

39

www.books-shop.com

:
TCP
,
. .

. ,
(. 1.2).
1.2. ,

1. socket():
,

2. connect():

,

bind()
3. , 



( )
()

( )

()
()

()

4.
5. , 

6. () 

7. , .
, 
.
,
(, )

8.
, connect().
,
, (

, , ,

..). Socket API

. socket(),
. "" .
read()
write() J .
recv().
TCP/IP , .
IP
,
, .

40

I.

www.books-shop.com

TCP/IP

2
...
IP

43

IP

49

51
57

UNIX
: IP

57
58

%RRNVVKRS

piracy@books-shop.com

Internet .
. ,

, , .
, .
Socket API ,

IP
, ,

IP
TCP/IP .

IP

. ,
, .

. ,
Internet.

( )
.
, .

Bob Sasha, ,

.
. .

,  
( ). ; ,
, . , 
(, DHCP). (
)

.
,

. ,
. ,
, , '
,
, .
.

, ,
.
, .

.
, , ,


(Media Access Control
). Ethernet.

42

I.

www.books-shop.com


, .

Ethernet 6
, 0 0 : 2 0 : 4 5 : F E : A 9 : O B .
, .
,

. .
,
.
,

.
,

( , ).
,

. ,
: ( ) ( ).
IP
.
IP

. , (
).

, ,

. IP

ARP (Address Resolution Protocol

) [RFC826].
ARP
ARP IP . 
, 
.  ,
. 
, , IP
. , ARP, 
. , ,  
.
, , I.

Internet
Internet " ".
. ,
, (. 2.1).

. 2.1. IP! ,

2. TCP/IP

43

www.books-shop.com

IP
.
. ,
, , .

, ,
, , , , .
Internet .
, :
.

. .

0.0.0.00.255.255.255
1.0.0.0 126.255.255.255

()
2242, 16777214 .
126 .
, 

. Internet
127.0.0.0 127.255.255.255
( )
128..0.0191..255.255
2162, 65534  .
64x256 .
,
,
. 
( , 129.5.0.0). 

8
192...0  223.xxx.xxx.255 2 2, 254 .
32x65536 .

Internet
224.0.0.0239.255.255..255
2282, 268435454 .
, 

240.0.0.0255.255.255.255
2282, 268435454 .

. ,
255.255.255.255 
IP

, ,

. ,

0. 1,

0.
: 0 (00000000)
126 (01111110)
: 128 (10000000) 191 (10111111)
: 192 (11000000)
223 (11011111)
D: 224 (11100000) 239 (11101111)
: 240 (11110000)
255 (11111111)
Internet
( 4 ) ,

44

I.

www.books-shop.com

CIDR (Classless Internet Domain Routing

).
(

RFC
15171519).
IP
.

, :

, .
: ,

. , ,
, ,

. ,
.

, ,

, .

, ,
, .

.
, 16 , ,

. Linux

, , , .
CIDR,
.
.

. ,
. , .
, .
,

, ,

187.35.209.208.
208 (11010000). , ,

ll0lxxxx, !
. : 187.35.209.208 (),
187.35.209.209 ( 1) .. 187.35.209.222.

.


. .
, .
. , , , , 
187.35.209.223. , 
, : 11011111.
( ) , 
.

2. TCP/IP

45

www.books-shop.com

, .
,
,


Internet .
,
. ,
( ),
.
,

,
( ) .
,
, .
, .
, , ,

, . ,

, ,

. .
,
. .

IP

, ,

. , ..
. (

), ,

. ,

, ARP


.
Ethernet ,

. , ,
,
Ethernet IP
. ARP.


, .
: ( ),
( ). ,

, ,
2. : .
.
: 0.0.0.0 0.255.255.255 127.0.0.0 127.255.255.255.

46

I.

www.books-shop.com

"" . ,

128.187.0.0, 0.0.25.31

128.187.25.31.
1992 . Internet (TAB Internet Activities
Board) [RFC 1160], Internet
(Internet Architecture Board),
Internet.

, 450 .

, 2% .
?
, .
, .

.

, , 128 .
30. 10 ,
. ,
,


.

. ,
. Internet

. .
?

?
Internet (ICANN Internet Corporation for Assigned Names and Numbers)
,
,
.
DHCP (Dynamic Host
Configuration Protocol

) [RFC2131], IP

. IP
.
,

.
, , ,

DHCP.

, DHCP. ,
(
) .

.

. ,
IP! ( ).

2. TCP/IP

47

www.books-shop.com

IP
, 
. . ping 127.0.0.1 
. , . Red Hat Linux
( ) /etc/sysconfig/
network

/etc/sysconfig/networkscripts/ifcfg*.
IP
.

IPv6 [RFC2460].

: 128 , 32! :
8008:4523:FOE1:23:830:CF09:1:385

,
.
IPv6

38
. 310

( 19, "IPv6:
IP").

IP
. ,
, ,

. ,

. TCP/IP .
, .
. TCP/IP ,
.
: ,

.
IP

. 16
.

. (
read() recv()). ,
( write() send()),

.
.

,
, EINVAL.
,
SO_REUSEADDR ( 9,
" ").

, ,
; , : ,
.
, ,
, .

48

I.

www.books-shop.com

.
/etc/services ( , "

"). .

1
7
9

tcpmux

TCP

echo

discard

/dev/null

13
20
21
23
25

daytime

smtp, mail

UNIX

37

time, timeserver

42
70
79
80

nameserver

(DNS)

gopher

Gopher

ftpdata

FTP

ftp

F

telnet

Telnet

finger

Finger

www, http

Web

.
Telnet.
/etc/services : , , .

: ,
(, Mandrake Linux ). ,
/etc/services, .
.

.
bind(). bind() ,
.

, 
, 1024, root. , 
( 13), root
, SUID. "set
user ID" . . SUID
, , 
. , /usr/bin/at ( 
) cron, root.
. 
. UNIX. : SUID
. ,
, , .

2. TCP/IP

49

www.books-shop.com

, ,

.
. Linux BSD
:
1024 .

, :
* , (
root);
*

::
* .


.
, .
. :
( ) ( ). ,

, , ,

, . , 214259635.

557.
:
:
:

00

01
5

02
57

03

04
...

, () .

:
:
:

00

01
57

02
5

03
DC

04
...

().

. ,
. ", ,

ASCII
?" ,
. ,

,
. ,

, . ,

, .

,

. ,
? ,
. ,

sockaddr. :

50

I.

www.books-shop.com

. 1,
" ":
/**************************************************************/
/***
:
***/
/***
sockaddr_in.
***/
struct sockaddr_in dest;
char *dest_addr = "127.0.0.1";
dest.sin_family = AF_INET;
dest.sin_port = htons(13); /* 13 ( ) */
if (inet_aton(dest_addr, &dest.sin_addr) == 1) {
: sin_family, sin_port sin_addr.

, .
. sin_port (13)
htons(), .

htons ()

htonl()

ntohs ()

ntohl ()

16 

32 

16 

32 

, " ".

, ,

,
.
inet_aton() IP
ASCII
, (..
htonl()).
.

inet_aton() (###.###.###.###)
; ,

inet_addr() ( inet_aton()), ; 
1 ( 255.255.255.255
)
inet_ntoa() IP,
, ASCII
gethost
( www.linux.org)
byname ()
IP

2. TCP/IP
%RRNVVKRS

piracy@books-shop.com

51

.
, .
,
" ".

, , , :
Linux ,
. . 
,
.


. write():
#include <unistd.h>
ssize_t write(int fd, const void *buf, size_t count);
read(),
, .
,

.
EBADF.

. ,
( ,

socket()).
EINVAL. ,

. , .
EFAULT. . buf
,
,
EPIPE.
,
. ,
, SIGPIPE, ,
write() EPIPE.
. :
1) ;
2) ,
( );
3) .
,
write ():

52

I.

www.books-shop.com

int sd, bytes_written = 0, retval;


sd = socket(PF_INET, SOCK_STREAM, 0);
/*** ***/
while ( bytes_written < len)
/* , */
{
/* */
retval = write(sd, buffer+bytes_written, len);
if ( retval >= 0)
bytes_written += retval;
else
/* */
}
fprintf (),
, FILE*:
FILE *sp
int sd;
Sd = socket(PF_INET, SOCK_STREAM, 0);

/*** ***/
sp = fdopen(sd, "w");
/*
*/
if ( sp == NULL)
perror("FILE* conversion failed");
fprintf(sp, "%s, %s, %s\n", Name, Address, Phone);
,

while . ,
, .
, FILE*

, .
send(),

.
,
recv(). :
#include <sys/socket.h>
#include <resolv.h>
int send(int sd, const void *msg, int len, unsigned int flags);
, write().

, ,

.
MSG_OOB. .
,

. ,
SIGURG.
MSG_DONTROUTE. .

2. TCP/IP

53

www.books-shop.com

. ,
ENETUNREACH ( ).
.
MSG_DONTWAIT. He send().

, .
,

SIGIO.

send (), ,
errno EAGAIN.
MSG_NOSIGNAL. He SIGPIPE.

,

SIGPIPE. ,
.
.

send():
/************************************************************/
/***

****/
/*************************************************************/
int bytes_sent;
bytes_sent = send(sd, buffer, MAXBUF, 0);
/*

*/
int bytes_sent;
bytes_sent = send(sd, buffer, MAXBUF, MSG_OOB | MSG_NOSIGNAL);

send().
EBADF. . ,

socket ().
ENOTSOCK. .
EMSGSIZE. ,
.

(
) ,
.
EAGAIN. ,

.
, , " ".

.
EPIPE. .
SIGPIPE, MSG_NOSIGNAL.
send()

. , Finger,

79, .

54

I.

www.books-shop.com

,
( Web
):
/***************************************************************/
/*** : ****/
/*** .
****/
int main(int count, char *strings[])
{ int sockfd;
struct sockaddr_in dest;
char buffer[MAXBUF];
/* */
sockfd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&dest, sizeof(dest));
dest.sin_family = AF_INET;
dest.sin_port = htons(atoi(strings[2]));
inet_addr(strings[1], &dest.sin_addr.s_addr);
/* */
if ( connect(sockfd, sdest, sizeof(dest)) != 0 )
PANIC("connect() failed");
sprintf(buffer, "%s\n", strings[3]);
sendfsockfd, buffer, strlen(buffer), 0);
/* */
bzero(buffer, MAXBUF);
recv(sockfd, buffer, MAXBUF
1, 0);
printf("%s", b u f f e r ) ;
close(sockfd);
return 0;
}


, :
/************************************************/
/*** , ***/
/*** .
***/
/*************************************************/
/* */
do
{
bzero(buffer, MAXBUF);
bytes = recv(sockfd, buffer, MAXBUF, 0);
printf("%s", buffer);

}
while ( bytes > 0);
close(sockfd);
,

. "".
,

. ,

, .
, .

2. TCP/IP

55

www.books-shop.com


.
,
. .

PF LOCAL

TCP/IP
Novell
AppleTalk

PF_INET
PF_IPX
PF_APPLETALK

; 

TCP/IP
Novell
AppleTalk

,
" ".

, Socket API,

. , ,
, ,

TCP/IP.

UNIX
: ,
? ,

Socket API.

( ) . ,
.

; ,

.
, :
TCP, UDP.

sockaddr. :
/****************************************************************/
/***

****/
/****************************************************************/
linclude <sys/un.h>
int sockfd;
struct sockaddr_un addr;
sockfd = socket(PF_LOCAL, SOCK_STREAM, 0);
bzerof(&addr, sizeof(addr));
addr.sun_family = AF_LOCAL;
strcpy(addr.sun_path,
"/tmp/mysocket");
/* */
if ( bind(sockfd, Saddr, sizeof(adrr)) != 0 )
perror("bind() failed");
. sun_path

104 ( NULL).

56

I.


www.books-shop.com

.
/tmp,
. , .

: IP$

Socket API

. ,

.
TCP/IP ,

: , ,
ARP
.

, ""

.
TCP/IP .


. .
, ,

.
Socket API ,
(inet_addr(), inet_aton(), inet_ntoa()),
(htons(), ntohs(), htonl()).

TCP UDP.

Internet

2. TCP/IP

57

www.books-shop.com


Internet

60

65

77


tcpdump

77

79

79

www.books-shop.com

, Novell (IPX), Microsoft (NetBEUI), AppleTalk ,


, TCP/IP. ,
,
.

, .
Internet : ,
ICMP, UDP ( ) TCP (
). (. 3.1).
,
, .

. 3.1. Socket API


,
, ?

, : ,
. ,
.

, (, UUCP),

.
IP (Internet Protocol) [RFC791] ,
: , .

.
, , ,
.
Internet.
( , ),
.

3. Internet

59

www.books-shop.com


.
, .
. 
( ) , o . ,
Linux .
2, " TCP/IP",
() . ,
( 3.1) (. 3.2) .

4
6

OF MF

10
12

16

( 40 )

20

( 65535 )

2060

. 3.2. IP!

3.1. IP
/****************************************************************/

/***
IP
***/
/****************************************************************/
#typedef unsigned int uint;
#typedef unsigned char uchar;
struct ip_packet {
uint version:4;
uint header_len:4;

/* */
/*
*/
uint serve_type:8; /* */
uint packet_len:16; /* */
uint ID:16;
/* */
uint _reserved:1; /* 0 */
/* , */
uint dont_frag:1;
uint more_frags:1; /* */
uint frag_offset:13; /* */

60

I.

www.books-shop.com

uint time_to_live:8; /* */
uint protocol:8;
/* : ICMP, UDP, TCP */
uint hdr_chksum:16; /* */
uint IPv4_source:32; /* IP
*/
uint IPv4_dest:32; /* IP
*/
uchar options[];
/* 40 */
uchar data[];
/* 64 */

}
, ,

, . IP

. , dont_frag

, :

.
,

3.1. .
,
.

version
IP.

, .
(. 3.1).

3.1. version

4
5
6
7
8
9

IPv4
( )
IPv6
TP/IX (Internet )
Internet ""
TUBA (TCP and UDP with Bigger Addresses TCP UDP 
)

( IP_HDRINCL).
0. ,
.

header_len

. 15 (60 ).
,

, ,
IP_HDRINCL. IP

3. Internet

%RRNVVKRS

piracy@books-shop.com

61

20 ,
5 (20/4).

serve__type
, .

: (

), (TOS type of service).

setsockopt()
: , ,

.
( 9,
" ").

ID
IP
.

16 , ,

. , ,

,
, , .
.

(IP_HDRINCL),

.

:
, . IP
. , 
.
dont_frag, more__frag frag_offset
.

(). ""
. ,
.

, 
Linux.
(, ). , "
, . 
,
.

62

I.

www.books-shop.com

dont_frag ,

. , ,
, ICMP

.
more_frags ,

. (

).

0.
frag_offset ,
. ,
. ,
. frag_offset 13
64 .

8 .

, ( ) 8.
: IP

time_to_live (TTL)
,

( ),
.
time_to_live 8 ,
255 , .
, .
, ,
.

"" .
time_to_live IP_TTL
( 9, " "). ,
.

protocol
Internet : ICMP
(IPPROTO_ICMP, 1), UDP (IPPROTO_UDP, 17) TCP (IPPROTO_TCP, 6).
, .
, socket()

SOCK_RAW.

netinet/in.h. (He
, , ,
.)

3. Internet

63

www.books-shop.com

options
IP
.
, , ,

.. 40 .

,
.

data
, 65535
( 60 ).
. , ICMP
4 , UDP 8, TCP 20
60.
IPv4.


Internet ,

. IP
,

.
, , .
TCP, UDP, ICMP
. (. 3.2).
3.2.
 ICMP

() 2060

2060+[4]

()

65535

65535

UDP

TCP

2060+[20
60]
( )
65535


2060+[8]

, ,

. , ,
.

64

I.

www.books-shop.com

, . 3.2.

, , .

, ,

,
, .
( )

, .

. . 3.2 .

,

. , TCP,

, IP
(65536 ).

, , .

. ,
. .
,

. , .
,
. ,
, .
,

. ,
.

. , ,
. ,
, Telnet, HTTP,

, .. ,
.

3. Internet

65

www.books-shop.com

HTTP
HTTP 1.0 UDP, TCP.
,
. , .

. , .

, .

, :
, .
,

. ,
, .
, .
,

.
CRC
(Cyclical Redundancy
Check ).

,
.
.

.
. ,
/: ,
..
, ,


. , , ,
, .
,

. ,
FTP, Web
, /.
,

. ,

, Web
.
,
.
, .

, .

66

I.

www.books-shop.com

,
.

, , , , .
,

. ,

, ,

.
, . ,

IP,
. .

.
, ,
, .
, , ,
.


, .

IP
.
.
. 3.3.
3.3.
()
()

2060
65535 (65515 )
( )

( )
( )

Linux TCP/IP
( Internet
5,
" "). TCP/IP
IP
.
.

3. Internet

67

www.books-shop.com

IP
,
socket () SOCK_RAW.

, , ,
root.

IP
. :

.
UDP, .
.
, .

, .

18,
" ".
ICMP
ICMP (Internet Control Message Protocol
Internet) IP.
, Internet (, ,

), , .
, traceroute
ping. . 3.4.
3.4. ICMP
()
()

2464
65535 (65511 )
( , )

( , )
( , )
( )

ICMP,

.
sendmsg() sendto() (

). .
ICMP ,
.
, . ,
ICMP .

:
. ,
.
ICMP
.
, ,
, .
IP, ICMP IP
,

( 3.2).

68

I.

www.books-shop.com

3.2. ICM
/***
/***
/***

*/
***/
***/
***/

ICMP.

netinet/ip_icmp.h.

typedef unsigned char ui8;


typedef unsigned short int ui16;
struct ICMP_header {
ui8 type;
/*
ui8 code;
/*
ui16 checksum; /*
uchar msg[]; /*

*/
*/
*/
*/

IP (2060 )
ICMP

2060

ICMP

2262
2464

( 65535 )

. 3.3. ICM!
, "
". msg ,

.
UDP
UDP (User Datagram Protocol )
(
).

. UDP . 3.5.
3.5. UDP
()
()

2868
65535 (65511 )

TCP/IP,
. UDP

3. Internet

69

www.books-shop.com

. ,
.
, UDP,

. , , ,
. ,
, . ICMP,

, .
, . ,

UDP,

, .
(: ,

. .)
UDP

. ,

, . ,
Internet ,

,
.
.
,

, .
UDP . ,
.
, .

. ,
.
.

. ,
.
, ,
.
CRC
.

. CRC

, , .
,

.

. ,
,

, .
, .
TCP,
.
UDP IP. UDP
IP
(. 3.4).
3.3.

70

I.

www.books-shop.com

3.3. UDP
/*** UDP
.
***/
/*** netinet/udp.h. ***/
typedef unsigned char ui8;
typedef unsigned short int ui16;
struct UDP_header {
ui16 src_port; /* */
ui16 dst_port; /* */
ui16 length;
/* */
ui16 checksum; /* */
uchar data[]; /* */

0
2060
2262
2464
2666
2868\

IP (2060 )




( 65535 )

. 3.4. UDP
UDP , $
. IP$ $
.
bind(), (. $
2, " TCP/IP").
TCP
TCP (Transmission Control Protocol ) $
, Internet. $
read() write() $
. TCP . 3.6.
3.6. TCP
()
()

40120
( )
( )

( )
( )

3. Internet
%RRNVVKRS

piracy@books-shop.com

71

,
, ,
. UDP ,
, .

TCP.
, , , .

,

. WWW,
TCP ,

UDP.

, Internet:

, .

.
, . ,
, . ,
, ( )

, . Internet
. ,
,

, , .
. ,

, ,
.
TCP ,

, . ,

10 . TCP
,
,

. , TCP

.

" " . 
' "; , 
. ' 
.
. (Nagle). 
(  9,
" ").


,
. ,
. TCP

,
, . ,
,

72

I.
www.books-shop.com

, TCP


,
.

. ,

.
UDP ,
, ,

. IP ,

.
, TCP

. ,
.
,
. TCP 536

1500 .

MSS (maximum segment size )

( 9, "

").
,

TCP
,
.

TCP . ,

TCP$
TCP ,

TCP
.
TCP UDP
.
3.4.
3.4. TCP
/*** TCP
.
***/
/*** netinet/tcp.h. ***/

/**************************************************************/
typedef unsigned char ui8;
typedef unsigned short int ui16;
typedef unsigned int ui32;
typedef unsigned int uint;
struct TCP_header {
ui16 src_port;
/* */
ui16 dst_port;
/* */
ui32 seq_num;
/* */
ui32 ack_num;
/* */

3. Internet

73

www.books-shop.com

uint data_off:4;
uint res:6;
uint urg_flag:1;
uint ack_flag:1;
uint psh_flag:1;
uint rst_flag:1;
uint syn_flag:1;
uint fin_flag:1;
ui16 window;
ui16 checksum;
ui16 urg_pos;
ui8 options[];
ui8 padding[];
uchar data[];

/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*

*/
() */
.
, */
*/
*/
*/
() */
*/
, */
*/
*/
TCP */

/* (
data[]) */
/* */

I

(2060

2060

2262

2464

90 eg

3272
3474

3676

3878

4080

|urg|ack|psh|rst|syn|fin

TCP

( 65536 )

. 3.5. TCP!
, data_off
. , header_len IP

, , , 32

.
,
.
.
TCP
, UDP.
seq_num ack_num .
, IP
(seq_num).

74

I.

www.books-shop.com

(ack_num), ,

. .
TCP

, . 3.7.
3.7.

SYN=1 (syn_flag)

()

=0 (ack_flag)
SYN=1 (syn_flag)
=1 (ack_flag)
SYN=0 (syn_flag)
ACK=1 (ack_flag)

.
().
, ,
.

, , . 3.8.
3.8. TCP

FIN=1 (syn_flag)







FIN=1

=1

=1
=1

TCP
,
. ,
.

, , , :
? ,

3. Internet

75

www.books-shop.com

.
, , ,
.
ICMP, UDP, TCP IP
. ,

. , TCP
, ICMP.

Linux TCP/IP,
.
ICMP, UDP TCP IP

. .


tcpdump
, , ,

. tcpdump ,
. "" IP
, TCP

root.
,

.

.
root, , 
. , Linux ,
, 
,
.

Ethernet
. 2, " TCP/IP",

, Ethernet 6

. .
Ethernet
OEM (Original Equipment Manufacturer 
) ( PCI PCMCIA), 
 ( Ethernet). 
, . ,
,  
. .

76

I.

www.books-shop.com

.
tcpdump ,
, .


 <>



v
vv
w <>

(
)

(, 
)
; 
,
""
( TTL )

tcpdump

.
, , ARP Ethernet
IP
. 100
:
tcpdump
v
t
100

t .

, .
tcpdump "". ,

, . ,

ping 127.0.0.1,


(
tcpdump, ), ,
, .

root.
:
sd = socket(PF_INET, SOCK_PACKET, )!,

bytes_read = recvfrom(sd, buffer, sizeof(buffer), 0, 0, 0 ) ;

: SOCK_PACKET.
, .
3. Internet

11

www.books-shop.com

. IP
,
. :
__802_3
__25
ETH_P_ALL
__802_2

802.3
.25
( !)
802.2

ETH_P_ALL. socket()
:
sd = socket(PF_INET, SOCK_PACKET, ETH_P_ALL);
recvfrom()
( ).
(, Ethernet) .
SOCK_PACKET ,

, . ,
.

IP
,

.
Web
snooper.

(Intel
) GNU

:
tcpdump

. IP ,
(ICMP), (UDP) (TCP).
.
. ICMP, UDP TCP

IP
, 20 120 .

.
TCP ,
. Internet,

. TCP

,
fprintf() fgets().
UDP
, .
,

. UDP

, .

78

I.

www.books-shop.com

...
,

82

: HTTP

86

87
92

UDP

97

100

101

www.books-shop.com

:
(TCP) (UDP).

, .
TCP , .


. UDP .
.
.

Linux ( UNIX)

socket(). (

IP, UDP TCP, 3, "


Internet
")

,
. , TCP,

. ,
. TCP

.

/ ,

.
,

.
TCP
, .
( IP) .
,
.
(
connect()) .


, fprintf() fgets().

.
TCP ,
, .

TCP , , ,


. :

80

I.

www.books-shop.com

, . ,

(
), , .
,

. ,

.
.
TCP.
:
. ,
. , ,
.

,
, . ,

.
, ,

.
.

.
TCP ,

, ,


.
, printf () .
, .
UDP, , .
.
, ,

. ,

, .
, ,

( ).
?
,
.
: ,
. , ,
, , ,

. ( UDP; TCP.)
, $
?

.
. TCP ,

, .
(
UDP;
TCP.)
,
Federal Express?
,
, . .

4. ...
%RRNVVKRS

piracy@books-shop.com

81

, .

. ,
.
"" ,

. (FedEx UDP; TCP.)


, $
,
?
: " ", " ".
.
. ,
Telnet : .
(
UDP; TCP.)
, ?
( ),
.

Web
. ( UDP;
TCP.)
$
?
,

, UDP.
, . ,
,
. ( UDP; TCP.)
, TCP,

TCP , ,
UDP. ,

connect() UDP
. ,

: UDP

. UDP


, TCP.
3, " Internet
",

, .

. UDP , connect()

.
UDP
, connect()

,
.

read() write(), TCP,

82

I.

www.books-shop.com

. 4.1

, TCP
.
4.1. UDP
/*************************************************************/
/***
UDP

***/
/***
( connected
peer.)
***/

int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_DGRAM, 0);
/* */
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(DEST_PORT);
inet_aton(DEST_IPADDR, &addr.sin_addr);
if ( connected, &addr, sizeof (addr)) != 0 ) /* ! */
perror("connect");
/* ! */
send(sd, buffer, msg_len);
/* TCP */
UDP sendto()
recvfrom() ( ). send() ,

connect!).
, , ,
,
bind(). 4.1

DEST_PORT.
bind(). ,
connect().
connect() TCP,

, .

UDP. TCP ,

.
, , UDP,

. connect() UDP
.
RDP
RDP (Reliable Data Protocol ) [RFC908, RFC1151]
, TCP,
UDP. , , ,
UDP TCP. , , Linux 

UNIX

4. ...

83

www.books-shop.com

: HTTP

HTTP. . *
.
.
,

.

.
TCP, ,

, , .
HTTP
HTTP
,
:
GET <> /1.0<r><r>

HTTP. 6,
" ", .
,
. URL

http://www.kernel.org/mirrors/, www.kernel.org
:
GET /mirrors/ HTTP/1.0<cr><cr>

. <r>

, .

, .
HTTP
.
, . 4.2
Web
.

, , HTTP
.

(stdout).
4.2. Web HTTP
/***
/***

HTTP

( http
client.c)

***/
***/

int sd;
struct servent *serv;
if ( (serv = getservbyname("http", "tcp")) == NULL )
PANIC("HTTP servent");
if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )

84

I.

www.books-shop.com

PANIC("Socket");
/* */
bzero(Sdest, sizeof(dest));
addr.sin_family = AF_INET;
addr.sin_port = serv>s_port;
/* HTTP */
if ( inet_addr(Strings[1], &dest.sin_addr.s_addr) == 0 )
PANIC(Strings[1]);
/* */
if ( connect(sd, Sdest, sizeof(dest)) != 0 )
PANIC("Connect");
/* */
sprintf(buffer, "GET %s HTTP/1.0\n\n", Strings[2]);
send(sd, buffer, strlen(buffer), 0);
/* , */

do
{
bytes_read = recv(sd, buffer, sizeof(buffer)l. 0);
buffer[bytes_read] = 0;
if ( bytes_read > 0 )
printf("%s", buffer);

}
while ( bytes_read > 0 );
, 4.2,
, .

, .

HTTP (1.1 HTTP


NG)

.
. HTTP
www.w3c.org.

, ,

). , UDP ,

, ,
. (: ,
. , .)

4. ...

85

www.books-shop.com


Linux ,

.
, , .

UDP
.
,
connect() .
send() recv().

, : sendto() recvfrom().
#include <sys/socket.h>
#include <resolv.h>
int sendto(int sd, char* buffer, int msg_len, int options,
struct sockaddr *addr, int addr_len);
int recvfrom(int sd, char* buffer, int maxsize, int options,
struct sockaddr *addr, int *addr_len);
, send() recv().
. sendto()
.
sockaddr ( 4.3).
4.3. sendto()
/**************************************************************/
/***
sendto()
***/
/**************************************************************/
int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(DEST_PORT);
inet_aton(DEST_ADDR, &addr.sin_addr);
sendto(sd, "This is a test", 15, 0, &addr, sizeof(addr));

DEST_ADDR:DEST_PORT. ,
ASCII
. .
recvfrom() ,
sendto(). ,
. ,

. , sendto()

, recvfromf)

. sockaddr
, (
, AF_INET).

86

I.

www.books-shop.com


recvf rom() . , 
PF_LOCAL, 
( ), . 
. 
, ,
.

, recvfrom()
addr_len, .
. :
/**************************************************************/
/***
recvfrom()
***/

int sd;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_DGRAM, 0);
/* */
while ()
{
int bytes, addr_len=sizeof(addr);
bytes = recvfrom(sd, buffer, sizeof(buffer), 0, fcaddr,
&addr_len);
fprintf(log, "Got message from %s:%d (%d bytes)\n",
inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
bytes);
/**** ****/
sendto(sd, reply, len, 0, &addr, addr_len);
}
while ,

addr_len ,
. addr .
, addr_len addr, recvfrom()

, .. NULL (0). UDP


, , .

addr , .

TCP .

, .
,

.
, ,

. UDP .
, , .
,
, , ,

( ).

4. ...

87

www.books-shop.com

UDP

, .
/
TCP . ,

.
,

.
(. 3, " Internet
").
TCPv3 [RFC 1644] ,
UDP, , TCP. /
(Transaction TCP) ,

sendto(). ?
TCP

. , ,

. TCP

(SYN),
()

(FIN).
TCP
,
3, "
Internet
".
,

. , SYN, FIN
.
,

?
/
.
, ,

(SYN).
, FIN,

,
(. 4.1).

,

,
(

). . 4.1. /
,
, !
!
. ,

!

.

88

I.

www.books-shop.com

/ .
:
, 540 . ,
64 . ,
, .
/
. , TCP
,
,

. .
:
/*************************************************************/
/***
/
***/
/**************************************************************/
int flag=l;

int sd;
sd = socket(PF_INET, SOCK_STREAM, 0);
if ( setsockopt(sd, IPPROTOJTCP, TCP_NOPUSH, &flag,
sizeof(flag)) != 0 )
PANIC("TCP_NOPUSH not supported");
/*** ***/
if ( sendto(sd, buffer, bytes, MSG_FIN, &caddr,
sizeof(addr)) < 0 )
PANIC("sendto");
/ TCP

setsockopt().
, ,
sendto () MSG_FIN.
/T Linux
, / Linux.
, UNIX.
Web.

, TCP ,
, ,
. / ,
.
/

.
.

, .

, ..

4. ...

89

www.books-shop.com

. ( ),

, . .
( Linux

). send()
recv() , ,

sendto() recvfrom(), .
, ,

, ,

. ,

.
, .

sockaddr Linux
Unux , 
( , ).
, , 
. bind(), sendto(), connect() recvfrom() ,
sockaddr, .
, " ".

, UDP TCP,
, ,
.
, . , /etc/services
, .


bind().
UNIX
, " ".
PF_LOCAL PF_UNIX, .
" ".


sockaddr. , ' AF_LOCAL AF_AX25 
 , AF_INET AF_IPX .
, , , (TCP UDP)
( , AF_INET).
UDP c . 
( /etc/services) .
bind() :

90

I.

www.books-shop.com

#include <sys/socket.h>
#include <resolv.h>
int bind(int sd, struct sockaddr *addr, int addr_size);
.
6, " ".

, connect().

:
/t**************************************************************/
/***
bind()
****/
/***************************************************************/
struct sockaddr addr;
int sd;
sd = socket(PF_INET, SOCK_STREAM, 0 ) ;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(MY_PORT); /* */
addr.sin_addr.s_addr = INADDR_ANY;
/* IP
*/
if ( bindfsd, Saddr, sizeof(addr)) != 0 )
perror("bind");
bind()
connect(), .
,

MY_PORT,
, INADDR_ANY.
, ,

.
INADDR_ANY (
0.0.0.0), ,
.

(, ,

IP
).
IP
. bind()

TCP UDP

.
,

:
if ( inet_aton("128.48.5.161", &addr.sin_addr) == 0 )
perrorf("address error");

128.48.5.161.


:
addr.sin_addr.s_addr = htonl(0x803005Al); /* 128.48.5.161 */
.
, INADDR ANY htonl()

4. ...
%RRNVVKRS

piracy@books-shop.com

91

. ,

.

UDP

. ,
. " " .

, bind().
. ,

. ,
, .


.
, (""). 4.4
, (
connectionless
sender. Web
).
4.4.
/***

***/
/***
( connectionless
sender.)
***/
/****************************************************************/
struct sockaddr addr;
int sd, bytes, reply_len, addr_len=sizeof(addr);
char *request = "select * from TableA where fieldl = 'test';";
char buffer[1024);
/* */
sd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
/* * */
if ( inet_aton(DEST_ADDR, &addr.sin_addr) == 0 )
/* IP
*/
perror("Network IP bad");
/* */
if ( sendto(sd, request, strlen(request), 0, saddr,
addr_len) < 0 )
perror("Tried to reply with sendto");
/* */
bytes = recvfrom(sd, buffer, sizeof(buffer), 0, saddr, &addr_len);
if ( bytes > 0 )
perror("Reply problem");
else
printf("%s", buffer);

92

L
www.books-shop.com

, 9999, SQL

.
,
recvfrom(). (

, . ,

.)

,

bind(). ,
.

4.5
(
connectionless
receiver. Web
).
4.5.
/****************************************************************/
/***

***/
/***
( connectionless
receiver.)
***/
/***************************************************************/
struct sockaddr addr;
int sd;
/* */
sd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
/* */
addr.sin_addr.s_addr = INADDR_ANY;
/* IP
*/
if ( bind(sd, saddr, sizeof(addr)) != 0 )
perror("bind");
/* */
do
{ int bytes, reply_len, addr_len=sizeof(addr);
char buffer[1024];
/* , */
bytes = recvfrom(sd, b u f f e r , s i z e o f ( b u f f e r ) , 0, saddr,
&addr_len);
if ( bytes > 0 .)
/* */
printf("Caught message from %s:%d (%d bytes)\n",
inet_ntoa(addr.sin_addr), ntohs(addr.sin_port),
bytes);
/**** ****/
if ( sendto(sd, buffer, reply_len, 0, saddr,
addr_len) < 0 )
perror("Tried to reply with sendto");

else
4. ...

93

www.books-shop.com

perror( "Awaiting message with RecvFrom");


while ( !quit );

. ,

.
.
, , .

.
,
. UDP
64 .
.
UDP
, ,
. B , .


UDP
.
, UDP.

, .
, UDP , ..

, . ,

,
. ,

. , .
UDP ( 100

TCP) . ,

TCP.
UDP
TCP

. TCP
. , UDP,
.

UDP, .
, .
.

, ?
94

I.

www.books-shop.com

, ?
,

. ,

. ,

( TCP).
, . ,

, .

, .
,

. .
,
.

, , TCP.

, .
,

. ,

. , IP
UDP

( 28 ).
, (4 5
28 UDP/IP).

, ,
"" .
.

, 1024 1 ,
1000 . 1024 ,
10 .
10x1024 . ,

,
.
: ,
?

, ,
, :
;
, ,

.
,
. ,
.

UDP

Internet (. 3, " Internet


").

4. ...

95

www.books-shop.com


.
,
.
. ,
, . ,

1, 2, 4 5, 4 5 ,
3.
, 3 ,
, ,
. .

,
. ,
, .
.

.

,

( ).

3 , "" .

.
UDP TCP (
,

1). IP ,
. ,

(CRC cyclical redundancy check)


( error correction code). 3 ,
IP UDP .

, CRC

.
Internet, .
:

;

,

96

I.

www.books-shop.com

. CRC

, .
"" . , 32

CRC
32 .
. ,

.


. ,
,
(, ).

. ,
, , .
,
. , ..
,
, .
,

.
. ,

. ,

: "" "".
,
, .

: ?

? , ,

, .
, ,

. :

, , ..
, .

,
.

.
:
. :
?

4. ...

97

www.books-shop.com

, ,

.
, , ,
,
. , ,
. ,
.

. 8, "
".

.
, ,
.

, .

TCP, UDP, TCP

. UDP

,

, sendto() recvfromf).
:
. TCP

send() recv(), UDP

sendto() recvfrom(), .
/ (Transaction TCP) TCP,

. , , ,


. Linux .
UDP ,
, . TCP,
UDP

.
TCP , .
UDP,

, , ,
. TCP UDP

. TCP

, UDP .

IP.

98

I.

www.books-shop.com

...

103

OSI

108

Internet

111

OSI IP

115

116

116

www.books-shop.com

( ) .
. .
( !
), .
,

. ,

. :

, "" , ,

.
,

, ,
,
, .

.
,

, ,
.

, .

, ,
. , ,
, , " ",

: , ,

); ,
, .
. 5.1 .
5.1.

<2

10 /

<150

100 /

( 
)

100 /

100

I.

www.books-shop.com

. 5.1

: HF

:
VHF/UHF

: 

> 1000

< 10 /

<30

< 40 /

<30

< 1 /



,


< 10 /

( 
)
<10

, 

< 1 /

< 100 /

, ( .

, ,

. .
, .

( , ).

.
. ,

, (
), .

, ,
.
, ,

. ,
.
.
: ,

, . ,

, .

, , ..
,
,

( "
"), , .

,
.

Ethernet
:

. ,
5.

%RRNVVKRS

piracy@books-shop.com

101

, , .
Ethernet
.

IP

. ,


.
.
, .
.

, ,
.

, , .
( )

.
, .

,

. ,
, .
.
, TTL (time
to
live)

. ,
.
255 . 64 .

, .
,
. , ,
"". ,

. ,

, .

, .
, ,


, TTL

. TTL

, .
.

.
,
. , ,
, .
. ,
.
,

( ).

102

I.

www.books-shop.com

.
,

.
.
, ,
.
,
.
8

.
.
,

,
.
.

.


.
,

, , .
,

.
,

( ).

Linux ,

.
,

,
. ( )

, ,
. , !
( , ; . 3,
" Internet
").
,

, .

.
, .

, .
,

, .
, .
,
, .
, ,
. :

5.

103

www.books-shop.com

.
.
,

()

(,
).
.
( ,
)
,
( IP
).
,
, . IP

. ,

.

.

. Java,
Pascal, .

, .
.

, . ,
.
3, " Internet
",
.
.
.

,
( 10, " ").
, .
,
.
() ,
.
,
.
,
Socket API.

, . , , ,
(,

, ). : OSI IP.

104

I,

www.books-shop.com

OSI

OSI (Open
Systems
Interconnection


7 (),


.
OSI

,

.
OSI

.
,

(. 5.1).

OSI

API

, ,

, ,

,
,

. 5.1. OSI: !
!
, !

1:
,
.
(, , , ),

.
.

(, ).

, .

5.

105

www.books-shop.com

, .
,

.
, ,
(Ethernet) . ,
,

. ,
.
,
. ""
,
.
, .
,
Ethernet
CRC
, .

, ,
.
.
. ,

. FDDI

CRC
.
.
2:

, (
).
CRC
, .

. , .
,

. ,
.
, , .
.
10
60 .
Linux

1
(100 / ). .
.
Linux

. ,
, .

106

I.

www.books-shop.com

3:
.

. , , .

. , , AppleTalk
Ethernet, .
,
.
4:

, .
, .
,
. (

, . ,

HTTP
,
.) ,
.
.
, !
. ,
( TCP/IP).

, ,
.
,

Internet. ,

.
5:

, . , ,

. ,
, ,

.
,
.
,

.
.

: , ,

5.

107

www.books-shop.com

, (
10, " ").
6:
:

, , , .. RFC (Remote
Procedure Calls ) (
15, "
(RPC)").
7:
, , ,
, ,
. ,
API
,
.
(NFS),

RPC.

Internet
Linux ( UNIX
) OSI

TCP/IP. Linux Internet,


Linux.

IP 1972 . ARPAnet, DARPA (Defense


Advanced Research Projects Agency
). BBN . 
UNIX, , Bell Labs,
IP. , ARPAnet,, UNIX ,
. Socket API 

SD
4.2

1983
.
Internet ,
OSI. .
OSI (. 5.2).
1:

Internet
OSI.

, .

108

I.
www.books-shop.com

Internet

OSI

API

, ,

, ,

,
,

. 5.2. Internet OSI; !


Socket API OSI
, !
, Telnet, FTP Lynx
, "" OSI.
,

. , ,
.


, ,

.
Linux :

"" . PCMCIA
.
PCMCIA , PCMCIA
, ,

.
2: (IP)
IP
, IPv4 IPv6,

.
, ,

5.

109

www.books-shop.com

OSI.

. ,

, .
2: (ICMP)
ICMP (Internet Control Message Protocol
Internet) .

"network not reachable" ( ) "host not found" (

).
,

. , , ARP

, . ,
TCP " "

. IPv6
() .
ICMP , .
UDP, TCP . ICMP

.
3: (UDP)
, UDP (User Datagram Protocol

)
OSI (. 5.3).

, ,
. UDP (. 5.2).
5.2. UDP

UDP


( )



( )



IP
UDP :

. 4, "

", ,
. UDP
Internet.
UDP OSI,
.

110

I.

www.books-shop.com

Internet

OSI

API

, ,

TCP
UDP

, ,

,
,

ICMP

. 5.3. Internet
, ; , !
UDP OSI

3: (TCP)
TCP OSI.
:
, ,

. , TCP UDP.
TCP
. . 5.3

TCP OSI.
5.3. TCP

TCP

( )

""

IP

5.
%RRNVVKRS

piracy@books-shop.com

111

4:
TCP/IP .

, OSI.

Web
, , Telnet FTP (File Transfer Protocol
). RPC
OSI. (NFS) RPC

OSI.
UDP TCP,

ICMP.


OSI IP
OSI IP .
,
,

.
OSI , .

.
, ,
: , ,
.
. ,
. ,

.
:

, ,

.
. .
, .
, .
IP
.
, ,
.
IP
. IP
,

, .
, 3, " Internet

", TCP/IP .

OSI,
, Internet IP. ICMP

. UDP
. TCP

112

I.

www.books-shop.com

. IP
.


, Internet.
IP,
socket() (. 5.4).
5.4. Internet
TCP/IP
4
3
(TCP)
3 (UDP)

2 (I)
2 (IP)

/
FTP, Gopher, Lynx, IRC
socket(PF_INET, SOCK_STREAM, 0);
socket(PF_INET, SOCK_DGRAM, 0)
,

socket(PF_INET, SOCK_RAW, IPPROTO_ICMP);


socket(PF_INET, SOCK_RAW, );

socket(PF_INET,

SOCK_PACKET, );

Linux
socket () SOCK_PACKET.
, .

3, "
Internet
".

:

. ,

, .
,
,

.
, OSI IP, .
, , , .

.
,

5.

www.books-shop.com

www.books-shop.com

...
6.
7. :
8. 
9.
10.

www.books-shop.com

6
...
:


: HTTP
:

121
122
129
131
134

www.books-shop.com

.
, ,
. I, " ",
:

TCP/IP.
, .
, ,
,

, .
,

. .
, .
, .
,
:
, .
I , ,

, .
. HTTP

, , Web

HTML
.

:

.

, ,
.

, (. 6.1).
, ,

: socket(), connect(), read(), write() close().


bind() ,
. ,

. ,
.
,

, .

: socket(), bind(), listen(), accept() close().


, .

listen () accept () ,
.
bind() 4, "
".
. , : listen()
accept().

6.

117

www.books-shop.com

. 6.1.
,


,
, .

. ,

"Hello, World" .
Web
simple
server..
,
().
.
.

.
, 
. ( 
)
. , 
.

118

II.

www.books-shop.com

, ,
.
.
1. socket().
2. bind().
3. listen().
4. accept().
5. recv() read().
6. send() write ( ) .
7. "bye", . 5.
8. close() shutdown().
9. . 4.
UDP
, .
, bye.
,

. ( )

1, " ". ,

.
.


socket)),

SOCK_STREAM. ,

.
bind() ,

. ,
.
.
, , ,

. .
bind)) :
tinclude <sys/socket.h>
linclude <resolv.h>
int bind(int sd, struct sockaddr *addr, int addr_size);
sd . addr
sockaddr.

, (. 1, " ").
sockaddr.

, Socket API: ,
. ,
.
bind()
sockaddr ( 6.1).

6.

119

www.books-shop.com

6.1. bind() TCP!


/***
/***

:
sockaddr_in

***/
***/

struct sockaddr_in addr;


/* 
bzero(&addr, sizeof(addr));
/*
addr.sin_family = AF_INET;
/* TCP/IP
addr.sin_port = htons(MY_PORT);
/*
addr.sin_addr.s_addr = INADDR_ANY;
/* IP
if ( bind(sd, saddr, sizeof(addr)) != 0 ) /*
perror("Bind AF_INET");

*/
*/
*/
*/
*/
*/

( 6.2)

( AF_UNIX AFJGOCAL).
6.2. bind()
/***
/***

:
sockaddr_ux

***/
***/

#include <linux/un.h>
struct sockaddr_ux addr; /*
bzero(Saddr, sizeof(addr));
/*
addr.sun_family = AF_LOCAL;
/*
strcpy(addr.sun_path, "/tmp/mysocket");
/*
if ( bind(sd, saddr, sizeof(addr)) != 0 )
/*
perror("Bind AF_LOCAL");

*/
*/
*/
*/
*/

/tmp mysocket.
, syslogd, :

.
bind()
.
EBADF. . ,
socket () ,

.
EACCES. root.
, 01023
root.

2, " TCP/IP".
EINVAL. . ,

. ,
. ,
( !).

120

www.books-shop.com

bind()
(
/etc/services). ,


,
. :
,
.

.
listen().
, . ,
" ". ,

accept().
#include <sys/socket.h>
linclude <resolv.h>
int listen(int sd, int numslots);
sd ,
socket(). numslots .
( 6.3).
6.3. listen()
/****************************************************************/
/***
listen():
***/
/***
***/
****************************************************************/
int sd;
sd = socket(PF_INET, SOCK_STREAM, 0);
/*** ***/
if ( listen(sd, 20) != 0 )
/* */
perror("Listen"); /* 20
*/
, 5 20.
.

,

(, 60,

60 ).
listen() .
EBADF. .
EOPNOTSUPP. listen(). TCP
(SOCK_STREAM) , UDP
(SOCK_DGRAM) .

6.

121

%RRNVVKRS

piracy@books-shop.com


,
.

. accept () .
.
, .
.
. accept() ,

.
, ,

,
. accept))

. ,

.
, ,
accept() .

4, "

", recvfrom() ,

.
#include <sys/socket.h>
#include <resolv.h>
int accept(int sd, sockaddr *addr, int *addr_size);
, sd .
,
sockaddr. recvfrom(),
. ,
.
,
.

: ,
. addr_size ,

( 6.4).
6.4. accept ()
/****************************************************************/
/*** accept(): ***/
/***
***/
/****************************************************************/

int sd;
struct sockaddr_in addr;
/*** ,
***/
for (;;)
/* */
{ int clientsd;
/* */
int size = sizeof(addr);
/* */

122

www.books-shop.com

clientsd = accept(sd, &addr, &size); /* */


if { clientsd > 0 )
/* */

{
/*** ***/
close(clientsd);
/* */

}
else
perror("Accept");

/* */

clientsd,

. ,
. ,
.

accept () ,
bind( ). bind( ) 
.
,

. addr
( 6.5).
6.5. accept( )
/****************************************************************/
/*** accept():
***/
/***
***/
/****************************************************************/
/*** ( ) ***/
client = accept(sd, saddr, &size);
if ( client > 0 )

{
if ( addr.sin_family == AF_INET)
printf( "Connection [%s]: %s:%d\n",
/* */
ctime(time(0) ) ,
/* */
ntoa(addr.sin_addr), ntohs(addr.sin_port));
/* */
accept() ,
.

. .

6.

123

www.books-shop.com

EBADF. .
EOPNOTSUPP. accept()
SOCK_STREAM.
EAGAIN.
,

. accept() ,
.

,

, bye ( 6.6).
6.6. 
/***

:
/*** "bye<ret>"

***/
***/

/*** ( accept()) ***/

if ( client > 0 )
{ char buffer[1024];
int nbytes;

do
{

nbytes  recv(client, buffer, sizeof(buffer), 0);


if ( nbytes > 0 ) /* , */
send(client, buffer, nbytes, 0);
}
while ( nbytes > 0 && strncmp("bye\r", buffer, 4) 1=0);
close(client);
}
, "bye\r",
"bye\n". ,
. .
,
Telnet.

. ,

: " ?" " ?"


,
, .

124

//.

www.books-shop.com


?
.
,
.
( ).
. ,
, , .
? ?
?
.
. , ,

.
. ,

. ,

, .

, .

, .
?
, .
, ,
, .
.
, . 16,
" ", SSL (Secure Sockets
Layer ),

.
, ,
. ?

? ?

, Web
.
?
ASCII, Web

/HTML. :
" ?"
" ?" ,
, .

.
ASCII
50
80%.
6.

125

www.books-shop.com

, ASCII
. :
7
.

, . ,
, ,

.
.

.
, ,
? ,
.
?
, ( !
, ).
. ,
, ,
.
, ,

. ,

,

.
?
, ,
, . ,
.
, .

.
, ( ).
(

).
,

( ).
,

.
?

.

, .

126

II.

www.books-shop.com

TCP/IP ,
.
9, "
".

: , ,
.
.
,

. ,
.
?
,

. .
, . , HTTP

.
,

read() recv(), .
.
, ,

. (EPIPE),

, .

: HTTP

. HTTP
.

,
, .

Web
( html
ls
server.c).
HTML
, .
( 6.7).
6.7. 
/**************************************************************/
/***
HTTP

***/
/**************************************************************/

while(1)
{ int client;
int size = sizeof(addr);
client = accept(sd, &addr, &size);
if ( client > 0 )
{ char buffer[1024];
/* */
char *reply = "<html><body>Hello!</body></html>/n";

6.

127

www.books-shop.com

bzero(buffer, sizeof(buffer) );
/* */
recv(client, buffer, sizeof(buffer), 0); /*
*/
send(client, reply, strlen(reply), 0); /* */
/* */
fprintf(stderr, "%s", buffer);
close (client);

}
else
perror( "Accept");

, ,
:
GET /dir /document HTTP/ 1.0
( )

, .
,

, . GET
: .

, (,

). HTTP 1.0
, ,

HTTP/.
MIME
,

:
/1.1 200
Content
Type: text/html

( )
( )
<html>
<head>

. ,

404 ("Not Found").


HTTP 1.1 , " ".
,
HTML
. ,

HTML
.
HTTP
. ,
, ,
FILE* ( 6.8).

128

II.

www.books-shop.com

6.8. HTTP
/**************************************************************/
/ * * * HTTP 1.0: , ***/
/*** ,
***/
/*** HTML
***/
/**************************************************************/
/*** ,
***/
for(;;)
{ int client;
int size = sizeof(addr);
client = accept(sd, &addr, &size);

/*
*/

if ( client > 0 )
{ char b u f [ 1 0 2 4 ] ;
FILE *clientfp;
bzero(buf, s i z e o f ( b u f ) ) ;
recv(client, buf, s i z e o f ( b u f ) , 0 ) ;
clientfp = fdopen(client, " w " ) ;
if ( clientfp != NULL )

/*
/*

/*
FILE*
/*

*/
*/
*/
*/

{
/**** ****/
/**** ****/
/**** ... ****/
/****
****/
/****
HTML ****/
fclose(clientfp);
/* */

else
perror("Client FILE");
close(client);

/* FILE*
*/
/* */

}
else
perror ("Accept") ;

/* accept () */

, ,

, HTTP 1.1 ..

6.

129

www.books-shop.com

,
.
: b i n d f ) , listen()
accept() , .
(bind()),
(listen()) (accept()).
accept() ,

.
,

.
,
.

130

II.

www.books-shop.com

...

136

160
164

167


()

168

171

%RRNVVKRS

piracy@books-shop.com

. ,
, .
. , ,
., , .

.
,

.
, ,

, , .
!
, ?
,
,

,
.

, , ,

, . ,

.
, .

, .

, .

.
.

:

Linux
UNIX.
( ) .
, .
.

: ( !
).

. , ,
.

().
, .

132

www.books-shop.com

, .

.


. (//). 
, , .
,
( ).
, .
,
. Linux !
. ,
, ,
. ,

, ,

.
Linux
.
, . ,

. ,
: ,

.
. 7.1 ,
.
.

, (PID process ID).



.
. 1 0,1 ,
.
, 100 (
10 ). ,

.
UNIX ,

. Linux 2.0
2.2 .

.
Linux .
,
. (
Linux 16 .)

7. :

133

www.books-shop.com

. 7.1. Linux

?
.
,
.
Netscape
Web
,

. ,
, ,
.
,

.
,
:

;

;
. ,
,
.

134

//.

www.books-shop.com

. , , ,
, , .

top ps aux) .
.

, . (
"". init.

.)
, .

. , init.

.

,
(1632 ).
.


.

.
:
stdin ( ),

;
stdout ( ),

;
stderr ( ),

.
( !
) .
, .
()
.
.

, clone ()
( ), .
,

, .

, .
, ,
. ,

, .

7. :

135

www.books-shop.com

Linux

. Linux .
. 
, , .


.
.

fork() 
,


pthread_exit(void* arg)
return
,


exit ()
; , 
, 

;
 ,


,


; 
,
,



( , 

)

, 


( chdir),
( enroot)
( umask)
;
,


sigprocmask(), 


.
,

136

www.books-shop.com

.
fork():
#include <unistd.h>
pid_t fork(void);
fork() "": ,

.
:
,
;
,
getpid();
,
; , ,
;
;

errno perror(),

.
fork()

(, if). ,

. 7.1 7.2
.
7.1.
/*********************************************************/
/***  ***/
/*********************************************************/
int pchild;
if ( (pchild = fork()) == 0 )
{ /*  */
/* */
exit(status); /* ! */

}
else if ( pchild > 0 )
{ /*  */
int retval;
/* */
wait(&retval); /* */

}
else
{ /*  */
perror("Tried to fork() a process");

7. :

137

www.books-shop.com

7.2.
/**********************************************************/
/*** () ( ) ***/
/**********************************************************/
int pchild;
for (;;) /* */

{
/* */
if ( (pchild = fork()) == 0 )
{ /*  */
/* */
exit(status);

}
else if ( pchild > 0 )
{ /* */
/* wait() */
/* (. ) */

}
else
{ /*  */
perror("Can't process job request");

}
, 7.1,

,
. 7.2
.

, , .

.
.
,
. ,

. !
,
. , 7.3,

, ,

.
7.3.
/*************************************************************/
/*** . ***/
/***
fork() ,
***/
/***
. ***/
/*************************************************************/
/*
*/
fork();
/* */
!
. , .

,
exit().

138

.
www.books-shop.com


. 
.
, 
{ Linux). 
. 
, . .

fork() , , ,

.
.

. , Linux
, .

, , .

. ,
,

. ,

, .
, , .

Pthreads. POSIX 1. ,

,
, POSIX. Pthreads
pthread_create ( ) :
#include <pthread.h>
int pthread_create(pthread_t* child, pthread_attr_t* attr,
void* ( * f n ) ( v o i d * ) , void* arg);

.
fork() . pthread_create()
_clone(). 
cc 
Ipthreads. , mythreads.c
Pthreads, :
cc mythreads.c  mythreads Ipthreads

fork(),
pthread create() .
, ,

(. 7.1).

7. :

139

www.books-shop.com

7.1. pthread create ()

child
attr
fn
arg

;

, 
( NULL)
, ; ,
, 
,
, 
; , , 
, , .. ( 
NULL)

, :

. ,
.
(child), (fn)

(arg) (attr).
NULL, .
.
.


( 7.4 7.5).
7.4.
/***

***/

void Child_Fn( void)


{
/* */

int main (void)


{ int pchild;
/* */
/* */
if ( (pchild = fork( < 0 )
perrorf ("Fork error");
else if ( pchild == 0 )
{
/*
*/
/*
*/
Child_Fn();
exit(0);

140

II.

www.books-shop.com

else if ( pchild > 0 )


{ /*  */
/*  */
/* */
wait();
}
return 0;

7.5.

/***

***/

void *Child_Fn(void *arg)


{ struct argstruct *myarg = arg;
/* */
return NULL; /* */
int main (void)
{ struct argstruct arg = {};
pthread_t tchild;
/* */
/* */
if ( pthread_create(&tchild, NULL, &Child_Fn, &arg) != 0 )
perror("Pthreads error"); /* */
/*** , ***/
/*  () */
/* */
/* */
pthread_join (tchild, NULL);
return 0;
}
fork(), ,
.

, , , ,
.
,

exit() .
Pthreads . return (

) .

7. :
%RRNVVKRS

piracy@books-shop.com

141

clone()

Linux _clone(),

. 6
.

(. . 7.1), ,
_clone() .

clone ()

clone {) .
, .

clone () :

#include <sched.h>
int
clone(int (*fn)(void*), void* stacktop, int flags,
void* arg);
fork(),

1 . . 7.2 .
7.2.

clone()

fn

pthread_create(), ; 
( return exit()), 

stacktop

flags

arg

; ( 
HP/PA RISC) ,
( ,
)
, ,
(. 7.3) ( 
 SIGCHLD)
pthread_create(), fn


,
.
.

, . 7.3, ,

(.
. 7.1).
,

, .

142

II.

www.books-shop.com

7.3.

clone ()

CLONE_VM

; ,
, 
, ,

CLONE_FS

: , 
( umask);
,

CLONE_FILES

;
, ,
, (
, 
)

CLONE_SIGHAND ; 
sigprocraaskf),
( , 
)
CLONE_PID

;
, ( 
Pthreads); , 

_clone() .
, ,
, .
, fork(),
pthread_create().
7.6 7.7 ,

fork() pthread_create() , clone()


.
7.6. fork() pthread_create()
/******************************/
/*** fork() */
/******************************/
void Child(void)

{
/* */
exit(O);

}
int main(void)
{ int pchild;
if ( (pchild = fork()) == 0 )
Child();
else if ( pchild > 0 )
7. :

143

www.books-shop.com

wait();
else
perror( "Can't fork process");
/***********************************************/
/*** pthread_create () ***/
/***********************************************/
void* Child (void *arg)
{
/* */
return &Result;

int main (void)


{ pthread_t tchild;

if ( pthread_create(Stchild, 0, &Child, 0) != 0
perror ( "Can ' t create thread" ) ;
pthread_join(tchild, 0);

7.7. clone ()
/*****************************************/
/*** fork() */
/*****************************************/
void Child(void *arg)
{
/* */
exit(O);
}
idefine STACK 1024
int main(void)
{ int cchild;
char *stack = mallocfSTACK);
if ((cchild = _clone(&Child, stack+STACK1, SIGCHLD, 0)) == 0)
{/** **/}
else if ( cchild > 0 )
wait();
else
perror("Can't clone task");
}
/********************************************/
/*** pthread_create() ***/
/**********************
"~
void* Child(void *arg)
{
/* */
exit(O);

144

www.books-shop.com

tdefine STACK
1024
int main(void)
{ int cchild;
char *stack = malloc(STACK);
if ((cchild = _clone(&Child, stack+STACK
1, CLONE_VM |
CLONE FS | CLONE_FILES | CLONE_SIGHAND |
SIGCHLD, 0 ) ) < 0)
perror("Can't clone");
wait();
}

_clone() ,
. , , ,
Pthreads. ,

( ),
Pthreads

. , .

, Linux,


,
.
, .
, . ,
.
,
, .


, .
,

. , ,
.
,

, .
. ,

(" !"), ("

!") .
.
,
. void*.
void* .

7. :

145

www.books-shop.com

.
void
, void* , 
, . 
, malloc (), 
. , ,
( auto). : /
. .


: . ,
"".

. .

, .
, .
,
,


.
: (
) .

( ,
).

shmget().
, ,
.


. ,
.
.
.
:

,
stdin stdout,
pipe():

linclude <unistd.h>
int pipe(int fd[2]);
fd , .

.
.
EMFILE. .

EFAULT. f d .
146

II.

www.books-shop.com

pipe():
/****************************************************************/
/***
pipe()
***/
/****************************************************************/
int f d [ 2 ] ;
/* , */
if ( pipe(fd) != )
/* */
perror("Pipe creation error");
read(fd[0], buffer, sizeof(buffer)); /* */


 , 
. , : stdin(0),
stdout (1) stderr (2). , 
( , ). ,
, pipe() (3)
(4).
.

, .
7.8 7.9 ,
.

.
7.8.
/****************************************************************/
/***

***/
/****************************************************************/
int FDs[2];
/* , */
pipe(FDs); /* : FDs[0]  , FDs[l]  */
char buffer[1024];
/* fork() */
close(FDs[0]);
/* */
write(FDs[l], buffer, buffer_len); /*
*/
/* */
wait();
close(FDs[l]);
7.9.
/****************************************************************/

/***

***/
/***************************************************************/

7. :

147

www.books-shop.com

int FDs[2); /* , */
pipe(FDs); /* : FDs[0]  , FDs[l]  */
char buffer[1024];
/* pthread create() */
write(FDs[l], buffer, buffer_len); /*
*/
/* */
pthread_join(pchild, arg);

. 7.10 7.11.
7.10.
/***

***/

int FDs[2];
/* , */
pipe(FDs); /* : FDs[0]  , FDs[l]  */
char buffer[1024];
/* */
dup(FDs[0], 0); /* stdin */
close(FDs[0]); /* */
close(FDs[l]); /*
*/
read(0, buffer, sizeof(buffer)); /*
*/
/*
printf("My report...");
exit(O);

*/

7.11.
/*********
/***

***/

int FDs[2];
/* , */
pipe(FDs); /* : FDs[0]  , FDsfl]  */
char buffer[1024];
/*___ */

148

www.books-shop.com

read(FDs[0], buffer, sizeof(buffer)); /*


*/
/* */
printf("My report...");
close(FDs[0]);
close(FDs[1]);

/* */
/* */

pthread_exit(arg);
,

. 7.2, .

.
1. .
pipe().
2.

fd[0], a
fd[l].


, , .. 
, , ,
. 
, , 
, pipe() 
(. 7.3).

3.

( ).

4.

5.
( )

. .
6.


, .

,

. ,
,
. ,
.

7. :

149

www.books-shop.com

. 7.2. !
!

. 7.2
.

, . 7.3.

150

www.books-shop.com

. 7.3.
,

7. :

151

%RRNVVKRS

piracy@books-shop.com


.
"" ( ).

,
. .

.
.
30
( ).
,

. , ,

. ,

, SIGCHLD.
.
, . ,
( !
). SIGCHLD wait(),
.

, , ,

<Ctrl+C>.
Linux : System V
( , ,
) BSD (

, ).
signal(), .
: ,

.


. ,
, "", ,
.
signal() sigaction(),
.
:
iinclude <signal.h>
int sigaction(int sig_num, const struct sigaction *action,
const struct sigaction *old);
.

. NULL,
.
sigaction:

152

www.books-shop.com

struct sigaction
{
/* */
void (*sa_handler)(int signum);
/* */
void (*sa_sigaction)(int, siginfo t *, void *);
/* , ,
, */
sigset_t sajnask;
/* */
int sa_flags;
/* (
0) */
void (* sa_restorer)(void);
};

,
(sa_handler) .

SIG_IGN,

, SIG_DFL,
.
(

, ),

, sa mask. ( 1024)

(1) (0) .

. ,
SIGCHLD ,

SA_NOMASK.
sa_flags , .
.
SA_ONESHOT. System V: ,

SA_RESETHAND. To , SA_ONESHOT.

SA_RESTART. ,

.
, , , accept().
SA_NOMASK.

SA_NODEFER. , SA_NOMASK.

SA_NOCLDSTOP. He
( SIGSTOP, SIGTSTP, SIGTTIN SIGTTOU).
.
7.12 , SIGFPE
( )
SIGINT ( ).

7. :

153

www.books-shop.com

7.12. SIGFPE SIGINT


/*** SIGFPE SIGINT ***/
#include <signal.h>
/* */
void sig_catcher(int sig)
printf("I caught signal #%d\n", sig);

int main(void)
{ struct sigaction act;
bzero(&act, sizeof(act));
act.sa_handler = sig_catcher;
sigaction(SIGFPE, act, 0);

act.sa_handler = SIG_IGN;
signal(SIGINT, &act, 0 ) ;
/* */

/*
*/
/* */
/* */

}

, ,
. ,
. ,
.
.
, ,
. ( ,

SIGFAULT, .
. .)

.
,
.
.
kill.
kill(). :

154

II.

www.books-shop.com

#include <sys/types.h>
#include <signal.h>
int kill(pid_t PID, int sig_num);

. , kill(),
, .

.

"", .
,
.

.
,
. ,
. void*.
,
. ,

:

, , .

, "".

. ,
. .
,

.

, , ,
. ,
.

, "" .
7.13 7.14, , .
7.13. 1
/****************************************************************/
/*** ,
***/
/*** queue
***/

7. :

155

www.books-shop.com

int queue[lO];
int in, out, empty;
/************** 1 **************/
/* */
if ( !empty ) /* */
{ int val = queue[out];
out++;
if ( out >= sizeof(queue) )
out = 0; /* */
empty = (out == in);

}
7.14. 2
/*** ,
/*** queue

***/
***./

int queue[10] ;
int in, out, empty;
/************** 2 **************/
/* */
if ( Jempty && out != in ) /* */
{ queue [in] = 50;
if ( in >= sizeof (queue) )
in = 0; /* */
empty = (out == in);

}
,
. , ,
, . ,

. ?
2 empty ,

1 out. ,

out in.
(
, ).
out++ 1.
, 2
out empty, .
:

queue, in, out empty.



,

. (

156

www.books-shop.com

, ) (
).

. !
,
. ( ),

. ( ),
, .
: . ,

. .
:
,

, , ,
,

.
, .
. ,

. ,

, , .
Pthreads .

.
( 7.15).
7.15.
/****************************************************************/
/***

***/
/***************************************************************/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
/* */
pthread_mutex_lock(&mutex);
/* */
pthread_mutex_unlock(&mutex);
/* */
Web
thread
mutex.c.
mutex , .
.
( ) PTHREAD_MUTEX INITIALIZER.
.

().
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP. ,
.
, ( ),
.
, .

7. :

157

www.books-shop.com

PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP.

, , . ,
.
pthread_mutex_trylock(),

. ,
EBUSY.

, .
,  ,
.
. ,
 .

Pthreads
Pthreads

.
,

. .

.
, . ,
.

, ,

, .

, .
, ( ).
Pthreads , .
, .

( ).

. Pthreads
, .

, .

, .

.
,
. , ,
. ,

158

IL

www.books-shop.com

, . ,
.
.
1
1. Funds_Mutex_1.
2. Funds_Mutex_2.
3. Funds_Mutex_2,
Funds_Mutex_1.
4. Funds_Mutex_2.
5. Funds_Mutex_1.

2
1. Funds_Mutex_2.
2. Funds_Mutex_1.
3. Funds_Mutex_1,
Funds_Mutex_2.
4. Funds Mutex_2.
5. Funds Mutex_1.

2 .

, . ,
:

(, Funds_Mutex_l Funds_Mutex_2);

;

.
,
, .



, .

. , . ,
,

.


.
getpriority() setpriority() ( ,

root).
,

, ,

7. :

159

www.books-shop.com

. Linux
. Pthreads :
Linux (
);
,
, (
);
FIFO
, (

).
: 

, ,

.
"", .
,
.
, ,
. , .

, (
).
( Web

), "bye". .
ps aux | grep < > (

).

, Z (). ,

(
).
, .
.

wait().
. ,

.

. . 
, , 
, init. 
, , 
. :.
kill. ( init s init 1 
, , .)

, fork()
_clone(), Pthreads

( ). ,

160

//.

www.books-shop.com

, .
:
#include <pthread.h>
int pthread_detach(pthread_t tchild);
tchild , pthread_create().
.
ESRCH. tchild .
EINVAL. .
pthread_detach() :
/****************************************************************/

/***
/***
/***

.
,
.

***/
***/
***/

/**************************************************************/
/* , */
pthread_t tchild;
/* */
if ( pthread_create(&tchild, 0, Child_Fn, Child_Arg) != )
perror( "Could not create thread");
else
/* */
pthread_detach(tchild);

pthread_detach()

. ,

.

. ,
SIGCHLD. , ,
wait( ).
/*** , ***/
/*** .
***/
/****************************************************************/
#include <signal.h>

void sig_child(int sig)


{ int status;
wait(&status); /* */
fprintf(stderr, "Another one bytes the dust\n");
7. :

161

%RRNVVKRS

piracy@books-shop.com

, :
{

struct sigaction act;


bzero(&act, sizeof (act) );
act . sa_handler = sig_child;
act. sa_f lags = SA_NOCLDSTOP | SA_RESTART;
sigaction (SIGCHLD, &act, 0); /*
*/

exec ()
exec () ( )
. ,
,
.
, , status.
, . ,
0
.
,
8 , 8 . 
, 500 (0x01 F4), wait()
status OxF400, .
, wait(), .
,
. WIFEXITED()
WEXITSTATUS( ). ,
, waitpid().



, ,

, .

,
,
fork() pthread_create().
.

telnet. , ,
.

162

II.

www.books-shop.com


()
. ,

ps,

. , Perl, .
?
()
fork(), .
CGI Web
.
CGI
,

. , :
"http://www.server.m/cgi/<>?1+2+..."

"http://www.server.com/cgi/ls?tmp+proc"
stdin, stdout
stderr .

().
,

. ().
l(). ,
.

,
(arg[0]). 0 NULL.
/* : */
if ( e x e c l ( " / b i n / l s " , " / b i n / l s " , "
aF", "/etc", NULL) != 0 )
perror("execl failed");
exit(
l);
/* if

() ,
*/
execl ()
execl () . ? ,
, 
( arg[0] main() ).
. , , 
, .

execlp(). ( ) ,

7. :

163

www.books-shop.com

/* ls PATH */
if ( execlp("ls", "ls", "
aF", "/etc", NULL) != 0 )
perror("execlp failed");
exit(
l);
execle(). execl(),
,
( 0 NULL).
/* : */
char *env[] = {"PATH=/bin:/usr/bin", "USER=gonzo",
"SHELL=/bin/ash", NULL};
if ( execle("/bin/ls", "/bin/ls", "
aF", "/etc", NULL, env) != 0 )
perror("execle failed");
exit(
l);
execv(). .
.

( 0 NULL).

/* : */
char *args[] = {"/bin/ls", "aF", "/etc", NULL};
if ( execv(args[0], args) != 0 )
perror("execv failed");
exit(l);
execvp(). execv(),

( PATH).
/* : */
char *args[] = {"ls", "
aF", "/etc", NULL};
if ( execvp(args[0], args) != 0 )
perror("execvp failed");
exit(
l);
()
.

, if.


, , ()

.
,
:
/***
/***
/***

,

("ls
ai /etc").

***/
***/
***/

while(l)
{ int client, addr size = sizeof(addr);

164

II.

www.books-shop.com

client = acceptfsd, &addr, &addr_size);


printf("Connected: %s:%d\n", inet_ntoa(addr.sin_addr),
ntohs(addr.sin_port));
if ( ork() )
close(client);
else
{
close(sd); /* */
dup2(client, 0); /* stdin */
dup2(client, 1); /* stdout */
dup2(client, 2); /* stderr */
execl("/bin/ls", "/bin/ls", "al", "/etc", 0);
perror("Exec failed!"); /*  */
}
}

fork()

vfork()

UNIX c vfork(). o 
, ,
. fork()
exec(), , 
. vfork(),
. Linux (
, 
). , (),
, . , 
vfork(). Linux fork().
,
:

(). ,
stderr, , ,
.
exec() , ,
. .
,

. ,
(), .
()
; , ()?
,
. Linux , 
, .
stdin stdout,
. : fork()
.

7. :

165

www.books-shop.com

, , .

, .

: . ,
Pthreads fork()
_clone().
.


.
(

) .

. ,


.

,
.

166

www.books-shop.com

...

:

?
.

173
175

175
176




l77
182


pll() select()

: 

187
190
191

www.books-shop.com

. ,
,
. , ,
,

.
. Linux
,

.
, ,

(). :

( ,
)
( ).


, (),
.

,
. ,

, ,

. ,
.

.
,

,
. ,


(
).

, .

.

. .
, , ,
. .

$:
?
.
100%

. ,

168

//.
www.books-shop.com

.
. ,
. ,
. ,
?



" , ".



. ,

160 /, 5 .

Pentium III 500 ,

.
24 . , ,

1250000 ( ).
EnergyStar
Green EnergyStar.
, , 
. ""
12 .

10

300 / (

TCP/IP). 100
10 (3 /).

, ,
1000 (

).
1000
5000.
,

, , 10. ,
, 20 , 5000000
500000 .
?
, "" ( ).

, ""

:
,
, , , ,
. ,

, ps aux. ,
, R (running). , S
(stopped), . ,
ps.

8. 

169

www.books-shop.com


?
(
),


. , ,

.
, .
.
,
.
read() .
,

,

. Linux

.

.
, ,

.
,
accept() connect()

,

.

, .

;
;
;
,

, ,

,
. ( , ,
.)

: ,


.

170

www.books-shop.com


, , 
, , .
, POSIX.1, 
. , read() . 
,
. Linux ( ) POSIX.1,
 . ,
" ".

. ,

, .
Linux
.
. . 8.1

, .

, .

. 8.1. !

8. 

111

%RRNVVKRS

piracy@books-shop.com

, .
recv() ,
.
,

.
recv(). ,

.
,

. ,
.

, , . (

, ,

,
"", ,
.)
s e n d ( )
. , . 8.2, ,
.

. 8.2. !

$

. , send(),

172

II.

www.books-shop.com

, .


.
.

, .
.

. .

, send() recv().
EWOULDBLK EAGAIN, .
, :
/***

***/
.*************************************************/
while ( /*** ***/ )
{

if ( /*** ***/ )
/*** ***/
/*** ***/

, Linux
. ,


, .

, ,

, , , .

.
, .
, ,

sleep().
, ,

.
,

, .


.
fcntl():
linclude <fcntl.h>
in fcntl(int fd, int command, int option);
read(),

, . command

8. 

173

www.books-shop.com

F_SETFL, option O_NONBLOCK. (


, , "API

")
:
if ( f c n t l ( s d , F_SETFL, 0_NONBLOCK) != )

perror("Fcntl could not set nonblocking");


,

. ,
Internet, . ,

, .

8.1.
8.1.
/***************************************************************/
/***
: ,
***/
/***

***/
/***************************************************************/
if ( fcntl(sd, F SETFL, 0 NONBLOCK) != )

perror("FcntI

could" not set nonblocking");


done = 0 ;
while ( !done )
{ int bytes;
Queue ProcessingQueue;
Queue OutputQueue;
/* */
/* */
if ( (bytes = recv(sd, buffer, sizeof ( b u f f e r ) , 0 ) ) > 0 )
QueueData ( ProcessingQueue , OutputQueue ) ;
/*
/* (
/* ,
/* recv())
ConvertAudio ( ProcessingQueue , OutputQueue ) ;

*/
*/
*/
*/

if ( /*** ***/ )
PlayAudio( OutputQueue) ;

/* */
/* */
if ( bytes == 0 && /* */ )
done = 1;

, .
: , while .
,

, .

174

www.books-shop.com

. ( , ,

.)

,

, ,

. :
fcntl() .
: ,
, .
:
, send() ( ).
, 8.2.

, , .
8.2.
/**************************************************************/
/***
:
***/
/***

***/
/***************************************************************/
int pos[MAXCLIENTS];
bzero(pos, sizeof(pos));
for ( i = 0; i < ClientCount; i++ )
if ( fcntl(client[i], F_SETFL, 0_NONBLOCK) != 0 )
perrorf'Fcntl could not set nonblocking");

done = 0;
/* , */
/* */
while( !done )
{ int bytes;
done = 0;
/* */
for { i = 0; i < ClientCount; i++ )
/* ...
if ( pos[i] < size )

*/

{
/* , , */
/* */
bytes = send(client[i], buffer+pos[i], sizepos[i], 0);
if ( bytes > 0 )

pos[i] += bytes;

/* */
/* ,

*/

8. 

175

www.books-shop.com

if ( pos[i] < size )


done = 0;

,
. pos

,
.
,

,
.
:
;
;
.
,

, ,
.. 4,
" ".


. ,
.

, . :
/*** : ***/
/***
***/
/***
***/

/* */
for ( i = 0; i < numports; i++ )
if ( fcntl(client[i], F_SETFL, O_NONBLOCK) != 0 )

perror("Fcntl  can't set nonblocking on port #%d", i);


for (;;) /* */
{ int client;
for ( i = 0; i < numports; i++ )
if ( (client = accept(sd[i], &addr, &size)) > 0 )
SpawnServer(sd[i], i);
/*** ***/

176

II.

www.books-shop.com

,
accept() ,
.
select(),

( ).



,

, .
.

, .
Linux
SIGIO
( !).

SIGIO,

.
,

, .
, SIGIO ,
.
.
, .

.

,
, SIGIO. ,

, .

,
.

.
?


.
,
.
,
.
send() recv() ,
. ,

.
8.3
.

8. 

177

www.books-shop.com

8.3. 

/***************************************************************/
/***
, ,
***/
/***

***/
/***************************************************************/
int ready=0;
void sig_io(int sig)
{
/*** recv(): ***/
/*** send(): ***/
ready =1; /* */

for (;;)
{
if ( ready > 0 )
{
/*** SIGIO ***/
ready = 0;
/*** recv():
***/
/*** send():
***/
/*** SIGIO ***/
}
/*** ***/
/***  ***/
/*** ***/

SIGIO .


,
,

(. 7, " :

"). .
,

send( ) recv().
,
. ,

, SIGIO,
fcntl(). ,
. ,
SIGIO,
.

178

www.books-shop.com

/***
SIGIO
***/
/*****************************************************/
if ( fcntl(sd, F_SETFL, O_ASYNC | O_NONBLOCK) < 0 )
PANIC("Can't make socket asynch & nonblocking");
if ( fcntl(sd, F_SETOWN, getpid()) < 0 )
PANIC("Can't own SIGIO");

,
, SIGIO.
SIGURG, .(
9, " ".)

( ). ,
.

. ,
.
,

.
(:
,
, .)

VRML
(Virtual Reality Modeling
Language ),
8.4.
8.4.
/***************************************************************/
/*** VRML
:
***/
/***
***/
int ready=0, bytes;
void sig_io(int sig)

{
/* */
bytes = recv(server, buffer, sizeof(buffer), 0);
if ( bytes < 0 )
perror("SIGIO");
ready =1; /* */
}
/* ,  */
if ( fcntl(sd, F_SETFL, 0_ASYNC | O_NTONBLOCK) < 0 )

PANIC("Can't make socket asynch & nonblocking");


/* */
8. 

179

www.books-shop.com

/* SIGIO SIGURG */
if ( fcntl(sd, F_SETOWN, getpid()) < 0 )
PANIC("Can't own SIGIO");
while ( Idone )

if ( ready > 0 )
/*** SIGIO ***/
ready = 0;
FillQueue(Queue, buffer, bytes);
/*** SIGIO ***/
/*** ***/
/*** ***/
/*** , ready
***/
}

.
,
,

, recv() FillQueue()

.
?
( 
, SIGIO), 
. 1, .. ,
, . 
setsockopt{) ( 9, " 
").
, Linux .


,

. send(),

, .

, .

send(), ,
.
.

,
. 8.5

.
8.5.
/***
/***

180

***/
***/

II.

www.books-shop.com

int ready=0, bytes, size=0, pos=0;


void sig_io(int sig)

{
if ( size > 0 )

{
bytes = send (client, buffer, size+pos, 0);
if ( bytes < 0 )

pos += bytes;
ready = 1;

/* ,  */
/* SIGIO */
while ( Idone )

if ( /*** ***/ )
/*** ***/
else
/*** ***/

, ,
SIGIO.
.

. ,
accept().
:

, .
.

:
/***
/***
/***
/***

:
.
. ( demand
accept.
Web
.)

***/
***/
***/
***/

int Connections[MAXCONNECTIONS];
int sd, NumConnections=0;
void sig_io(int sig)
{ int client;

8. 

181

%RRNVVKRS

piracy@books-shop.com

/* ; */
/* ,
*/
/*
*/
if ( (client = acceptf sd, 0, 0) > 0 )
if ( NumConnections < MAXCONNECTIONS )
Connections [NumConnections++] = client;
else
{
sendfclient, "Too many connections !\n, 22, 0");
close(client);
}
else
perror(" Accept");

,
, ,
,
,
,

,
.

,
( ,

).



ll() select()
Linux ,

.
( ), .
, ,
.
,

,
. , ,
. ,

.
select () .

, .
#include <sys/time.h>
#include <sys/types.h>
linclude <unistd.h>
int select (int maxfd, fd_set *to_read, fd_set *to write,
fd_set *except, struct timeval *timeout);

182

II.

www.books-shop.com

FD_CLR(int fd, fd_set *set);


/*.
FD_ISSET(int f d , fd_set *set);
/*

FD_SET(int fd, fd_set *set); /*
FD_ZERO(fd_set *set);
/*

*/
*/
*/
*/

select() . 8.1.
8.1. select()

maxfd
to_read
to_write
except

,
,
,
, 

timeout
fd
set

,
,

maxfd
1.
(
1024), (
: stdin 0, stdout 1, stderr 2). to_read
[3,6], to_write [46],
except [3,4], maxfd 6 (

) 1,.. 7.
timeout ,

. :
NULL ;
;
.
, [3,4,6],
:
/***************************************************************/
/***
selectf)
***/
/***************************************************************/
int count;
fd_set set;
struct timeval timeout;
FD_ZERO(&set);
FD_SET(3, &set);
FD_SET(4, &set);
FD_SET(5, &set);

/* */
/* #3 */
/* #4 */
/* #5 */

timeout.tv_sec = 5; /*  5,25 */

8. 

183

www.books-shop.com

timeout.tv_usec = 250000;
/* select() */
if ( (count = select(6+l, &set, 0, 0, &itimeout)) > 0 )
/*** , ***/
else if ( count == 0 )
fprintf(stderr, "Timed out!");
else
perror("Select");
select() ,
, . ,
, .

0, , 5,25 .
poll() , select(), .

, :

struct pollfd
{
int fd;
/* */
short events; /* */
short revents; /* , */
}

, fd, .
, events revents, , ,
.
POLLERR. . ,
.
POLLHUP. . ,

.
POLLIN. . ,

.
POLLINVAL. fd . ,
.
POLLPRI. . ,

.
POLLOUT. . , write ()
.
poll() :

linclude <sys/poll.h>
int poll(struct pollfd *list, unsigned int cnt, int timeout);
pollfd, .
cnt . (,

. ,

, .. , . poll()

184

II.

www.books-shop.com

.) timeout

select(), .
, select() poll(),

. ,

, .


,
. Linux

.
:
timeout select() poll();
SIGALRM

.
 Linux
 (SO_RCVTIMEO)
(SQ_SNDTIMEO). , .
select()
,
poll() . ,

, .
. ,
, .

, :


.

timeout,

.
SIGALRM.
, . ,
.

EINTR.
, ,
.

alarm(), SIGALRM.

:
/***
alarm(). ***/
/*** ( echo
timeout. Web
.)
***/
/**************************************************************/
int sig_alarm(int sig)
{/*** ***/}

8. 

185

www.books-shop.com

void reader()
{ struct sigaction act;
/* */
bzero(&act, sizeof(act));
act.sa_handler = sig_alarm;
act.sa_flags = SA_ONESHOT;
/* ,*/
if ( sigaction (SIGALARM, &act, 0) != 0 )
perror( "Could not set up timeout");
else
/* , */
/* */
alarm (TIMEOUT_SEC) ;
/* , */
/* 
*/
if ( recv(sd, buffer, sizeof(buffer), 0) < 0 )
{
if (errno == EINTR)
perror ("Timed out!");

, ,
recv().
, SIGALRM.
recv() , errno
EINTR.
, sa_flags sigaction
SA_RESTART. 7, " : ",

, .
,
.
: alarm()
sleep(),

. SIGALRM,
sleep(), .

: $

,
,

1 86

II.

www.books-shop.com

( , ),
, .

fcntl(),

.


. ,

. ( )
, ,
.

.

.
select() poll() ,

"" , .

8. 

187

www.books-shop.com

...

194


select()

200

206

212

213

213

 :

214

215

217

www.books-shop.com

Socket API ,

. ,
.
,
: ( ), () .

. .


,
.
,
. ,
.
,

, ,


. 7, " :
", ,

.
.
, .

,
, .

,

, .

( ! " ",

). .
/**************************************************************/
/***

***/
/**************************************************************/
int sd;

struct sockaddr_in addr;


if ( (sd = socket(PF_INET, SOCK_STREAM, 0)) < 0 )
PANIC("socket() failed");
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(MY_PORT);

9.

189

www.books-shop.com

addr.sin_addr = INADDR_ANY;
if (bind(sd, &addr, sizeof(addr)) != 0 )
PANIC("bind() failed");
if (listen(sd, 20) != 0)
PANIC ("listen() failed");

for (;;}
{

int client, len=sizeof(addr);


client = accept(sd, &addr, &len);
if (client > 0)

{ int pid;
if ( (pid = fork()) == 0 )

{
close(sd);
Child(client); /*

*/

else if( pid > 0 )


close(client) ;
else
perror("fork() failed");

7, " :

". ,
,
.. :
? ,

?


"".

, 
, . , 
, 
. , , 
, .
,
, .
:
/***************************************************************/
/***
, .
***/
/***
( capped
servlets.c Web
.)
***/
/***************************************************************/
int ChildCount=0;
void sig_child(int sig)
{

wait(O);
ChildCount;

190

II.

www.books-shop.com

for (;;)
{

int client, len=sizeof (addr);


while ( ChildCount >= MAXCLIENTS )
sleep(l);
client = accept (sd, &addr, &len);
if ( client > 0 )

{ int pid;
if ( (pid = fork()) == 0 )
{/* */
close(sd);
Child(client); /* */

}
else if ( pid > 0 )
{/* */
ChildCount++;
close(client) ;

}
else
perror("fork() failed");

.
, "" ,


"" . . ChildCount
,

, .
,


, ,

. ,
, .

520 ,
. HTTP
. (
httpd, ,
, .)

? :
/***************************************************************/
/***

***/
/**************************************************************/
if ( (pid = f o r k ( ) ) == 0 )
{
close(sd);
Child(client) ; /* */

9.

191

%RRNVVKRS

piracy@books-shop.com

, (sd).
!
?
, , ,

.

, .

.

, :
/***
, ***/
/*** .
***/
/*** ( preforking
servlets.c Web
.)
***/
/***************************************************************/
int ChildCount=0;
void sig_child(int sig)
{
wait(O);
ChildCount ;
main()
/*** ;

***/

for (;;)
if ( ChildCount < MAXCLIENTS )
if ( (pid = fork()) == 0 ) /* */

for (;;)
int client = accept(sd, 0, 0);
Child(client); /*
*/
else if ( pid > 0 ) /* */
ChildCount++;
else
perror("fork() failed");

else
sleep(l);

accept() fork():

,
, .
, , 10 .

. ,

192

www.books-shop.com

( "" ). ,
"", ,
" ".

.
, ?


accept(). ,
.
.
,
.
. ,
"" , .


,
.
.


.
,

( ),
. ,
""
.
?

. : ,

. :
,

.
. , TCP

,
listen().
, accept()
. ,
.
,

,
.

, .
,
. ,

API
. .

9.

193
www.books-shop.com

, . ,

, ,

.
, "" .

(
),
. ,

, .
,

,
. ,

, fork()

, .

, . ,

.
.

: , .

. ,
60 ( 30
),
. 9.1.

. 9.1. ,

,

, .
,
.
(. . 9.1, ). ,
fork() ( ,
5 ).
, ,
.
.
/***

/***

( servlet
chumner.c

Web
.)

***/

***/

/**************************************************************/

194

II.

www.books-shop.com

int delay=MAXDELAY;
time_t lasttime;
void sig_child(int signum)

/* , 5 */

wait(O);
timej&lasttime);
delay = MAXDELAY;

/* */
/* */
/* */

void Chuiraner( void (*servlet)(void))


{
time(&lasttime) ;
/* */

for (;;)
{

if ( !fork() )
/* */
servlet(); /* ( /
exit()) */
sleep(delay);
/*  */
/* ,
*/
if ( times[0]  timesll] >= delay  1 )
if ( delay > MINDELAY )
/*
*/
delay /= 2;
/* */

, .
( delay), .


select()

.
,
.

:
"" .

,
. ,
. ,

9.

195
www.books-shop.com


. :
Linux 10 .

, .
, 200 , 2 ,

0,01 . ,

1 , 200 /
10 / ( TCP/IP).
512 /.
.
:

.
, 20 .
, ,
( ) ,


.
" "
, ,
Linux, , . Linux 2.4
" " ,
.
select()

. ,


: select() poll().
.
20 ,
, .

, ( )

, select() poll() ,
.

.

.

. .

, ,
, ,
,


j make. (

.)

196

www.books-shop.com

select()

.


. ,

. ,
.

.
select(), " " ,
.
.
.

select().
/*** select(): ***/
/***
***/
/*** . ***/
/*** ( smart
select. Web
ye.)
***/
int sd, maxfd=0;
fd_set set;
FD_ZERO(&set);
/*** fork() * * * / > :
/* */
maxfd ~ sd;
FD SET(sd, &set);

f or ( ; ; )
{

struct timeval timeout={2,0}; /* 2 */


/* */
if ( select (maxfd+1, &set, 0, 0, stimeout) > 0 )

{
/* , */
/* */
if ( FD_ISSET(sd, &set) )
{ int client = accept(sd, 0, 0);
if ( maxfd < client )
maxfd = client;
FD SET(client, &set);

/* , */
/* */
else
/*** ***/
/* ,  */
/* */

9.

197
www.books-shop.com

( ,
), 510 ,
, , 5
10 .


, SD
,
. , select()
"" , .
BSD4.4 , select().
,

Linux

.

.

.

, .
,
. , ,
,

, HTTP
,

Web
.


, .

. ,
:
/*** ***/
/***********************************************/
if ( FD_ISSET(sd, &set) )

if ( ceiling < MAXCONNECTIONS )


{ int client = accept(sd, 0, 0);
if ( maxfd < client )
maxfd = client;
FD_SET(client, &set);
ceiling++;
}
,

.
.

, ,
(

).
.

198

IL
www.books-shop.com

, ,

. ,
.
.

, , .
. ,


, ,
. ,

. ( ,
,
.) ,

, .
poll().
( select(), .)
. ,
.

,
.
poll() . ,

, poll()
.
/****************************************************************/
/***
:
***/
/***

***/
/*** .
***/
/***
( fair
load. Web
.)
***/
/****************************************************************/

int fd_count=0;
struct pollfd fds[MAXFDs]; /*
bzero() */
/*

*/

int sd = socket(PF_INET, SOCK_STREAM, 0);

/*** bind() llsten() ***/


for (;;)
{ int i;
/* ,
/* */
for ( i=0; i<fd_count; i++ )
if ( fds[i].events == 0 )
break;
if ( i == fd_count && fd_count < MAXFDs )

9.

*/

199
www.books-shop.com

fd_count++;
/* ? */
/* */
if (i < fd_count)
{
fds[i].fd = accept (sd, 0,0);
fds[i].events = POLLIN | POLLHUP;
}
else
/* */
sleep(1);
/* "" *[

/* */
void *Servlet(void *init)
{ int start = *(int*)init; /* */
for (;;)
{ int result;
/* 0,5 */
if ( (result = poll(fds+start, RANGE, 500)) > 0 )
{ int i;
for (i = 0; i < RANGE; i++)
{
if ( fds[i).revents & POLLIN )
/*** .***/,
else if ( fds[i].revents & POLLHUP )
/*** ***/

else if ( result < 0 )


perror( "poll() error");

,
.

fds[].

. ( events
pollfd , poll() .

,
0.)
.
7, " : ", ,

. ,
.

, .

200

II,
www.books-shop.com


getsockopt() setsockopt().

, , (

, " ").
:
int getsockopt(int sd, int level, int optname, void *optval,
socklen_t *optlen);
int setsockopt(int sd, int level, int optname, const void *optval,
socklen_t optlen);
.
Linux 4 : SOL_SOCKET, SOL_IP, SOL_IPV6 SOL_TCP.
.
optval,
optlen.
getsockopt() , .
, , SOJCEEPALIVE:
/***

setsockopt()

***/

int value=0; /* FALSE */


if ( setsockopt(sd, SOL_SOCKET, SO_KEEPALIVE, Svalue,
sizeof(value)) != 0 )
perror("setsockopt() failed");
:
/***

getsockopt()

***/

int value;
int val size = sizeof(value);
if ( getsockopt(sd, SOL_SOCKET, SO_TYPE, &value, &value)) != 0 )
perror("getsockopt() failed");"

.
SOL_SOCKET.

SO_BROADCAST.

.
(. 2, " TCP/IP").

. , ,
. ( ,
False)
SO_DEBUG. /
.
TCP. ( , False.)

9.

201

%RRNVVKRS

piracy@books-shop.com

SO_DONTROUTE. / .
. ,
. (

, False.)
SO_ERROR. .

,
errno. (

, 0, .).
SO_KEEPALIVE.

, ,
. (

, True.)
SO LINGER. , .

close () (
) . ,
.

linger, : l_onoff
(/ ) l_linger (

). , 1_linger

, .
, close()

. ( linger,
.)
SO_OOBINLINE. ,
,

( ).

.

,

. ( , False.)
SO_PASSCRED. /
. ( , False.)
SO_PEERCRED.
( , ). (
ucred, .)
SO_RCVBUF.
. TCP 34

(. TCP MAXSEG). UDP


, , ,

. ( , 65535 .)
SO_RCVLOWAT. , ,

. ,
.
Linux . (

, 1 .)

202

www.books-shop.com

SO_RCVTIMEO.
.
(read(), readv(), recv(), recvfrom() recvmsg())
,
. ( timeval, 1 , .)
SO_REUSEADDR. ,

/.

. , ""
.


.
bind() "Port
already used" ( ),
, . ( ,
False.)
SO_SNDBUF. . (
.)
SO_SNDLOWAT. . ,
, ,

, .

,

. Linux
. ( , 1 .)
SO_SNDTIMEO.
.

(write(), writev(), send(), sendto() sendmsg())


,
. ( timeval, 1 , .)
SO_TYPE. .

socket(). ( ,
, .)

IP

. SOL_IP.
IP_ADD_MEMBERSHIP.
. (
ip_mreq, , .)
IP_DROP_MEMBERSHIP.
. (

ipjnreq, , .)
IP_HDRINCL.
IP
. ,
, .
. ( ,

False.)

9.

203

www.books-shop.com

IP_MTU_DISCOVER.
(MTU
Maximum Transmission Unit).
.

:
IP_PMTUDISC_DONT (0)
;
IP_PMTUDISC WANT (1)

;
IP_PMTUDISC DO (2)

. ( , .)
IP_MULTICAST_IF. ,

IPv4,

.
, .
, . (
in_addr, INADDR_ANY.)
IP_MULTICAST_LOOP. .
.
( , False.)
IP_MULTICAST_TTL. (TTL Time To
Live) , .
Internet,
,

. ( , 1.)
IP_OPTIONS. IP
.

IP

( , ,
..). ( , .)
IP_TOS. (TOS Type Of
Service), .
:
IPTOS_LOWDELAY ;
IPTOS_THROUGHPUT ;
IPTOS_RELIABILITY ;
IPTOS_LOWCOST . (

.)
IP_TTL. .

, .
( , 64.)

204

II.

www.books-shop.com

IPv6
,
IPv6. SOL_IPV6.
IPV6_ADD_MEMBERSHIP. IPv4,
.
( ipv6_mreq, ,
.)
IPV6_ADDRFORM.
IPv4 IPv6. ( ,

False.)
IPV6_CHECKSUM.
IPv6

. 1,
, . (

, 1.)
IPV6_DROP_MEMBERSHIP. IPv4,
.
( ipv6_mreq, ,
.)
IPV6_DSTOPTS.
.

recvmsg(). ( , False.)
IPV6_HOPLIMIT.
recvmsg(),
, . (
, False.)
IPV6_MULTICAST_HOPS. IPv4 ( IP_MULTICAST_TTL),
,
. ( , 1.)
IPV6_MULTICAST_IF. IPv4, , IP
(
) . (
, 0.)
IPV6_MULTICAST_LOOP. IPv4, ""

. ( , False.)
IPV6_NEXTHOP. ,

. ,

root. ( ,

False.)
IPV6_PKTINFO. ,
IPv6. ( ,
False.)
IPV6_PKTOPTIONS.
.
sendmsg(). ( , .)

9.

205
www.books-shop.com

IPV6_UNICAST_HOPS. IPv4 ( IPJTTL),


. (

, 64.)

TCP

.

SOL_TCP.
TCP_KEEPALIVE. , SO_KEEPALIVE,

2 , .

TCP_KEEPALIVE

. . Linux

sysctl(). ( ,
7200 .)
TCP_MAXRT.
. 1,
. (

, 0.)
TCP_MAXSEG. TCP .
.
,

. ( , 540

.)
TCP_NODELAY. TCP ,
, ,
,

. ,
,

. ( , False.)
TCP_STDURG. ,
. , ,
recv() MSG_OOB.

TCP ,

. Linux

sysctl(). ( , 1.)


,
bind() "Port already used" (
). (
), Usenet.
, .
,

( ).

206

www.books-shop.com

. , ,
, , .
, SO_REUSEADDR, ,
. ,
,
. , .
/***
/***

( ,
)

***/
***/

int value=l; /* TRUE */


int sd = socket(PF_INET, SOCK_ADDR, 0 ) ;
if ( setsockopt(sd, SOL SOCKET, SO_REUSEADDR, &value,

sizeof(value)) != 0 )
perror("setsockopt() failed");
/*** bind(), listen() accept() ***/
bind() ,
EAGAIN. ,
.
SO_REUSEADDR , .

, , HTTP

80. , , ,
. , ,
/var.

. (
, .
TCP_NODELAY,

.
, TCP ,

, .
,

, ,

. , ,

, , , ,
, ,
, write() ,

.
,

, . :

,
. ,
.

9.

207
www.books-shop.com

$
, ,


.
.
, . ,
,
Socket API.
, , , printf(), ,

.

,

, ,

.
read() write() , ec ,

Socket API.
Socket API.
.
, , .

 :

:

, .
,
. Linux ,
.
Socket
API ,
. , fcntl().
.
, .
8, "
", ,


.
send()

. ,

send().
,
.

208

www.books-shop.com

,
send(). , , ,

, ,
.
SO_ERROR ,

errno.
send() , MSG_DONTWAIT.
.
,

, .
, ,

. , .
,

, .
recv()
send(), recv()

, , , ,
. , recv()
. ,
. ( ,
MSG_WAITALL.)
, ,
.

: , ,

. .

, ,

recv().
, ,
.
, ,

, .

, SIGIO.
recv().
, , .
, ;
, . ,


,
, .
, , ,
recv() MSG WAITALL.


""

. TCP

, "" .

9.

209

www.books-shop.com

( out
of
band).
, :

, (

, ).
,

. ,

: .
,

. , Telnet
(^) .
, reset
transaction
restart
transaction. 256 .
SO_OOBINLINE ,

SIGURG (
). ,
recv() MSG_OOB.
, MSG
send(). , ,

fcntl()
:
/*********************************************************/
/***
SIGIO SIGURG
***/
/**********************************************************/
if ( fcntl(sockfd, F_SETOWN, getpid()) != 0 )
perror( "Can't claim SIGURG and SIGIO");

,
SIGIO SIGURG.
,

, , ,
. ""

:
/****************************************************************/
/***

***/
/***
( ).
***/
/*** ( heartbeat
server. Web
.)
***/

int clientfd;
void sig_handler(int signum)
{
if ( signum == SIGURG )
{ char c;
recv(clientfd, &c, sizeof(c));
if ( == '?')
send (clientfd, "Y", 1, MSG );

/* ? */
/* ! */

int main()
( int sockfd;

struct sigaction act;


210

II.

www.books-shop.com

bzero(&act, sizeof(act));
act.sa handler = sig_handler;
sigaction(SIGURG, &act, 0);
/* SIGURG */
/*** ***/
/* SIGIO SIGURG */
if ( fcntl(clientfd, F_SETOWN, getpid()) != 0 )
perror("Can't claim SIGURG and SIGIO");
/*** ***/
}

, .
:
/****************************************************************/

/***
/***
/***


( ).
( heartbeatclient. Web.)

***/
***/
***/

int serverfd, got_reply=l;


void sig_handler(int signum)
{
if ( signum == SIGURG )
{ char c;
recv(serverfd, &c, sizeof(c));
got_reply = ( == 'Y' )
/* */
}
else if (signum == SIGALARM)
if ( got_reply )
{
send(serverfd, "?", 1, MSG_OOB);
/* ? */
alarm(DELAY);
/* */
got reply = 0;
}
else
fprintf(stderr, "Lost connection to server!");
}
int main()
{ struct sigaction act;
bzero(&act, sizeof(act));
act.sa_handler = sig_handler;
sigaction(SIGURG, &act, 0);
sigaction(SIGALRM, &act, 0);

/*** ***/
/* SIGIO SIGURG */
if ( fcntl(serverfd, F_SETOWN, getpid()) != 0 )
perrorj"Can't claim SIGURG and SIGIO");
alarm(DELAY);
/*** ***/

9.

211

%RRNVVKRS

piracy@books-shop.com

,
.

, ,

.
,

,
.

, .

, .
,

, ,

. ,
,

.

. ,

, , , .

Socket API, ,


. ,

. ,
, ,
.

212

II.

www.books-shop.com

10

...







:

220
221
223
227
230
234
235
236

www.books-shop.com

. ,
.
, .
? !
, .
,
?

, ?
?

,

, .

.

. ,
.



Socket API.
, ,
. , ,
.
2, " TCP/IP",
. ,

Alpha 68040, .
"",
. , , ,
Linux.

.
,
Linux. ,

, GNU
, .

, .
, .
,
,

UNIX. :

214

II.

www.books-shop.com

, 0;
,

errno;
;
;

;

,

, const;
, typedef
();

, ,
;
,

.
.
.
, ,
, , .

: ,

Linux .
.


Socket API

. :
,
.
.
.
bind(). , ,

. ,
.
( )
.
connect(). , .
"host not found" (

) "host unreachable" ( ).
accept(). ,
. ( ,

.)
EINTR ( ). .

10.

215

www.books-shop.com

sigaction() SA_RESTART,

.

(recv(), send() ..).

, .

(. ). ,

fprintf(), ,
. ,
SIGPIPE .
gethostbyname().
, 0 ( NULL).


, .
fork(). , , ,
. ,
, .
pthread_create(). fork(), ,
.
setsockopt()/getsockopt(). ,

. ,
,
.


. :

, .

, .
.
,

.
socket(). ,

),

. bind(), connect() .
"not a socket" ( ).
listen(). bind() ,
, . ,
, .
close() shutdown(). ,
. ,

.
, , , ,
, . ,

. , ,

216

//.

www.books-shop.com

. ,

, .
,

. ,
" ".

TCP/IP,

.
,
.
, ,

, .
, getsockopt() SO_ERROR:
int error;

socklen_t size = sizeof(error);


if ( getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error, &size)
== 0 )
if ( error != 0 )
fprintf(stderr, "socket error: %s(%d)\n", stderror(error),
error);
, ,

. ,
.
.
, ,

. ,
,

, ,


,
. .
, ,
SIGPIPE.
,

7, " : ".

.
, .
.
,
.

. ,

,
( ).

. , ,
, .

10.

217
www.books-shop.com


, .
,
.
,

. ,

,
, .
, .
,
. ( Linux 32)
. ,
.
. 32

( ,
" ", 7 )
: SIGPIPE, SIGURG, SIGCHLD, SIGHUP, SIGIO SIGALRM.

SIGPIPE
UNIX ,

. ,
. ,
, .
,
.
,

(. sigpipe
client.c sigpipe
server.c
Web
). ,
, less, ,
, "broken pipe" (

). SIGPIPE , MSG_NOSIGNAL
send(). .
.
, .
, ,
.
, , :

, , ,
. ,

. ,

, . ,

, .

,
.

, ,
( Web
).
, ,
, ,
.

218

II.

www.books-shop.com

SIGURG

.
(.

9, " "),
. ,

SIGURG . .

, . ,

.
SIGCHLD
SIGCHLD , (
, ) . ,

, .
,

(. 7, " :

").
SIGCHLD wait().
,
. , ,

.
wait() (

), waitpid():
#include <sys/types.h>
#include <sys/wait.h>
int waitpid(int pid, int *status, int options);
pid ; 1,
, wait(). status

wait()

. ,
options WNOHANG.
, ,
, 0.

SIGCHLD.
/*** ***/
/*******************************************/
void sig_child(int signum)
i
while ( waitpid(
l, 0, WNOHANG) > 0 );
}

,
. waitpid(). ,
10.

219

www.books-shop.com

,
.
wait()
, . waitpid()
.
, ,
.
SIGHUP
,

? SIGHUP.

. .
,
.

,
. , .
,
.

SIGHUP.

, init .
, (), .
,

. (
, .)
SIGIO
,

. SIGIO
,

( ).

, (
SO_SNDLOWAT ).
,
( SO_RCVLOWAT ).
8, "

",

9, " ".
SIGALRM
SIGIO, SIGALRM,
. alarm(), ""
. ,
, .

220

II.
www.books-shop.com

. , "" (

), , ,

.
( )
.



(); stdin, stdout stderr. , ,
.

,
, .
.

.
,
. ,

("")
"" ( )
. ,
, . ,
"" .
(, ElectricFence),

.
,

, malloc() calloc() ( C++


);
, NULL (0). ,
, ,

, ..

assert(). , ,

.
, .
calloc(), .

. , C++ new ,
malloc() calloc().

delete ,

malloc(), .

10.

221

%RRNVVKRS

piracy@books-shop.com

NULL.
(,
, ).
,
.

. ( ) ,

. ( )

,
.
. 10.1 .

, ,
.
10.1.

, , 

,






""
""
, , 


,

(

"")
,
Linux 
(
1 ,
)

malloc()
. malloc() , , 
,  .


,

.
,

.
, " ". ,
,
?

222

II.

www.books-shop.com

, "" ,

. , ,

. !
,
.


.

, .

:
int Counter;

/*
*/

char *words[] = {"the", "that", "a", 0}; ;/*


*/
void fn(int arg1, char *arg2)
/* () */
{ int i, index;
/* () */

, .

Wall, .
,

,
.
.

. ,
.
.

. .
. ,

,

.


(,

) , .
, ,
.

. ,

10.

223

www.books-shop.com

,
.
.

.
. ,
,

.
, .

, ,
.

,
.
.

, .
, "". ,
"". , , ,

, .
, .

, ,
, .
.

( , Linux).

. , ,

, ( ).
: ", ".
.
.
, . , HTTP

. ,
,

, ; ,
, .

Internet

. ? TCP
. ? .
, .
,
. , , ,
TCP
.

224

www.books-shop.com



( ,

), .
, .
TCP .
: , .
,
,
.
,

. ,
.
TCP ,

. ,
.

,

.
, .
. TCP

, TCP


, .
, .

. .

, ,
. , .

,

. . TCP

, .
.

, , ,
.

, .
: .
, .

, .
, ,
.

10.

225

www.books-shop.com

, , 100$

.
, .
, ,

.
. ,
200$, 100$.
.

. .
,
, .
,
.
, ,
, .

.
,
, .

.
,
.

, , ""
.

.

.
,
,

TCP. .
TCP
"",

.

 ,
;  . 
. . 
. 
(, 
). ,

UDP.


. .
,

226

www.books-shop.com

. , .
.

, .
, ,

. , , (

).
,
,
. .
TCP
,

. ( .

. .)
, .
.
.
( ). ,
( ).
, .
( .
.)
""
, "" ,
.  ,
.

. ,
. , , .

.
, .
.




,
. .

. :

. .
. ,
(
). .

10.

227

www.books-shop.com


,
. , ,
. HTTP Telnet.
HTTP
,
. , Telnet
. , ,
, . Telnet
,

(<Ctrl+C>).
:
, , .
,

:
.
,
.
, , ( )
.

, .

. ,
. ,

. .
,

"",
. " ?",
, ,
.

, . , ,

select(),

. ,

.

Internet
. ,

:
. ,
, .
, .

/ .

, ,
.

, , .

228

//.

www.books-shop.com


. , ,
,
.

, .

.
,

. ,
, .

. , .
,
. .
.

, .

(,

, accept()). .
, .

, TCP/IP
.
, . .

,
,
,
.
.
, .

, ,
. ,
.

, ( )

.
.
1.



.
, .

2.

( ) ,
.
, .

3.
( ).
, ,
.

10.

229
www.books-shop.com

:
,

. ,
, , .
,

.
, , ,

, .
,

.
,

. .

230

II.

www.books-shop.com

III

...
11.
12. Java
13. C++
14. 

%RRNVVKRS

piracy@books-shop.com

11

...

239
242





: 

244
247
249
251
252
253

www.books-shop.com

. ,
. , ,

, .


.
,

.
,

, .
, ,

,
 . 
, Java C++, . , 
 , 
. , 
.

, ,
. , ,

, ,

, . XX

, ,

,
, . ,
,
.

.
: 


. ,
, ,
.


.

, .
.

11.

233

www.books-shop.com

.
,
, , .

, , ,

.
,

.
,

, : ,
.

.
,

, .

.
, ,

,
.

, .

. ,
.
,

. ,

, ,

, , ,
.
:

, , ,
.
, " ",
.
.
.

, 
. .
, 
. , 
.

234

III. 

www.books-shop.com



.
,
(,

).

, .

(),
. ,

.
,


. ,

. ,
, .
:

,

, .
, FIFO (First In, First
Out , ). ,

, .
, ,

, , ..
, . ,
UNIX, ,

10 . ,
.
, ,
. , ,

. ,

,
.
 
:

.
: "
?" " ?" ,
.

11.

235

www.books-shop.com

.
() ( ),

. .
.

. ,

,
!
,
: .
.



,

. "
, ".
.
,
.

, .

,
HTTP
, , ,

.
,
, . ,
, , ,
. , ,
!
? ,
.
( )

,  .
. , 
. 
( ), : " 
, , .( )". ,
( ) . ,
.

236

III. 

www.books-shop.com

.
.
.
. ,

.

, ,

.
,

.
. ,
.

, ,

. ,

, .
,
. ,
, .. :
. ,

.
,
.

( , ,
..).
.

.
.
. ,
.
socket(). ,
, ""

.
.
, .
, . ,
.

,
. ,

( ).
, .
, , .

. .

11.

237

www.books-shop.com

OSI.
.

,
()
.
,

. , ,
.
, ,
. , ,

.

.
,

.
.
.

,
.

. 
. : 
? , .
, .

,
.

: .
.
, , .

, .

,
.
.
.
.
, ,
.

.
.

238

III. 

www.books-shop.com


, , ,
, .

. : "

, ".
.
, ,

. . 11.1 Device (),


.

. 11.1. Device ()
BlockDevice (!
) CharDevice (! )
: Network (), Disk () SerialPort
( )
, , " (SerialPort)

(CharDevice) (Device)".
Device () : initialize(),
open(), read(), write() close(). CharDevice
IOctl(). , SerialPort ,
.

11.

239

www.books-shop.com


, ,

, .


, , .
, .
,
.
,

. .
.

.
, , .

, .

, ,
.
,

. . 11.1, CharDevice
Device . ,
. , CharDevice

,
.
, ,
. , Device : Disk Network.
dev
Device, Disk:
/* Disk */
/* dev Device
*/
/***************************************************/
Device *dev = new Disk();
dev
>Initialize();
Device Initialize() , ,
, Disk.
Address() Device,

. ,

:
BlockDevice *dev = new Disk();
dev
>Address();
. ,
,

240

III. 

www.books-shop.com


, , .
, ,
, . .

. , PlayVideo() PlayMIDI()
1(),

, MIDI
.
,
"" , .
,
.


.
, .

"" "".
,

. , ,
.
struct ,
, .

, .

, ,
.

, .
, .
,
: ( )
(, , ). ,

. ,

, .

.
(), (
). ,
.

11.

241

%RRNVVKRS

piracy@books-shop.com

Getxxx()
Setxxx(), .

Get() Set()
Get() Set .
, ,

, .
,

. ,

.
, .

. Java C++ : private, protected public.


private.
.
protected. ,
.
public. .
,

.
: , , .

.
"". :
.
"". :

.
"". :

242

III. 

www.books-shop.com

,
.


, .
,
.

. , ,

. C++

. ,
.
,

. , ,

,
.

, .

.
.
,
, . ,

.

, .

. , Java.
C++, ( !
Java) .

11.

243

www.books-shop.com


( C++)

, ,
,

C++. Java, , ,

.
C++ ( !)
.
, ,

.
, . ,

, ; ,

(int)+(int).
.
, (,
?:).
.
, , ..

( ), ( ).
(
).

C++ . ,

, .
,

.
Java ,

. ,
, , , .
,

, ,
, , .

,
. ,
,

, , .

244

III. 

www.books-shop.com

.
. ,
.

, .
. ,
.
, , .
, , Get() Set().

.
.
? ,

, .

Set().
?
, ,

, .

, ,


, .. . ,

, .

int float,
.
,

, .
? ,
, ,
.
, .
?
, , ,
.
?
. ,
, .

11.

245

www.books-shop.com

. Cobol.

SmallTalk Eiffel.

Java C++,
.

,
.


. ,
, SmallTalk. , ,

.
, C++ Java, , !
.

. , , C++

.
struct. Java

main().

,
.
.

, .

Perl Visual Basic.

, variant,
.
, , variant,
.

,

( C++ Java).
. ?

( ),
.

.
.
.
<_>_<_>().

246

III. 

www.books-shop.com

. ,

,
.
. ,

.
. .
.
Get( )/Set().
.
(
), ,
.
.
.
.

.
. ,


.
.

(, setjump() ),
.

: 

(, ,
), ,

. ,
, . ,

, .

11.

247

www.books-shop.com

12


Java

...

 Java


256
263
265
266
269
269

www.books-shop.com

, ,
.
, ,
.
Java
,
, . Java
:
. ,
, Java.
( Sun Microsystems

.)
.

" " ,

. Java

,

. Java (JVM Java


Virtual Machine) ,

. ,

( ), ,
,
.
Java .

C/C++ ,
. ,

JDK (Java Development Kit


Java) .
.
,

Java. ,

, Java

.
, Java
,
,
.
/


, Java

Java TCP. ,
( UDP), , .
Java ,

.

12. Java

249
www.books-shop.com


(TCP
)
Java. Java

. ,

TCP,
.

TCP$ Java
, , :
Socket s = new Socket(String Hostname, int PortNum);
Socket s = new Socket(InetAddress Addr, int PortNum);
:
Socket s = new Socket("localhost", 9999);
.
() Socket,
,
.
, :
Socket s = new Socket(String Hostname, int PortNum,
InetAddress localAddr, int localPort);
Socket s = new Socket(InetAddress Addr, int PortNum,
InetAddress localAddr, int localPort);
InetAddress IP
.
,

Socket (), .

IPv4/IPv6
Java IPv4. Merlin (
Web java.sun.com), IPv6, , 
. InetAddress, 
, . , 
, InetAddress.getHostAddress(),
,

.
/
Socket
.
( InputStream) ( OutputStream) :
InputStream i = s.getlnputstream();
OutputStream = s.getOutputStream();

:
250

III. 

www.books-shop.com

byte[] buffer = new byte[1024];


int bytes_read = i.read(buffer); //
o.write(buffer); //
InputStream.available() ,

.
, , .
if ( i.available() > 100 ) // ,
100
bytes = i.read(buffer);
(

)
Socket. close ( ) :
//
s.close();

Java , new.
, , .
, ,
.
, , 
,

.
12.1 ,
.
12.1.  Java
//****************************************************************

//  ( SimpleEchoClient.Java)
//****************************************************************
Socket s = new Socket("127.0.0.1, 9999"); //
InputStream i = s.getInputstream(); //
OutputStream = s.getOutputStream();
//
String str;
do
{
byte[] line = new byte[100];
System.in.read(line);
//
.write(line);
//
i.read(line);
//
str = new String(line);
//
System.out.println(str.trim()); //
}
while ( !str.trim().equals("bye") );
s.close();

//

. ,

, .

12. Java

251

%RRNVVKRS

piracy@books-shop.com

try
{
// <

}
catch (Exception err)
{
System.err.println(err);
}
try...catch .
main() .
TCP Java
, Java ,
. .

:
ServerSocket s = new ServerSocket(int PortNum);
ServerSocket s = new ServerSocket(int PortNum, int Backlog);
ServerSocket s
new ServerSocket(int PortNum, int Backlog,
InetAddress BindAddr);
Backlog BindAddr
listen()
( ) bind() (

). , 710
. Java :
ServerSocket s = new ServerSocket(9999);
Socket = s.accept();
ServerSocket

. ,
ServerSocket.accept() Socket,

.
12.2 , $.
12.2.  Java
//
( SimpleEchoServer.Java)
//****************************************************************

try .
{
ServerSocket s = new ServerSocket("9999"); //
while (true)

{
Socket = s.accept(); //
InputStream i = c.getlnputstream(); //
OutputStream =c.getOutputStream(); //

do

252

. 
www.books-shop.com

byte[] line = new byte[100]; //


i.read(line);
//
.write(line);
//
}
while ( !str.trim().equals("bye") );
c.close();
//
}
}
catch (Exception err)
{

System.err.println(err);

UDP
,
.. UDP. Java ,
UDP
. DatagramSocket.
UDP
:
DatagramSocket s = new DatagramSocket();

:
DatagramSocket s = new DatagramSocket(int localPort);
DatagramSocket s = new DatagramSocket(int localPort,
InetAddress localAddr);
UDP
.

. UDP

DatagramPacket, :
DatagramPacket d = new DatagramPacket(byte[] buf, int len);
DatagramPacket d = new DatagramPacket(byte[] buf, int len,
InetAddress Addr, int port);
,
.
. . buf
, len

.
, ,
.

4, " ".
12.3
.
12.3. UDP

//
// ( SimplePeerSource.java)
12. Java

253

www.books-shop.com

DatagramSocket s = new DatagramSocket(); //


byte[] line = new byte[100J;
System.out.print("Enter text to send: ");
int len = System.in.read(line);
InetAddress dest = //
InetAddress.getByName("127.0.0.1");
DatagramPacket pkt = //
new DatagramPacket(line, len, dest, 9998);
s.send(pkt);
//
s.close();
//

. ,

. ,
.

12.4.
12.4.
//
// ( SimplePeerDestination.Java)
DatagramSocket s = new DatagramSocket(9998); //
byte[] line = new byte[100];
DatagramPacket pkt = //
new DatagramPacket(line, line.length);
s.receive(pkt);
//
String msg = new String(pkt.getData()); //
System.out.print("Got message: " + msg);
s.close();
//


UDP .
,
. Java.
,

IP
, .

, , ,

. Java MulticastSocket,
:
MulticastSocket ms = new MulticastSocket();
MulticastSocket ms = new MuiticastSocket(int localPort);
,
, .
,
.

254

III. 

www.books-shop.com

, , UDP

( DatagramSocket).

. ,
. IPv4
: 224.0.0.0
239.255.255.255.
MulticastSocket ms = new MulticastSocket(16900);
ms.joinGroup(InetAddress.getByName ( " 2 2 4 . 0 . 0 . 1 " ) ) ;
ms.joinGroup(InetAddress.getByName("228.58.120.11"));
,
224.0.0.1:16900 228.58.120.11:16900.

, .
.

, .

IPv6 UDP 
TCP. Tew ' UDP
. , MulticastSocket DatagramSocket, 
, ,
. , 
, .
12.5 , .
12.5. , 16900,

//****************************************************************
//
// ( SimpleMulticastDestination.Java)
//****************************************************************
MulticastSocket s = new MulticastSocket{16900); //
ms.joinGroup(InetAddress.getByName("224.0.0.1")); //

String msg;
do
{
byte[] line = new byte[100];
DatagramPacket pkt = new DatagramPacket(line, line.length);
ms.receive(pkt);
msg = new String(pkt.getData());
System.out.println("From "+pkt.getAddress()+'4"tmsg.trim());
}
while ( !msg.trim().equalsf"close") );
ms.close();
//
16900,

. 2 2 4 . 0 . 0 . 1
, .

12. Java

255

www.books-shop.com

$ Java

. Java ,

. Java ,

.

$
Java .

Reader, Writer, InputStream OutputStream.


.
, .

. ,

, .

, ByteArraylnputStream,
ByteArrayOutputStream, CharArrayReader, CharArrayWriter, StringReader
StringWriter.
.
.

FilelnputStream, FileOutputStream, FileReader FileWriter.


.
,
. ,
, ,
. FilterReader, FilterWriter,
PrintWriter PrintStream ().
. .

Java.
Serializable .
ObjectlnputStream
ObjectOutputStream.
.
,

. ,
,

. PipedlnputStream,
PipedOutputStream, PipedReader PipedWriter.
.
.
.
InputStream OutputStream.

InputStreamReader OutputStreamWriter.
, ,

SequenceInputStream, .

256

III. 

www.books-shop.com


Socket
:
InputStream OutputStream. , ,

.
,

.
, , , .
BufferedReader.

InputStreamReader,

InputStream

Reader:
Socket s = new Socket(host, port);
InputStream is = s.getInputstream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String 1 = br.readLine();
25 :
BufferedReader br = new BufferedReader(new InputStreamReader(
s.getInputstream()));
:
String msg = new String(
"<html><body>Welcome to my Java website</body></html>");
SocketServer ss = new SocketServer(9999);
Socket s = ss.accept();
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
pw.println(msg);
s.close();
PrintWriter
. ,

println()
. PrintWriter ,

. ,

.
Java
,
ObjectlnputStream ObjectOutputStream

/ , Serializable:
String msg = new String("Test");
Socket s = new Socket(hostname, port);
ObjectOutputStream oos = new ObjectOutputStream(
s.getOutputStream());
oos.writeObject(msg);

:

12. Java

257

www.books-shop.com

Socket s = ss.accept();
ObjectInputStream ois = new ObjectInputStreatn(s.getInputStream());
String newMsg = (String) ois.readObject();
,

ClassCastException.

, Java,
.


9, " ", ,

.
Java. , , ,

, Java .

Java , .

:
getSoTimeout()
setSoTimeout(int timeout)

SO_TIMEOUT, .

, Linux fcntl(), poll()


select().
( )
.
SO_SNDBUF.
getSendBufferSize()
setSendBufferSize(int size)
( SO_RCVBUF):
getReceiveBufferSize()
setReceiveBufferSize(int size)
,

( SO_LINGER):
getSoLinger()
setSoLinger(boolean on, int linger)
,
, ( TCP_NODELAY):
getTcpNoDelay()
setTcpNoDelay(boolean on)

258

III. 

www.books-shop.com


MulticastSocket.


, ( IP_MULTICAST_TTL; ,
Java TTL ):
getTimeToLive()
setTimeToLive(int ttl)

( IP_MULTICAST_IF):

getInterface()
setInterf(InetAddress inf)

Java .

Java .
.

,

Thread, Runnable.
run( ), :
public class TestThread extends Thread
{
public void run ( )
{

/*** ***/

run() , .
Thread,
start(), . ,

:
public static void main (String[] args)
{

start(); // < run()


/***
***/

12. Java

259

www.books-shop.com

start () . , ,

.
, :
Thread t = new TestThread();
t.start();

Java (
Windows, Linux/UNIX). He 7, " :
", , .

,
.
, , ,
, .

Thread.
, Frame. Java
,

. ,

Runnable. ,

.
public class TestThread extends Frame
implements Runnable
{
public void run()
{
/*** ***/
}
public static void someMethodf)
{
Thread t = new Thread (this);
t.start();


.
, , Frame
Runnable. ,

.
, .
Thread , ,

Runnable, . start()
, .

260

III. 

www.books-shop.com

. ,

7, " : ". Java


.

Pthreads. :
public synchronized changeSomething()
{

/*** ***/

}
synchronized .
, , ,

, .
. ,

( ),
. ,

, .
, .
, ,
. ,

, .
.

, .

. ,
.
, , ,

( )

, . :
public synchronized changeSomething()
{
while ( buffer_not_full) // ?
{
try { wait() } // ,
catch (Exception err)
{ System.err.println(err); }
}
/* */
notifyAll();

//

}
wait() .
"" . ,

, . notifyAll()
, ,

12. Java

261

%RRNVVKRS

piracy@books-shop.com


Java ,

. .
!.

,
,
.
IPv4. Java

TCP/IPv4. Web

java.sun.com Merlin,
IPX
IPv6. ,
.
. Java

I
.
.

.
fork ().
,

. , ,
,
.
. Java .
, , .
, Java

, .

Java . Network
, (TCP), (UDP)
(UDP) . , ,
.

. ,

.
Java
. :
Thread, Runnable.
start() , run().
Java ,

.
Ct+.

262

III. 

www.books-shop.com

C++

13

...
C++?

272

273

283

287

287

www.books-shop.com

Java. Java
, ,

. Java,

C++.
( )

, .
, IV,
" ".
, ,

C++
.
C++ .


C++?
,

, , .

,
.

, ,
,
. ,

.
C++
. , C++,

c. ( . cc

, ++, .)
,
.
,
. , ,

. , ,

, . ,
.
, .

264

III. !
www.books-shop.com

, ,

, ,

, .


, .
, ,

, .


. ,

. ,
.
, . :

.

,
. .
,
.


,
" " ( ).

. ,
, ,
.
.
, ,

. ,

, .
. ,
.


:
,

13. C++

265

www.books-shop.com


.
, .

, .

,
.


, ,

. , TCP. TCP

. ,
.
, .
, .
UDP.

.
. 17, ",

".
,

: ,

. ,
,

API
.

:
. , ,

, .

, ,

. , send() ,

. .
, . ,
11, " ",
, . Java
: , serializable.
, Java


,
.
C++

. , C++ ,

, ,

266

III. 

www.books-shop.com



, .

, ..
, ,

.
.
C++
try/catch, , Java.

, .

, .. main(),

,
.


. ,

. ,

. ,

,
.
.
.
:
.

, ..

Exception, (. 13.1).
,

, . ,

new , .

13. C++

267

www.books-shop.com

. 13.1.
Exception, !

. Message
(Wrap()) (Unwrap()) .
Java.
, TextMessage, ,
. , Wrap()

( ,
). TextMessage

.
Unwrap() .
.

, , TextMessage

64 ( ), Unwrap()
.
True, .

:
.
, .
HostAddress. struct sockaddr,
IP
.
, ,
HostAddress. .

268

III. 

www.books-shop.com

: ,
.
Socket,

.
: SocketServer, SocketClient, Datagram, Broadcast MessageGroup (
).

.
, , ,
. , Send()
, .
.

,

. 13.2
. , Socket
"" "".

. 13.2. !
!



, .

11, " ",


,
, .

.
Socket. . 13.3
. Broadcast
MessageGroup UDP
,

Datagram. SocketClient SocketServer



, .

13. C++

269

www.books-shop.com

. 13.3. Datagram, MessageGroup Broadcast


, Socketclient SocketServer


Socket, . 13.3, , ..
.
.
Get()/Set() , Send(), Receive()
Close(). ,
.

, Socket 
.
. , UDP, TCP, 
Socketclient SocketServer .
. , 
socket Datagram. .
: 
, .
SocketServer Socketclient

, Socket.
, SocketStream,


. . 13.4
Socket.

. 13.4. :
Socket SocketStream

270

III. 

www.books-shop.com


, : "
?"

, , ,

.

. : 
, .
, 
. .

, .
:
, .

.
.

9, " ",
, " ". ,

.

Get() Set(), getsockopt()


setsockopt().
. 13.5 Socket

. ,
, , .

,
Get(). He .
, ,

.
IP_TOS .
Datagram: MinimizeDelay(), MaximizeThroughput(),
MaximizeReliability() MinimizeCost().
setsockopt(), : IPTOS_LOWDELAY ( ),
IPTOS_THROUGHPUT ( ), IPTOS_RELIABILITY
( ) IPTOS_LOWCOST ( )

. .
,

. , SocketServer
, .
MessageGroup , .

13. C++

271

%RRNVVKRS

piracy@books-shop.com

Puc. 13.5. Socket

:
,
, ,
.
Socket API (. 13.1).

272

III. 

www.books-shop.com

13.1. , Socket

Socket

Bind()

bind()

Send()
Receive()

send() sendto()
recv() recvfrom()

CloseInput()

shutdown()
shutdown()
accept()

SocketServer

CloseOutput()
Accept()

SocketClient

Connect()

MessageGroup

Connect()
Join()
Drop()

connect()
connect()

Broadcast .
, .
:
,

. , Broadcast

,
.
, .
.

, : ,

, .. ,

Socket:
//*******************************************************
//*** Socket, .
//*** Network (PF_INET) Protocol
//*** (SOCK_STREAM),
//*** SD.
Socket::Socket(ENetwork Network, EProtocol Protocol)
{
.
SD = socket(Network, Protocol, 0 ) ;
if ( SD < 0 )
throw NetException("Could not create socket");
}

,

. ,

13. C++

273

www.books-shop.com

. ,

( static). ,
, ,
.
,
. , :

,
::. , .
, .
, ,

, .
:

, ,
. Java, ,
C++ .
.
, ""
. ,
.

. Socket:
//***************************************

//*** Socket
Socket::~Socket(void)
{
if ( close(SD) != 0 )
throw FileException("Can't close socket");

}
( virtual),

. ,
, .

( ) ,

.
virtual.

. , ,

Web
.

274

III. 

www.books-shop.com

 
( )

. ,

. .
13.1.  (echoclient.cpp)
//
HostAddress addr(strings[l]); // <:>
try
{

SocketClient client(addr); //
TextMessage msg(1024); //
do // , "bye"
{
char line[100];
client.Receive(msg);
//
printf("msg=%s", msg.GetBuffer()); //
fgets(line, sizeof(line), stdin); //

msg = line;
//
client.Send(msg); //
}
while ( strcmp(msg.GetBuffer(), "bye\n") != );

}
catch (Exceptions err)
{
err.PrintException();
}
try/catch.
,

.
:
//********************************************
//
catch(...)
{
fprintf(stderr, "Unknown exception!\n");
,
.


,
HTTP
.
TextMessage. 13.2 ,
.

13. C++

275

www.books-shop.com

13.2.  (echoserver.cpp)
//

try
{
SocketServer server(port); //
do
//
server.Accept(Echoer); //
while (1);

}
, . SocketServer
.

Echoer() ( 13.3).
13.3.  (echoserver.cpp, 2)
//
try
{

TextMessage msg(1024); //
client.Send(welcome); //

do
{
client.Receive(msg); //
client.Send(msg);
//

}
while ( msg.GetSize() > 0 &&
strcmp(msg.GetBuffer(), "bye\n") != )

_}

, :

, "bye".
, try/catch. ,

. ,
,
try/catch main() .

. 
. , try/catch , 
,
.

276

III. 

www.books-shop.com

,
. UDP
,


( 13.4).
13.4. (.)
//

try
{
HostAddress addr(strings[l]); //
Socket *channel = new Datagram(addr); //
if ( !fork() ) //"
receiver(channel); //
channel>CloseInput(); //
HostAddress peer(strings[2]); //
TextMessage msg(1024); //

do
{
char line[IOO];
fgets(line, sizeof(line), stdin); //

msg = line; //
channel>Send(peer, msg); //

}
while ( !done );
delete channel;
}

, .
,
7, " : ". ,
. ,
,
.

,
.
.
.
C++ ! C++

. " ",
, .

, ,
.

13. C++

277

www.books-shop.com

( )
, C++.

, .
,

, , .
, .
Message,
. , .

/
Message.
,
Message. , ,
. ,
. ,
, , .
.

, .

.
, ,
.
,

: ?

?
: Socket Process/Thread.


, C++,

.
,

. .

, , , .
Exception ,

. HostAddress Message

Socket.

278

III. 

www.books-shop.com

14

...




:

289
293
294
296
299

www.books-shop.com

. ,
.
,

, .


, ,

, ,

. ,

.

, .

.
, .
,
.

: , ,
. ,

. ,

. .
, ,

, .
, .
" ",

: " ". .

. ,
.
.
. .
,
. .
9: " "
[ Send]


[ ]

[ ]
280

III. 

www.books-shop.com

9.1: " : "


[ Send]


[ ]

[ ]
9.2: " "
[ Send]


[ ]


[ ]

. , ,
.

,
.
, "" () " " ().
.
. , Socket,
NetIO,
.
,
, ,

.


, ""

. , ,

, , .
?


. ,

. ,

, Java,
, .
.

,
.

14. ...

281

%RRNVVKRS

piracy@books-shop.com



. / , .
.

. ,

, ,
.

. ,
, ,

, , ,

. ,
, , .

, ,

. ,

.
: " .

".

.

.
,
. ,
, , .

, ,

.
, , .

,

, ,

. "" .

, .
, ,

.
,
, , . ,
.

282

III. 

www.books-shop.com

?
?
?
?
,

. ,
.
friend
,
friend.
, ,
.

( ,
).

, ,
.
,
goto.

,
.
, .

, , (s).


.
,
.
, , ,
<>+<> , *<>
<>
>{).
new delete
,

("()") ("." "


>")
.
.
, ,
.

14. ...

283
www.books-shop.com

. , ,

.

.

,

. ,
,

, .

, , . (
, Java,

Object.)

. ,

.
, ,

.

, . ,

.

,

, . ,
.

,


, .

, ,

.

.

,

,
C++ Java, .

. ,

284

III. 

www.books-shop.com

,
, .
,
(BLOB binary large object), "". ,
,
.
.

.
.
!
,
.

, ,
, .

: .

, , ,
,
.

, .
,

. ,
.


. .
.
,
. : "
?"
.
,

, .

, .

14. ...

285
www.books-shop.com


. C++
, .
. 11, "

", .

, .

, .
,
. , ,

, .
. ,
,
.
,

, .
, .
.

( ), .


, ,
: .
, .
, .
; 2050%
,

. .

:
.
,

. ,
C++,

. , , ,

.
, .
.

.
.
.
.

286

III. 
www.books-shop.com

inline
. (

, ,

.)

,
, .

, ,

.
, ,
, .
, .
,

. ,

, .

,
, , ,
. ,

, .
,

, .
.

.
,

. ,
, .
! ,

.
.

.

.
, ,
.

14. ...

287

www.books-shop.com

. ,
.

.
, .
,


.

,
: " ?"
, .
, .
, 20%

. 80%

/ .

: 33% ,
34% 33% .

34% .
?
,
, .

.
, ,
, . ,

,
.
,

, .

. ,

" ".

,
.
.
.

, ,

.

.
,

.
( ).
.

288

III. 
www.books-shop.com

, , ..
.
, , ,

: ,
, .

, .

, .
, ,
. ,

.
,

,
,
.

. ( ),
, .
.

. ,

.

( ,
), .

.


. ,

, .

.
Internet,
3
. ,
" ", , ,
.
, .

:
,
. ,
.

,
.

14. ...

289

www.books-shop.com

www.books-shop.com

IV

...
15. (RPC)
16.
17. , 

18.
19. IPv6: IP

%RRNVVKRS

piracy@books-shop.com

15


(RPC)

...
OSI

303

304

307

RFC
rpcgen

310

315

: RPC

317

www.books-shop.com

,
.
,

.
RPC (Remote Procedure Calls
).
RFC

.
. ,
,

. , (
),
. ,

. ,

,
(UDP), (TCP).
RPC
:

,
,

rpcgen. , ,
, RPC.

SI
5, " ", ,


, ,
. ,
.
, .
,

, (7).
TCP/IP 4 .
TCP ,

. ,
. ,
.
.
, ,
. FTP Telnet.

.
,
. , . !
,

.

. ,
,
. ,
"" , ( )

15. (RPC)

293

www.books-shop.com

. ,
.

,
. , .

,
().

. "",

. ,

( ),
.
,
. ,


, ,
. , ,

. ,

:
.
.

, "" .

, 
,  .
.
(int char) (
) .  
. , 
. , 
.
, ,
.

. ,

. getphoto(),
. image_t host_t

294

IV.

www.books-shop.com

, , NULL.
/*******************************************************/

/*** ,  ? ***/
/***
***/
/**************************************************/
image_t *getphoto(host_t host);

.
. ,
, S .
. ,
.
. ,
"", . ,
.
.

, ,

, .

, , .
, .

:
/********************************************************/
/***

***/

/*

******

*/

/* getuserinfo() */
/*

*/
/*
user ()
*/
/*
host ()
*/
/*'
data

()
*/
/* :
*/
/*
( errno) */
int getuserinf(char* user, char* host, userinfo_t *data);
: ,

, . ,
, .


"" .

,
. .

15. (RPC)

295

www.books-shop.com

, .

, .

, .
RPC .



.
RFC
,
.

/ (,
).

. ,
, .
: ,
,
.

10, " ", ,


.

, .

,

, ,
(, ). ,

,
( ).
SQL
COMMIT.
,

(,
). ,

.
.
,

. .

,
. ,
. , Socket API

, .

296

IV.
www.books-shop.com

, , (

). 10,
" ".
,
.

, .


.
, .
, .
,

. ,


, ,
.

.

, . ,
. , ,
.

. (,
,
!) , ,

.
.


, ,
. ,
, ..
,
.

. , .

.

, , /
.

, ,

.
, :
, .

15. (RPC)

297

www.books-shop.com



, .

.
getphoto() getuserinfo(), ,
, .
.

, ,

.
,
,
.
, ,


,
. , ,

. .

,
.

, .
,
.

.
UDP,

.
, ..
, .
TCP. ,
,

. ,

: , .


, .
,
, .
, ,

298

IV.
www.books-shop.com

(, ,
recv() ). ,
.
.
,
. Linux

, (

). ,
. , ,
6, " ".
1. .
2.
, .
3.

.
4.

5. ,

.
6. ,

, .
7. .
, , ,

.
,
.
.
.
, .

. ,

.
.
, ,

.
.

. ,
.

. ASCII EBCDIC.
OSI
. ,

15. (RPC)

299

www.books-shop.com

, .
, , .

RPC

rpcgen

Linux rpgen,

RFC
. RFC

.

.
rpcgen
,
UNIX. , ,

, .
, ..
, ,
.

RPC . ,

COM
+,



X.
COM.


, ,

UTC ( , 1
1970 .):
/*** , ***/
/*********************** ***************************************/
program RPCTIME

{
version RPCTIMEVERSION
{
long GETTIME() = 1

} = 1;

} = 2000001;
RPCTIME.
, rpcgen
.
, .
.
.
. ,

300

IV.

www.books-shop.com

,
.
2000000
3000000.
,
long, time_t. rpcgen (

),

. , ,
:

typedef long time_t;


XDR rpcgen

.
:
rpcgen
a rpctime.x

,
.

(rpctime_clnt.c) (rpctime_svc.c)

. ,
XDR
(rpctime_xdr.c). He


.

rpcgen
(rpctime_client.c) (rpctime_server.c) ,
Makefile.rpctime,
. .

, make clean
, pake

clean. Makefile .
, ,

gettime_1(). _1 .
, gettime()
,

. rpcgen .
rpcgen

, .

rpctime_client.c :
/************************************************/

/***
RFC
***/
/************************************************/
/* */
result_l = gettime_l((void*)&gettime_l_arg, clnt);
if (resultlt_1 == (long *) NULL) {
clnt_perror(clnt, "call failed");
}
/* */

15. (RPC)

301

%RRNVVKRS

piracy@books-shop.com

else
printf("%d|%s", *result_l, ctime(result_l));
.
:
/**********************************************/
/***
RFC

***/
/**********************************************/
static long result;
time(&result);
/* */
return &result;
rpcgen , ,

return. , :
make
f Makefile.rpctime
./rpctime_seryer &
./rpctime_client127.0.0.1

ASCII
.

$
rpcgen,
string bool_t.
. bool_t

0, 1, .
string . char*

char, char ,
NULL. ,
string. :
string filename<100>; /* 100 */
string myname<>;
/* */
. " ,
. , XDR
.

(union),

switch:
/***

RFC

***/

union proc res switch (int Err)

case 0:
string Data<>; /* Err ,
Data */
default:

302

IV.
www.books-shop.com

void; /* Err 0,

*/

};
,

, Err. rpcgen
:
struct proc_res
{

int Err;
union

{
char *Data;
} proc_res_u;

};
, ,
XDR.
, .
, NULL. ,
,
,
,
.
,

, :
/***************************************************************/
/***
RPCProc
***/
union proc res switch (int Err)

{
case 0: /* */
string Data<>;
/* */
default: /* */
void;

program RPCPROC

{
version RPCPROCVERSION

{
proc_res READPROC( string) = 1; /*
/proc */

} = 1;

} = 2000025;
,
/proc, . ,

, .
. ,

, .

15. (RPC)

303

www.books-shop.com

, , .
char*.

. ,
a

, . XDR
,
:
xdr_free((xdrproc_t)xdr_proc_res, (void*)&result);
, , xdr_<_>
( xdr_proc_res). ,
.

. ( Web
.)


. struct

, rpcgen:

. ,

.
:
/**********************************/
/*** RPCList ***/
typedef struct NodeStruct *TNode;
struct NodeStruct
{
string Name<>;
TNode Next;

}
, (TNode).
, ,

: ,
. XDR "":

,
"" .
,
.

.
typedef::
typedef struct NodeStruct TNode;
struct NodeStruct
{
string Name<>;
TNode *Next; /* !

*/

304

IV.

www.books-shop.com


. ,
. ,
.
(, ).

( ,
) (

).

, , . ,
. ,
.
, , ,

.
.

.
.
.
.

.

.
,

. .

,
.

15. (RPC)

305

www.books-shop.com

, :

, .

.
.

.
,

.

,
, . ,
, ,
.
,
. .
, , ,
.
.

.

, ,

..
, .
.
,
.

.
.
, . .
.

, .

. .
,

, .
, .
,

306

IV.

www.books-shop.com

: RPC$

, .
:

rpcgen.
6 , .
; ,
, , .

, .
rpcgen ,

.
. ,
.
RFC
.
" ".
, .
,

.
RPC SSL (Secure Socket Layer
), .

,
.

15. (RPC)

307

www.books-shop.com

16

...

Internet

319
321

323


SSL

329
330

335

www.books-shop.com

, ,
.

.

. :
" ".

, .
.
: " ?"

: , Internet,

, SSL.



. ,
, : .
,

, ,
.

, .

:


.
.
"", , .

.

.

Linux ,

. , Windows 95 98

.
,
, " ".
. ,
( ) , .

16.

309

www.books-shop.com


, ,

.
: .

. ,

, ,
.
,

. Web

.
,
. ,


. , ,
.
.
,

TCP/IP.
.

. ,
, (
). ,

"" .
:

. ,
.


, .
,

. RPC
( , telnet, rlogin
rsh). , , .
.
. ,

.
"" Love Bug Microsoft Outlook.

. ,

Internet
Internet , ,

. , ,
,

310

IV.

www.books-shop.com

. ,

.
Internet .
: "

".
,
"" ;

,

: Internet .

"!", ,
. :
. ,
.

. , .
AT&T US Sprint.
.
,

.
,

Internet.

Internet ( ),

. ,
, Internet .
Internet , " ",
.
,

root. , .

,
, Linux,

.
.

, , ^


,
. .

, .

.


.
,

16.

311

%RRNVVKRS

piracy@books-shop.com

.
" ping" b " ".
,
.
, , Linux,
,

.
, , ,
.
. ,
.
, .

. Linux ,

. : , .
, ,

.
TCP/IP
Internet.

Novell Microsoft ,
Internet.

TCP/IP?

, IP "". ,
, ,

,
(, IP root),

ICMP, UDP RDP (Reliable Datagram Protocol

).
TCP/IP .
, TCP
. ,
,

.
, TCP

. ,
. ,

, (
: , ),
.. TCP ,

, .

312

IV.

www.books-shop.com


?
.
, .
, .
.
,
.

.
,
.
root (,

IP
).

, . ,

I
.
,
.

.
,

.

Ethernet
( ),

.
,
. , ,
Telnet,
, , ,

Internet.

( ), .
, , .
,

. , ,

, .

16.

313

www.books-shop.com

. , ,

.
,
: .
.

. ,
.
.
.

. ,

. , FTP

, HTTP
.
, ,

IP
. , ,
DHCP. ( ),
, .

, 
, IP.
. , FTP :
, .
, . B
. ,

.

,
.
: !
( ).

,
, .
.

.
, ,
.
, ,

(. 1
6.1).

, .
:
?

. ""
,

, .

314

IV.

www.books-shop.com

Internet,

(. 16.2).

. 16.1. Internet !

. 16.2. !

,
.
:
.

, .

, ,
. .
( ),

, .
, .

16.

315

www.books-shop.com

RPC

. o , ,

, . , portmap
R . RPC , Java RMI Microsoft
/+. Web
, ,
|
, .
( ).
Internet
. ,
.
HTTP, HTTPS FTP ( ).
( ).

.
,
TCP
, ,
.
,

, .
(
). , Perl, C/C++,
,

. ,

,
.
.
IP

.

, .
Internet

, .
Internet , .
, .

: .
:

, , .

316

IV.

www.books-shop.com

.
.
. : /
/.
( )
.
,

, .
(
)
( )

. ,
.
.
,
() .

, .
,
.
, ,
. ,

, .

,
, .
, . .
.
,
,

( ). ,

HTTP ,

. :

.
,
.

.
, ,


.
.

, , . Internet ( !).

. ,

. ,

16.

317

www.books-shop.com

. (, ,

.)
,
. ,
.
.
.

. ,
,

. ,

128
.


, . 
, , ,
. , 
, , . ,
, .
.
128 ,

(10
9) ,
20
10 . ,
.
: ( )

( ).

. , UNIX .

.
, , .
, , .

,
.
, ,
/.

Enigma ("").

.
, .
,

,
. , ,
. ,
"", .

318

IV.
www.books-shop.com


:
. :
(), ().
.

, . ,
. ,
.
, ,
, .

. (
,

.)
.
,
.

, .
. , 128

232 .
,

. , 128

, 64
32

.

Internet

. RSA (

: (Rivest), (Shamir) (Adelman);


), DES (Data Encryption Standard
) RC2/RC4 ( ),
(
RSA 2000 ).
Linux ,
Web

.

.
,
""
. ) ,
.
. 2000 ..

, .
.
,

16.

319

www.books-shop.com

, :

. , Internet ,

SSL
, ,
. SSL
(Secure Sockets Layer ).

. SSL

, .

, .
SSL
. , SSL

OpenSSL.
, .

OpenSSL
,

SSL
OpenSSL.
www.openssl.org , , ,
Linux. ,
, (
,

Mandrake Red Hat Linux;

, ).
1. tar
, ( )
.
2. config (./config).
, ,

./config linux
elf.
3. make, .
4. make test, .
5.

root. make
install, (/usr/local/ssl).

6.

ln
s /usr/local/ssl/lib/libssl.a/usr/lib/
ln
s /usr/local/ssl/lib/libcrypto.a/usr/lib/
7.

ln
s /usr/local/ssl/include/openssl/usr/include

320

IV.

www.books-shop.com

8. /etc/man.config MANPATH

/usr/local/ssl/man,
(, makewhatis).
9. PATH /usr/local/ssl/bin.
, ^
, 600 .
,
libssl.a libcrypto.a : . .so.

( ,
):
cc test.
lssl
lcrypto
, ,
C++. .

. (
, ,
,
!)

SSL$
, /. SSL

SSL
, ,
OpenSSL
.
OpenSSL:
/*************************************************************/
/***

***/
/**************************************************************/
SSL_METHOD method;
SSL_CTX *ctx;
OpenSSL_add_all_algoritms();
/* */
SSL_load_error_strings(); /*
tf6 */
method = SSLv2_client_method();
/*
*/
ctx = SSL_CTX_new(method);
./* */
NULL 0,
:
ERR_print_errors_fp(stderr);

/*
stderr */

:
/***

SSL

***/

struct sockaddr_in addr;

16.

321

%RRNVVKRS

piracy@books-shop.com

struct hostent *host = gethostbyname(hostname);


:
int sd = socket(PF_INET, SOCK_STREAM, 0);
/* */
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
/* */
addr.sin_addr.s_addr = *(long*)(host
>h_addr); /* */
connect(sd, &addr, sizeof(addr));
/* */

SSL :
**********************************************************/
/***
SSL
***/
/***

***/
/**********************************************************/
SSL *ssl = SSL_new(ctx); /* SSL
*/
SSL_set_fd(ssl, sd);
/* */
if ( SSL_connect(ssl) ==
1 ) /* */
ERR_print_errors_fp(stderr);
/* */
SSL
.

:
char* cipher_name = SSL_get_cipher(ssl);
:
/***************************************************************/
***/
/**

/***************************************************************/
char line[1024];
509 *509 = X509_get_subject_name(cert);
/* */
X509_NAME_oneline(x509, line, sizeof(line)); /* */
printf("Subject: %s\n", line);
x509 = X509_get_issuer_name(cert);
/* */
X509_NAME_oneline(x509, line, sizeof(line)); /* */
printf("Issuer: %s\n", line);
,

, send() recv(). .

, flags ;
, 1.
send() recv() ,
.
/***************************************************************/
/***

int bytes;
bytes = SSL_read(ssl, buf, s i z e o f ( b u f ) ) ; /* / */
bytes = SSL_write(ssl, msg, strlen(msg)); /* / */
,

322

IV.

www.books-shop.com

SSL
.

, SSL.
.
, :
/***

***/
/**************************************************************/
SSL_METHOD method;
SSL_CTX *ctx;
OpenSSL_add_all_algoritms();
/* */
SSL_load_error_strings(); /*
*/
method = SSLv2_server_method();
/*
*/
ctx = SSL_CTX_new{method);
/* */
, , ,
SSL2, SSL3. ,
Netscape.
, .

: ,

. .
, , :
/***

***/
/************************************************************/
/* */
SSL_CTX_use_certificate_file(ctx, CertFile, SSL_FILETYPE_PEM);
/* */
SSL_CTX_use_PrivateKey_file(ctx, KeyFile, SSL_FILETYPE_PEM);
/* */
if ( !SSL_CTX_check_private_key(ctx) )
fprintf(stderr, "Key & certificate don't match");
,
.

, Internet,
, VeriSign.
, OpenSSL (
, ). Perl CA.pl
/usr/local/ssl/misc, .
, , PATH 
/usr/local/ssl/bin.

16.

323

www.books-shop.com

, :
/***

***/

struct sockaddr_in addr;


int sd, client;
sd = socket(PP_INET, SOCK_STREAM, 0);
/*
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = INADDR_ANY /*

bind(sd, &addr, sizeof(addr));


/*
listen(sd, 10);
/*
client  accept(server, &addr, &len); /*

*/

*/
*/
*/
*/

, SSL 
:
/***

SSL

***/

ssl = SSL_new(ctx);
/* SSL */
SSL_set_fd(ssl, client);
/* */
if ( SSL_accept(ssl) == FAIL ) /*

SSL */
ERR_print_errors_fp(stderr);
else
{ int bytes;
bytes = SSL_read(ssl, buf, sizeof(buf));
SSL_write(ssl, reply, strlen(reply));

/*
*/
/* */

}
. Web

Netscape.
,
.

:

. ,

, , .
Internet,

.
Internet , .
Internet.
,
. ,
324

IV.

www.books-shop.com

, Web

.
,
Internet, ,
.

.
.

, SSL.
SSL.
.
OpenSSL,
200 .
OpenSSL, ,
, Internet.

: .
,

, ,

16.

325

www.books-shop.com

17

...

337

339

346

www.books-shop.com

. ,
, , .

?
.
,

,
. "".
IP

: . ,
.


[RFC919, RFC922]
. :
. ( ,

, .
, .)
IP

. 2, " TCP/IP",
ifconfig ,
. ,
.

. , 1 9 8 . 2 . 5 6 . X X X , 250 ,
198.2.56.0, :
198.2.56.255. ( 2, " TCP/IP", ,

, , . :

.)

: . ,

.
, .

, IP
(

Ethernet

). , ,


. ,
,

.
, ,

,
,
(FF:FF:FF:FF:FF:FF).

, ,

17. , ...

327

www.books-shop.com

, .
, .
IP
. .

, .
( UDP) ,
,


. .

. "" .


SO_BROADCAST. :
.
/***

***/

const int on=l;


sd = socket(PF_INET, SOCK_DGRAM, 0);
if ( setsockopt(sd, SOL SOCKET, SO_BROADCAST, Son, sizeof(on))

1= 0 )
panic("set broadcast failed");
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin~port = htons(port);
addr.sin~addr.s_addr = INADDR_ANY;
if ( bind(sd, Saddr, sizeof(addr)) != 0 )
panic)"bind failed");
addr.sin_port = htons(atoin(strings[2]));
if ( inet_aton(strings[1], Saddr.sin_addr) == 0 )
panic("inet_aton failed ( % s ) " , strings[l]);
,
.
. ,
,
.

:
/*** . ***/
/*** .
***/
if ( fork() )
Receiver(sd);
else

{
shutdown(sd, SHUT RD); /* */

Sender(sd);
}
wait(O);

328

IV.
www.books-shop.com


.
, ,
. , ,

. ,
255.255.255.255 Internet. ( ,

.
,

, 198.2.255.255, , 198.2.1.0,
.)
.
,
. ,
.
. IPv4
.

, .

[RFC1112]

.
.

, ,
.
.
.

, TCP
. TCP,
Linux,
.
.
. , Internet,
.
.

(
" ").
IPv6. IPv6

, .
'
Linux , 
( /proc/net/dev_mcast, , 
), ,
, , ,
.

17. , ...

329

www.books-shop.com


,
. , ,
, . ,

.
2, " TCP/IP", ,
IP
,

: 224.0.0.0
239.255.255.255. , ,
, , ..

,
(. 17.1).
17.1.

(TTL)

224.0.0.0
224.0.0.255

< 32

239.255.0.0
239.255.255.255

< 128

239.192.0.0
239.195.255.255

<= 255

224.0.1.0
238.255.25.255

, setsockopt(),
ipjnreq:
/***************************************************************/

/***

ipjnreq

struct ip_mreq

struct in_addr imrjnultiaddr; /* */


struct in_addr imr_interface; /* */

};

imrjnultiaddr ,

. , sin_addr sockaddr_in.
imr_interface .

bind(), ,
INADDR_ANY,

.

imr_interf INADDR_ANY,
. , Linux 2.2.
" ". , 
, .
,
ipjnreq . imr_interface INADD_ANY
.

330

IV.

www.books-shop.com

,
,

.
/***************************************************/
/*'**

***/
/***************************************************/
const char *GroupID = "224.0.0.10";
struct ip_mreq mreq;
if ( inet _aton(GroupID, &mreq.imr_multiaddr) == 0 )
panic("address ( % s ) bad", GroupID);
mreq.imr interface.s_addr = INADDR_ANY;
if ( setsockopt(sd, SOL_IP, IP_ADD_MEMBERSHIP, &mreq,
sizeof(mreq)) != 0 )
panic("Join multicast failed");

, SO_REUSEADDR.
Linux (SO_REUSEPORT).
/***********************************************************/
/*** ***/
/*************************************************************/
if ( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))
!= 0 )
panic("Can't reuse address/ports");
, ,

. UNIX 16
. , , .

, "

".
, :
/***********************************************************/
/***

***/
/*************************************************************/
if ( setsockopt(sd, SOL_IP, IP_DROP_MEMBERSHIP, &mreq,
sizeof(mreq)) != 0 )
panic("Drop multicast failed");
,

.

, 
. , 
, . ,
.
.
. ,

IP
.
. Internet,
IAB (Internet Architecture
Board Internet).

17. , ...

331

%RRNVVKRS

piracy@books-shop.com

. UDP
,

.

, 
. '.
, . 
.

" ":
, .

/. ,
, .
.
,

, . ,
.

( , Linux)

, , ,
"" . ,
,
.
MAC
(

).

. ,

(FF:FF:FF:FF:FF:FF),

, 01:00:5,

( 23 ) .

, 224.138.63.10 (EO:8A:3F:OA)

01:00:5E:OA:3F:OA ( , 8 8 ).
,
. .
. .

, .
.
! ( ).

64
512
.
,

.

, .
,

.
.

332

IV.

www.books-shop.com

. ,
, .

.
.
,
TCP/IP
. , ,

, , ,
. UDP
TCP, .

, .

.
. .

, .


Internet

: IP

.
, , .

; ,
.
.
.


. ,
.
, Internet

IGMP (Internet Group Management Protocol

) [RFC1112, RFC2236],
. IGMP


,
. ,

. .
( , .

,
.)

, ,
, .
( )
17. , ...

333

www.books-shop.com

.

.
. .
,
, .

, .

(
)

,

, . ,
, .

1992 . , ,

. ,
IP

,
.
(multicast backbone, Mbone) .
?
( mrouted),
mrouted. mrouted

.
IP
. mrouted

, .

, ,


,
. ,
.
, , ,
.

,
.
, .

334

www.books-shop.com

, , ,
,
(, "" ,
56 /). ?
, .
.

, .

. ,

, ,
.
, Internet
. ,

,
. ,
.

.
,

IGMP.

,
. , ,
,
,
, .

, .
, .
, , .

.
( )
.

, ,
. ,

.
,

. ,
.

17. , ...

335

www.books-shop.com

18

...

348

349

350
352
354
35

ping

;

www.books-shop.com

. TCP UDP
I
.

, . ,



, IP

, .
, . ,

, ,
. ,
,
ICMP
ICMP (Internet
Control Message Protocol Internet),

. , TCP UDP,
ICMP
. , Sockets API
, SOCK_MSG.

( SOCK_RAW), ICMP

.
ICMP ,

, " ". (
ping), , .

, , ICMP
.
IP
IP

IP_HDRINCL. 3,
" Internet
".
setsockopt(), , .
IP
, ,
. ,
IP,
. 3.1.

18.

337
www.books-shop.com

. ,
, .
, , 12

10 /.
. ,
, .

, , .


, .
.
,

. .
.

. , TCP :
. ,
UDP, .
.

( ).
,
,
. ,
,
.
MyPing, .
.

, ,

. ICMP

TCP/IP.
ICMP!.
, ICMP

, TCP (SOCK_STREAM) UDP (SOCK_DGRAM).

, 3.2,

, ,
.

338

IV.

www.books-shop.com

TCP! UPD!o. TCP UDP


.
, 6 (TCP) 17 (UDP),

. ,
. UDP
,
UDP
,

, .
. ,
, ,
root.
,

, ,
.

.


. ,

/etc/protocols ( , "

").

getprotobyname():
#include <netdb.h>
struct protoent* getprotobyname(const char* name);

protoent. p_proto
:
struct protoent* proto;
int sd;
proto = getprotobyname("ICMP");
sd = socket(PF_INET, SOCK_RAW, proto
>p_proto);
, ICMP

, .
socket() SOCK_RAW.
ICMP

,
. IP

18.

339

www.books-shop.com

, sendtsof)
, .
I
.
( ) Linux
, ICMP
:
#include <netinet/ip_icmp.h>
struct,
icmphdr

,*icmp_header;

:
#define PACKETSIZE 64 /* '*/
struct packet_struct
{
struct icmphdr header;
char message [PACKETSIZE
sizeof( struct icmphdr)];
} packet;
.

, ICMP
,
. ,
. , Linux
, , ,
.

18.1.
1 8. 1 . ICMP
unsigned short checksum(void *b, int len)
{ unsigned short *buf = b, result;
unsigned int sum=0;
for ( s u m = 0 ; l e n > 1 ;

len
=2)

.
/*
*/

if ( len == 1 )
/* , */
sum += *(unsigned char*) buf; /* */
sum = (sum >> 16) + (sum & OxFFFF); /* */
sum += (sum >> 16);
/* */
result = sum;
/* , */
return result;
/*
*/
}
:

, .
, .

, .
, .

340

IV.

www.books-shop.com

IP
IP
,

, ,

. ICMP, IP
,
.
IP

(. 3.1), .
, sendto()
, ,

(4 PF_INET, 6 PF_INET6). ,
.
setsockopt().

IP

. .
, : ,

.
,

.
.
, ,
.

, TCP, , IP

IP
. IP
,

.

, IP ,
. , ,
,  . , , 

.
Internet "" , 
IP. , Linux :
.

ping
, ,
ping, ,.
. IP
:
, ping.
,

, :

, . , ,

,
, .

18.

341

%RRNVVKRS

piracy@books-shop.com

MyPing
. .
recvfrom() ( 18.2).
18.2. MyPing
/***
MyPing.
***/
/***
MyPing.c Web
.
***/
/****************************************************************/
for ( ; ; )

int bytes, len=sizeof(addr);


bzero(buf, sizeof(buf)); /* */
bytes = recvfrom(sd, buf, sizeof(buf), 0, &addr, &len);
if ( bytes > 0 )
' /* , */
display(buf, bytes);
/*
*/
else
perror("recvfrom");

display() buf packet_struct

. , ,

.
,

. ,

, ,
. ,

.
.

ICMP, ICMP
( ,

). ? ICMP

(PID process ID).


.
, .
MyPing
.

, ( 18.3).
18.3. MyPing
/************************.****************************************/
/***
MyPing.
***/
/***
MyPing.c Web
.
***/
/***
for ( ; ; )

{ int len=sizeof(r_addr);
342

IV.

www.books-shop.com

/* , , */
if ( recvfrom(sd, &pckt, sizeof(pkt), ft/ &r addr, slen) > 0 )
print("***Got message!***\n");
/* */
bzero(&pckt, sizeof(pckt));
/*
pckt.hdr.type = ICMP_ECHO;
/^ 
pckt.hdr.un.echo.id = pid;
/*
for ( i = 0; i < sizeof(pckt.msg)l; i++ )
pckt.msg[i] = i+'O';
/*

pckt.msg[i] = 0;
/*
pckt.hdr.un.echo.sequence = cnt++; /*
pckt.hdr.checksum =
/*
checksum(&pckt, sizeof(pckt));
if ( sendto(sd, &pckt, sizeof(pckt), 0, addr, /* !
sizeof(*addr))<= 0 )
perror("sendto");
sleep(l);
/*

*/
*/
*/
*/
*/
*/
*/
*/
*/

.
ping TTL ( )
: 255. ,

, recvfrom()
.

ICMP

. traceroute
.
My Ping,
ICMP
.
,

TTL.
(ICMP).
TTL . ,

. :
.

,
.
,

MyPing. :
TTL = 0;
do

{ int len=sizeof(r_addr);
struct iphdr *ip;

18.

343

www.books-shop.com

TTL++;
if ( setsockopt(sd, SOL_IP, IP_TTL, &TTL, /*

TTL */
sizeof(TTL)) != 0 )
perror("Set TTL option");

/***
(. MyPing) ***/
if { sendto(sd, &pckt, sizeof(pckt), 0, addr, /* ! */
sizeof(*addr)) <= 0 )
perror("sendto");
if ( recvfrom(sd, buf, sizeof(buf), 0,
/* */
&r_addr, &len) > 0 )
{ struct hostent *hname;
ip = (void*) buf;
printf("Host #%d: %s \n", cnt1, /* IP
*/
inet_ntoa(ip>saddr));
hname = gethostbyaddr(
/* */
(void*)&r_addr.s_addr, sizeof(r_addr.s_addr),
r addr.sin_family);
if ("hname !=NULL )
printf("(%s)\n", hname>h_name);
else
perror("Name");

}
else
perror(recvfrom);
}
/* ,
*/
while ( r_addr.sin_addr.s_addr != addr
>sin_addr.s_addr );
, ,
. ,
. 2, " TCP/IP".

ICMP,

IP
.
.
,
IP

.
ping traceroute.

344

IV.

www.books-shop.com

IPv6:

IP

19

...

IPv6

358

IPv6
:

366

360

367

www.books-shop.com

Internet .
IP
,

. ,
IP
, , .
IP:
IPv6.
IPv4.

, ,


IPv4

. 2, " TCP/IP", IP

32
(4 ).. .
,
, :
.
Internet , IAB,
, . ,
1% .
Internet .
,

, Internet, . IPv4
.

$

IAB .
IP
,
DHCP IP

.
, 32

. IPv6 [RFC2460].
IPv6 128
(16 ).

IPv4
( ). IPv6

1x1038!

IPv6
IPv6

IPv4, .
, ,
2FFF:80:0:0:0:0:94:1.
: 2FFF:80::94:1.

346

IV.
www.books-shop.com


,
, . ,
80 : 2FFF:80::94:1.80.
IPv6 , [RFC 1897,
RFC2471]. (
IPX).

.
, 001,

IPv4. . 19.1 .

. 19.1. IPv6 , !
,
. 19.1 ,

. 19.1.
19.1. IPv6

(001), Internet (
)
(TopLevel Aggregation ID);
Internet (13
)
(NextLevel Aggregation
ID); (32 )
(SiteLevel Aggregation
ID); (16 )
(64 )

TLAID

NLAID
SLAID

2, " TCP/IP", "

", .

.

.
IPv4 IP
.
IPv6 .
(TLA, NLA SLA), , .
,

, .

19. IPv6: IP

347

www.books-shop.com

IPv4 IPv6?

. Internet

IPv6. IPv4.
?
, IPv6,

IPv4. ,

IPv6.
.

. Internet UDP TCP,

IP
. IPv4

, IPv4.
IP
, , TCP
UDP. ,
IPv4 IPv6 .
IPv6 IPv4, ,
, .
IPv4 IPv6, 80 IPv6
, OxFFFF
IPv4. , 128.10.48.6 ::FFFF:128.10.48.6, ..
::FFFF:800A:3006 (, :: ).
, ,

, IPv4,
IPv6. ( . 128

32
. IPv4

"" , .

, .)

IPv6
IPv6

. Linux
IPv6
, . ,
.

,

IPv6. /, /proc/net.
igmp6 if_inet6. ,
ipv6.o.

348

IV.
www.books-shop.com

ifconfig
ifconfig, net_tools, ,

ipv6.o.
ipv6 .
,
. (

,
.
Web
www.kernel.org.) ,
Experimental Drivers. IPv6
It Is Safe to Leave These Untouched Network Settings.
IPv6. ! ,
, ipv6 ,
. .
,


.
IPv6, ifconfig

. .
IPv6 ,
IPv6.
,

help.
. , IPv6
. net_tools,
.
configure.sh, IPv6.
,
( /sbin).
,

. , ifconfig,
IPv4 .
IPv6 :
ifconfig eth() add < IPv6>
:
ifconfig eth() add 2FFF::80:453A:2348
.

IPv4 IPv6
,

. ,

19. IPv6: IP

349

www.books-shop.com

, ,

.
.
sockaddr_in, a sockaddr_in6:
struct sockaddr_in6 addr;
bzero(&addr, sizeof(addr));
b i n d ( ) , connect() accept()
. .

.
PF_INET6:
sd = socket(PF_INET6, SOCK_STREAM, 0); /* */
/* */
.
.,
..
sd = socket(PF_INET6, SOCK_DGRAM, 0);
/* UDP6 */
/* */
sd = socket(PF_INET6, SOCK_RAW, 0);
/* ICMP6
*/
, , .

socket();

:
addr.sin6_family = AF_INET6;
addr.sin6_port = htons(MY_PORT);
if ( inet_pton(AF_INET6, "2FFF::80:9ACO:351",
perror("inet_pton failed");

&addr.sin6_addr)

== 0 )

sockaddr_in6 ,
. ( bzero()
memset()), .
.
inet_pton().
inet_ntop()
. IPv4, IPv6, Rose IPX. ,
GNU

AF_INET AF_INET6.
:
tinclude <arpa/inet.h>
int inet pton(int domain, const char* prsnt, void* b u f ) ;
char *inet_ntop(int domain, void* buf, char* prsnt, int len);
inet_pton()

,
buf. inet_ntop{) . domain
, len prsnt.

350

IV.

www.books-shop.com


IPv6
UDP TCP .

ICMP, ,

IPv6.
IPv6 , IPv4,
(40 , 20). ,
.

( ):
/***

IPv6

***/

union IPv6_Address
{

unsigned
unsigned
unsigned
unsigned

char u8[16];
short int ul6[8);
long int u32[4];
long long int u64[2];

};
struct IPv6_Header

{
unsigned
unsigned
unsigned
unsigned

int version:4;
/* IP (6) */
int priority:4;
int flow_label:24;
int payload_len:16; /*
*/
unsigned int next_header:8; /* ( TCP) */
unsigned int hop_limit:8;
/* , L */
union IPv6_Address source;
union IPv6_Address dest;

};
. priority

. ,

.
flow_label priority.
(flow) ,
.
, .
. ,
. priority flow_label ,

sin6_flowinf sockaddr_in6.
, payload_len 0, .
1 / ( 100 /)

( 100 ),
19. IPv6: IP

351

%RRNVVKRS

piracy@books-shop.com

. ,0,

:
/***

(Jumbo)

***/

struct Jumbo_Payload
{

unsigned char option;


unsigned char length;
unsigned long bytes; '

/* 194 */
/* 4 () */
/* */

};

4 .
ICMPv6
ICMPv6 [RFC2463] ,
ICMPv4, type code . ,


(128 129 ).
.
, " ".


. : ,
.
17, ",
",
: ,

: IPv6
33:33. ,

FF02::725:6832:D012,

33:33:68:32:00:12 (725 ).
IPv6 , IPv4. , FF,

, . 4

. ,
. ,

, , .
.
(

). , . IPv4

TTL ( ,

). ,

. IPv6 (. 19.2).

352

IV.

www.books-shop.com

19.2. IPv6

1
2

5
8
14

( 12 7.0.0.1)
, 
; 



(
)

, (. 17, ",

") . IPv6

IGMP, IPv4,
.


, .
IPv6 , IPv4,
:
/***
IPv6
***/
/**************************************************************/
struct ipv6_mreq
struct in6_addr ipv6mr_multiaddr; /* IPv6 */
unsigned int ipv6mr_interface;
/* */
, ipv6mr_multiaddr,

IPv6 (, FF02::10). :
, 1 (ethO) ..
:
/**************************************************************/
/***
IPv6
***/
/**************************************************************/
const char *GroupID = "FF02::4590:";
struct ipv6_mreq mreq;
if ( inet_pton(GroupID, &mreq.ipv6mr_multiaddr) == 0 )
panic("address (%s) bad", GroupID);
mreq.ipv6mr_interface =0;
/* */
if ( setsockopt(sd, SOL_IPV6, IPV6_ADD_MEMBERSHIP, &mreq,
sizeof(mreq)) != 0 )
panic("Join multicast failed");
if ( setsockopt(sd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))

!= 0 )

panic("Join multicast failed");


19. IPv6: IP

353

www.books-shop.com

IPv6
IPv6 IPv4.

, , 128

.
, , IPv4 :,
.
,

. , IPv4,

6.4 .

, Jumbo 4 .

. , ,

, .
IPv6.
,
. IPv4 20 .
IPv6 40 . IPv4
. , IPv4

65535 , IPv6 ( Jumbo)


65535+40 .
IPv6 .

.
, IPv6 .

, CRC
.

.
Linux
Linux
IPv6. Linux, 2.2.0,
. IPv6 ,

. 100%.
6b

IPv4 , 
Mbone ( ), 
IPv6. IPv6 6bn,
IPv6 IPv4,
. .
: IPv6
.
, Internet.

354

IV.

www.books-shop.com

:

IPv6 ,
IPv4. , IPv6

Internet. IPX,

.
, IPv4, IPv6
,
, . socket()

.
IPv6 IPv4,
IPv4
.

, , ,
.
Linux, 2.2.0, IPv6,
.
, .
, ,
. ,

. IPv6
, .

19. IPv6: IP

355

www.books-shop.com

www.books-shop.com

V
...
.
.
. API
.

www.books-shop.com

...
371
375
376

: socket()
: socket()

Internet (
100 )
HTTP 1.1
( get/setsockopt())

ICMP
IPv4
IPv6
ICMPv6
IPv6
IPv6

377
378
380
386
388
389
389
390
391
392

www.books-shop.com

,
.

:
socket()
. socket().
bind(), ,
AF_.

. sys/socket.h.
.1. socket()

PF UNSPEC

PF_LOCAL
PF_UNIX
PF FILE

BSD 

PF_INET

#include <linux/un.h>
struct sockaddr_un addr;
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path,
"/tmp/mysocket");

struct sockaddr_un {
sa_family_t sun family;
char sun_path[UNIX_PATH_MAX];

IPv4

struct sockaddr in {
sa_family_t
unsigned short int
struct in_addr
unsigned char

#include <linux/in.h>
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
if ( inet_aton("127.0.0.1",
&addr.sin_addr) == 0 )
perror("Addr conversion");

PF_AX25


struct sockaddr {
unsigned short int sa_family;
unsigned char sa_data[14];
};
#define UNIX_PATH_MAX 108


.25
#include <linux/AX25.h>

};
sin_family;
sin_port;
sin_addr;
pad[];

};

typedef struct {
char ax25_call[7];
} ax25_address;
struct sockaddr_
sa_family_t
ax25_address
int

ax25 {
sax25 family;
sax25_call;
sax25_ndigis;

};

359

www.books-shop.com

PF_IPX

. A.I

Novell

struct sockaddr ipx

#include <linux/ipx.h>
sa_family_t sipx_family;
u16
sipx_port;
u32
sipx_network;
unsigned char
sipx_node[IPX_NODE_LEN];
u8
sipx_type;
/* */
unsigned char sipx_zero;
PF_APPLETALK

AppleTalk
#include <linux/atalk.h>

struct sockaddr_at {
sa_family_t sat family;
u8
sat_port;
struct at_addr {
u16 s_net;
u8 s_node;
}
sat_addr;
char
sat_zero[];

};
PF_NETROM


NetROM

PF_BRIDGE

PF_ATMPVC

ATM

PF_X25

( .25)
#include <linux/x25.h>

typedef struct {
char x25_addr[16];
} x25 address;
struct sockaddr_x25 {
sa_family_t sx25 family;
/* .121 */
x25_address sx25_addr;

};

360

V.
www.books-shop.com


PF_INET6


IPv6
#include <linux/in6.h>

. . 1

struct in6_addr
{

union {
_u8 u6_addr8[16];
_u16 u6_addr16[8];
_u32 u6 addr32[4];
#if ("OUL) >~oxfffffff
#ifndef _RELAX_IN6_ADDR_ALIGNMENT
/* 4 
.

,
*/
_u64 u6_addr64[2];
#endif
#endif
} in6_u;
#define s6_addr in6_u.u6_addr8
#define s6_addr16 in6_u.u6_addr16
#define s6_addr32 in6_u.u6_addr32
#define s6_addr64 in6u.u6_addr64
struct sockaddr_in6 {
unsigned short int sin6_family;
_ u16
sin6_port;
_ u32
sin6_flowinfo;
struct in6_addr sin6_addr;

PF_ROSE


Rose
#include <linux/rose.h>

typedef struct {
char rose addr[5];
} rose address;
struct sockaddr_rose {
sa_family_t srose_family;
rose_address srose_addr;
ax25_address srose_call;
int
srose_ndigis;
ax25_address srose_digi;
struct full_sockaddr_rose {
sa family t srose_family;
rose_address srose_addr;
ax25_address srose_call;
unsigned int srose ndigis;
ax25 address
srose_digis[ROSE_MAX_DIGIS];

.
%RRNVVKRS

piracy@books-shop.com

361

. . 1

(
DECnet)
PF_ NETBEUI (
802.2LLC)
#include <linux/netbeui.h>

PF_DECnet

PF_SECURITY

#define NB_NAME_LEN

20

struct sockaddr_netbeui {
sa_family snb_family;
char
snb _name[NB_NAME_LEN];
char
snb_devhint[IFNAMSIZ];

PF_ KEY

PF_NETLINK
PF_ROUTE

4.4 BSD
#include <linux/netlink.h>

struct sockaddr_nl
{
sa_family_t
nl_family;
unsigned short nl_pad;
u32
nl_pid;
u32
nl_groups;

PF_PACKET


#include <linux/if packet.h>

struct sockaddr_pkt

{
unsigned short spkt_family;
unsigned char spkt_device[14];
unsigned short spkt_protocol ;
struct sockaddr_ll
{
unsigned short sll_family;
unsigned short sll_protocol;
int
sll_ifindex;
unsigned short sll_hatype;
unsigned char sll_pkttype;
unsigned char sll_halen;
unsigned char sll_addr[8];

PF_ASH

362

Ash

V.

www.books-shop.com

PF_ECONET

Acorn Econet
# include <linux/if ec.h>

. . 1

struct ec_addr
{

/* */
unsigned char station
/* */
unsigned char net;

};
struct sockaddr_ec
{
unsigned short sec_family;
unsigned char port;
/* */
unsigned char cb;
/* */
unsigned char type;
struct ec_addr addr;
unsigned long cookie;

};
PF_ATMSVC

ATM
PF_SNA
PF_IRDA

Linux SNA
IRDA
#include <linux/irda.h>

struct sockaddr_irda {
sa_family_t sir_family
/* LSAP/TSAP */
unsigned char sir_lsap_sel;
/* */
unsigned int sir_addr;
/* <cep:IrDA:TinyTP */
char
sir_name[25];

};

:
socket()
socket() .
, . .2, ,
.

363

www.books-shop.com

.2. socket()

SOCK_STREAM

(TCP) .
, 
FILE*. 
. 
accept() ,

SOCK_DGRAM

(UDP) .
, .

SOCK_RAW

(IP) .
ICMP. root

SOCK_RDM

(RDM) . ,
. ( Linux
UNIX.)

SOCK_SEQPACKET

; . (
Linux.)

SOCK_PACKET

( ). (
), . 
Linux. root. (

PF_PACKET.)

.1 /etc/protocols [RFC2292],
.

.
.1. /etc/protocols

ip
icrop

0 IP
1 ICMP

igmp

2 IGMP

ggp

3 GGP
4 IPENCAP
5 ST
6 TCP

ipencap
st
tcp

egp
pup
udp
hmp
xnsidp

364

8
12
17
20
22

EGP
PUP
UDP
HMP
XNSIDP

IP (Internet Protocol)
ICMP (Internet Control Message
Protocol )
IGMP (Internet Group Management
Protocol )
GGP (GatewayGateway Protocol)
IP

TCP (Transmission Control
Protocol )
EGP (Exterior Control Protocol)
PUP (PARC Universal Protocol)
UDP (User Datagram Protocol)
HMP (Host Monitoring Protocol)
XNS/IDP (Xerox Network

V.

www.books-shop.com

rdp
isotp4
xtp
ddp
idprcmtp

27
29
36
37
39

rspf
vmtp

73 RSPF
81 VMTP

ospf

89 OSPFIGP

ipip
encap

94 IPIP
98 ENCAP

RDP
ISOTP4
XTP
DDP
IDPRCMTP

Standard Internet Datagram Protocol)


RDP (Reliable Datagram Protocol)
ISO Transport Protocol ( 4)
XTP (Xpress Transfer Protocol)
DDP (Datagram Delivery Protocol)
IDPRCMTP (InterDomain Policy
Routing  Control Message Transport
Protocol)
RSPF (Radio Shortest Path First)
VMTP (Versatile Message
Transaction Protocol)
OSPF IGP (Open Shortest Path
First Interior Gateway Protocol)
IP
IP

Internet$
( 100 )
.2 ( 100)
/etc/services. ,

.
.2. /etc/services
tcpmux
rtmp

1/tcp
1/ddp

nbp

2/ddp

echo

4/ddp

zip

6/tcp

echo
echo
discard
discard
systat
daytime
daytime
netstat
qotd
msp

7/tcp
7/udp
9/tcp
9/udp
11/tcp
13/tcp
13/udp
15/tcp
17/tcp

msp

18/udp

chargen

19/top ttytst source

TCP
RTMP (Routing
Table Maintenance Protocol)
NBP (Name Binding
Protocol )
(AppleTalk
Echo Protocol)
ZIP (Zone
Information Protocol)
sink null
sink null
users

quote

18/tcp

MSP (Message Send


Protocol)
MSP (Message Send
Protocol)

365

www.books-shop.com

chargen
19/udp
ftpdata
20/tcp
ftp
21/tcp
fsp
21/udp
ssh
22/tcp
ssh
22/udp
telnet
23/tcp
# 2 4
smtp
25/tcp
1 26
time
37/tcp
time
37/udp
rip
39/udp

ttytst source
fspd
SSH (Secure Shell)
SSH (Secure Shell)

mail
timeserver
timeserver
resource

nameserver 42/tcp name


whois
43/tcp nicname
remailck 50/tcp
remailck

50/udp

domain
domain
mtp
bootps
bootps
bootpc
bootpc
tftp
gopher
gopher
rje
finger
www

53/tcp
53/udp
57/tcp
67/tcp
67/udp
68/tcp
68/udp
69/udp
70/tcp
70/udp
77/tcp
79/tcp
80/tp

www

80/udp

nameserver
nameserver

RLP (Resource
Location Protocol)
IEN 116
RMCP (Remote Mail
Checking Protocol)
RMCP (Remote Mail
Checking Protocol)
(DNS)



Gopher

netrjs
http

link
87/tcp ttylink
kerberos
88/top kerberos5 krb5
kerberos
88/udp kerberos5 krb5
supdup
95/tcp
linuxconf 98/tcp
100

Transfer

Transfer

HTTP (HyperText
Protocol)
HTTP (HyperText
Protocol)

Kerberos v5
Kerberos v5

HTTP 1.1
. . HTTP 1.1
[RFC2616, RFC2817].

366

V.

www.books-shop.com

.. HTTP


100 Continue
101 Switching Protocols
200 OK
201 Created
202 Accepted
203 NonAuthoritative Information
204 No content
205 Reset Content
206 Partial Content
300 Multiple Choices
301 Moved Permanently
302 Moved Temporarily
303 See Other
304 Not Modified
305 Use Proxy
400 Bad Request
401 Unauthorized
402 Payment Required
403 Forbidden
404 Not Found
405 Method Not Allowed
406 Not Acceptable
407 Proxy Authentication Required
408 Request Timeout
409 Conflict
410 Gone
411 Length Required
412 Precondition Failed
413 Request Entity Too Large
414 RequestURI Too Long
415 Unsupported Media Type
500 Internal Server Error
50% Not Implemented
502 Bad Gateway
503 Service Unavailable
504 Gateway Timeout
505 HTTP Version Not Supported

367

www.books-shop.com

(
get/setsockopt())
. .4.7 .

UNIX . ,

IP_TTL Linux int, . AIX


char. ( "*"

Linux, "" ,
"3" .)
.4.

SOL_SOCKET
SOL_SOCKET
SOL_SOCKET

SO_ATTACH_FILTER
?
SO_BINDTODEVICE
?
SO_ BROADCAST


SO_BSDCOMPAT


BSD
SO_DEBUG

SO_DETACH_FILTER
?
SO_DONTROUTE

SO_ERROR

SO_KEEPALIVE


SO_LINGER


SO_NO_CHECK

SO_OOBINLINE


SO_PASSCRED

SO_PEERCRED



SO_PRIORITY


SO_RCVBUF

SO_RCVLOWAT

SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET

SOL_SOCKET
SOL_SOCKET
SOL_SOCKET
SOL_SOCKET

368

?
?

?
?

int
char*
int

int

int
int
int
int
int

struct
linger

int
int

int

struct
ucred

int

int
int

V.

www.books-shop.com

SOL_SOCKET

SO_RCVTIMEO

SOL_SOCKET

SO_REUSEADDR

SOL_SOCKET

SO_REUSEPORT

 


( 
)


 

SOL_SOCKET

SO_SECURITY
AUTHENTICATION

SOL_SOCKET

SO_SECURITY_ENC
RYPTION_NETWORK

SOL_SOCKET

SO_SECURITY

ENC

RYPTIONJTRANSPORT
SOL_SOCKET

SO SNDBUF

SOL_SOCKET

SO_SNDLOWAT

SOL_SOCKET

SO_SNDTIMEO

SOL_S0CKET

SO_TYPE

..4
3
struct

timeval
int

int

int

int

int

int

struct
timeval

int

struct
Ipv4 ip_mreq
struct
Ipv4 ip_mreq

int

Ipv4 struct
in_addr

int

int

int[]

int

.5. IP

SOL_IP
SOL_IP
SOL_IP
SOL_IP
SOL_IP
SOL_IP
SOL_IP
SOL_IP

IP_ADD_MEMBER

SHIP
IP_DROP_MEMBER

SHIP
IP_HDRINCL

IP

IP_MTU_DISCOVER

IP_MULTICAST_IF


IP_MULTICAST_

LOOP

IP_MULTICAST_TTL TTL


IP_OPTIONS
IP

int

369

www.books-shop.com

. .5

SOL_IP

IP_PKTINFO

SOL_IP

IP_PKTOPTIONS

SOL_IP

IP_RECVERR

SOL_IP

IP_RECVOPTS

SOL_IP

IP_RECVTOS

SOL_IP

IP RECVTTL

SOL_IP

IP_RETOPTS

SOL_IP

IP_ROUTER_ALERT






TTL



TTL

SOL_IP

IPJTOS

SOL_IP

IP_TTL

int

int[]

int

int

int

int

int

int

3
?

int

int

.6. IPv6

SOL_IPV6

IPV6 ADD MEMBER


SHIP

SOL_IPV6

IPV6_ADDFORM

int

?
?

IPV6_AUT8HDR

SOL_IPV6

IPV6_CHECKSUM

int

SOL_IPV6

IPV6 DROP
MEMBERSHIP

SOL_IPV6

struct
IPv6 ipv6_mreq

SOL_IPV6

IPV6_DSTOPTS

int

SOL_IPV6

IPV6_HOPLIMIT

int

SOL_IPV6

IPV6_HOPOPTS

int

370






struct
IPv6 ipv6 mreq
int

V.

www.books-shop.com

. .6
3

SOL_IPV6

IPV6_MULTICAST_H
OPS

int

SOL_IPV6

IPV6_MULTICAST_I
F

int

SOL_IPV6

IPV6_MULTICAST_ L
OOP

int

SOL_IPV6

IPV6_NEXTHOP

int

SOL_IPV6

IPV6_PKTINFO

int

SOL_IPV6

IPV6_PKTOPTIONS
IPV6_ ROUTER_ALER

?
?

?
?

int[]

SOL_IPV6

SOL_IPV6

IPV6_RXSRCRT

int

SOL_IPV6

IPV6_UNICAST_HOP
S

 ?

?


 ?

 ?

?

?

?


 ?

 ?

int

int

.7. 
*

SOL_TCP

TCP_KEEPALIVE

SOL_TCP

TCP_MAXRT

SOL_TCP

TCP_MAXSEG

SOL_TCP

TCP_NODELAY

SOL_TCP

TCP_STDURG

SOL_TCP

TCP_CORK

SOL_TCP

TCP_KEEPIDLE

SOL_TCP

TCP_KEEPINTVL


(
sysctl())

( 
)



(
sysctl())







int

int

int

int

int

int

int

int

371

%RRNVVKRS

piracy@books-shop.com

. . 7

SOL_TCP

TCP_KEEPCNT

int

SOL_TCP

TCP_SYNCNT

int

SOL_TCP

TCP_LINGER2

int

SOL_TCP

TCP_DEFER_ACCEPT

int

SOL_TCP

TCP_WINDOW_CLAMP






FINWAIT2

, 

int


. .8 .
,
BSD, Linux, System V.
.8. Linux

SIGHUP

SIGINT

2
3
4
5
6

8
9

11
13

SIGQUIT
SIGILL
SIGTRAP
SIGABRT
SIGFPE
SIGKILL
SIGSEGV
SIGPIPE

,


, abort ( )
,
kill
: , 

SIGALRM

14

, alarm( )

SIGTERM

15

, kill

SIGUSR1

30, 10, 16

SIGUSR2

31, 12, 17

SIGCHLD

20, 17, 18

SIGCONT

19, 18,25

372

,
,

V.

www.books-shop.com

. . 8

SIGSTOP
SIGTSTP
SIGTTIN
SIGTTOU
SIGIOT

17, 19, 23
18, 20, 24
21,21,26
22, 22, 27
6

SIGEMT
7,, 7
SIGBUS
10,7,10
SIGSYS
12,, 12
SIGSTKFLT , 16, 
SIGURG
16, 23, 21
SIGIO
23, 29, 22
SIGPOLL
SIGCLD
,,8
SIGXCPU
24, 24, 30
SIGXFSZ
25, 25, 31
SIGVTALRM 26, 26, 28
SIGPROF
27, 27, 29
SIGPWR
29, 30, 19
SIGINFO
29, , 
SIGLOST
SIGWINCH 28, 28, 20
SIGUNUSED ,31,

,


SIGABRT

(SVID)

(4.2 BSD)
 (4.2 BSD)
SIGIO (System V)
SIGCHLD
(4.2 BSD)
(4.2 BSD)
(4.2 BSD)

(System V)
SIGPWR

(4.3 BSD, Sun)

.
.

.
.
.

POSIX.1.

373

www.books-shop.com

ICMP
. .9 ICMP [RFC792] ,
.
.9. ICMP

0
1
2

4
5

8
9
10
11

3
4
5
6
7
8
9
10
11
12
13
14
15
0
0
1
2
3
0
0
0
0
1

12

374


, DF



( )















TTL
TTL

V.

www.books-shop.com

. ,9

IP






1
13
14
15
16
17
18

0
0
0
0
0
0

IPv4
. [RFC2365]

.
. 10.

TTL

224.0.0.0224.0.0.255

224.0.1.0238.255.25.255

<= 255

239.0.0.0239.191.255.255

( )

239.192.0.0239.195.255.255

239.196.0.0239.254.255.255

( )

239.255.0.0239.255.255.255

<128
<32


IPv6
. .11 IPv6
.
.11. IPV6

()
( )
NSAP
IPX

0000
0000
0000
0000

0000
0001
001
010

375

www.books-shop.com

. . 11

( )
( )
( )

( )
( )
( )
( )
( )
( )
( )
( )
( )
( )


0000 01 1
0000 1
0001
001
010
01 1
100
101
110
1110
11110
1111 10
1111 110
1111 11100
11111110 10
1111 111011
1111 1111

ICMPv6
. . 12 ICMP IPv6.
. 12. ICMPv6

2
3

0
1
2
3
4
0
0
1

4
0

376



( )
( )







V.

www.books-shop.com

. . 12

128

1
2
0



 (ping)

 (ping)

0
0
0
0
0
0
0
0

129
130
131
132
133
134
135
136
137


IPv6
. . 13

IPv6.

. 13. IPv6

( )

34

14

( )

( )

()

15

()

5
67

8
913


( 127.0.0.1 )
, 
; 




( )

377
www.books-shop.com

IPv6
. .14
IPv6.
.14. IPv6

:
0 ;
1
()
()
()

1
2
3

378

V.
www.books-shop.com

...

394

400

409

410

415

419

www.books-shop.com


Socket API ,
.

socket()
socket () , ,
.

,
.

#include <resolv.h>
#include <sys/socket.h>
#include <sys/types.h>
int socket(int domain, int type, int protocol);

, .
errno.

domain
type
protocol

() (. ,
" ")
(. ,
" ")
0 (. ,
" ")


EPROTONOSUPPORT
ENFILE
EMFILE
EACCES ENOBUFS
ENOMEM
EINVAL

380


,


; , 

,

.
www.books-shop.com


/***
***/
int sd;
sd = socket(PF_INET, SOCK_STREAM, 0);
/*** ICMP
***/
int sd;
sd = socket(PF_INET, SOCK_RAW, htons(IPPROTO_ICMP));

bind()
bind() .

,
,
.

#include <sys/socket.h>
#include <resolv.h>
int bind(int sockfd, struct sockaddr *addr, int addrlen);

0. ,
errno.

sockfd

addr

addrlen

addr


EBADF

EINVAL

EACCES

root

ENOTSOCK

/*** ft 9999 IP ***/


struct sockfd;
struct sockaddr_in addr;
sockfd = socket(PF_INET, SOCK_STREAM, 0);

381

%RRNVVKRS

piracy@books-shop.com

bzero(Saddr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(9999);
/* */
/* */
addr.sin_addr.s_addr = INADDR_ANY;
/* , : */
/* inet_aton("128.l.l.l", &addr.sin_addr); */
if ( bind(sockfd, saddr, sizeof(addr)) != 0 )
perror("bind");
listen()
listen()

. SOCK_STREAM.
.

#include <sys/socket.h>
#include <resolv.h>
int listen(int sockfd, int queue_len);

0. ,
errno.

sockfd
queue_len

SOCK_STREAM,


EBADF
ENOTSOCK
EOPNOTSUPP


,
listen();
, ,
SOCK_STREAM

/*** ; ***/,
/***  10 ***/
int sockfd;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
/* bind() */

listen(sockfd, 10); /* 10 */


382

V.

www.books-shop.com

acceptQ
accept() .

, (
sockfd),

. SOCK_STREAM.

#include <sys/socket.h>
#include <resolv.h>
int accept(int sockfd, struct sockaddr *addr, int *addr_len);

, ,

errno.

sockfd
addr
addr_len

, 

,
, ; 


EBADF
ENOTSOCK
EOPNOTSUPP
EFAULT
EAGAIN
EPERM
ENOBUFS, ENOMEM


,
SOCK_STREAM
addr
,

/*** , ***/
/*** ***/

int sockfd = socket(PF_INET, SOCK_STREAM, 0 ) ;


/*
/*

bind() */

listen()
for

*/

(;;)

383

www.books-shop.com

int client;

client = accept(sockfd, 0, 0) ;
/*

*/
close (client);
/*** , ***/
/*** ***/
int sockfd = socket(PF_INET, SOCK_STREAM, 0);
/*

bind()

*/
/*


listen()

*/
for (;;)
{ struct sockaddr_in addr;
int client, addr_len = addr;
clientsd = accept(sockfd, &addr, &addr_len);
printf ("Connected: %s:%d\n", inet_ntoa (addr.sin_addr) ,
ntohs(addr.sin_port) );
/*

*/
close (client) ;

connect()
connect() .

SOCK_DGRAM SOCK_STREAM.

( UDP) ,

.
send() recv(). ( TCP)

#include <sys/socket.h>
#include <resolv.h>
int connect(int sockfd, struct sockaddr *addr, int addr_len);


0. ,
errno.

sockfd

; 
bind() ( , 
)

addr
addr_len

,
addr

384

V.

www.books-shop.com


EBADF
EFAULT


;
addr

ENOTSOCK
EISCONN

,
; ,




ECONNREFUSED
ETIMEDOUT

ENETUNREACH
EADDRINUSE
EINPROGRESS

EALREADY
EAFNOSUPPORT
EACCES



,
. 
select() poll(),
getsockopt() 
so_ERROR ( SOL_SOCKET), 0,
,
,

sa_f amily

, 

/*** TCP ***/


int sockfd;
struct sockaddr_in addr;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = 13; /* */
inet_atoi("127.0.0.1", &addr.sin_addr);
if ( connect(sockfd, saddr, sizeof(addr)) != 0 )
perror("connect");
socketpair()
socketpair() ,
, UNIX
. pipe(),
Socket API.
socketpair() PF_UNIX PF_LOCAL.

bind().

385

www.books-shop.com


#include <sys/socket.h>
#include <resolv.h>
int socketpair(int domain, int type, int protocol,
int sockfds[2]);

0. ,
errno.

domain
type

protocol
sockfds [ 2 ]

PF_LOCAL PF_UNIX
SOCK_STREAM;
, UNIX 
, POSIX.1
0
,


EMFILE
EAFNOSUPPORT
EPROTONOSUPPORT

EOPNOSUPPORT
EFAULT


sockf ds

/*** ***/
int sockfd[2];
struct sockaddr_ux addr;
if ( socketpair(PF_LOCAL, SOCK_STREAM, 0, sockfd)
perror("socketpair") ;

!= 0 )

386

V.

www.books-shop.com

send()
send()

, . write(),

#include <sys/socket.h>
#include <resolv.h>
int send(int sockfd, void *buffer, int msg_len, int options);


write(), send()

. , msg_len.

. ,
, errno.

sockfd
buffer
msg_len
options

, SOCK_DGRAM SOCK_STREAM


, :
* MSG_OOB. ( );
* MSG_DONTROUTE , .. ;
, ;
* MSG_DONTWAIT. , ..
send(); , errno EAGAIN;
* MSG_N0SIGNAL He SIGPIPE , 


EBADF
ENOTSOCK
EFAULT
EMSGSIZE
EAGAIN
ENOBUFS
EINTR
NO


,
buffer
,
,
,

; , 


387

www.books-shop.com

EINVAL
EPIPE


;
SIGPIPE, MSG_NOSIGNAL

/*** (TCP, UDP) ***/


int sockfd;
int bytes, bytes_wrote = 0;
/*
, /
*/
while ( (bytes = send(sockfd, buffer, msg_len, 0)) > 0 )
if ( (bytes_wrote += bytes) >= msg_len )
break;
if ( bytes < 0 )
perror("send");

/*** (TCP) ***/


int sockfd;
int bytes, bytes_wrote = 0;
/*
,
*/
if ( send(sockfd, buffer, 1, MSG_OOB)) != 1 )
perror("Urgent message");

sendto()
sendto() ,
.

, / (Transaction TCP), ,
, Linux.

#include <sys/socket.h>
#include <resolv.h>
int sendto(int sockfd, void* msg, int len, int options,
struct sockaddr *addr, int addr_len);

1, .

sockfd
msg
len
options
addr
addr_len

388




( , send())

V.

www.books-shop.com


( , send())

/*** (TCP, UDP) ***/


int sockfd;
struct sockaddr_in addr;
if ( (sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0 )
perror("socket");
bzero(Saddr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(DEST_PORT);
inet_aton(DEST_ADDR, &addr.sin_addr);
if ( sendto(sockfd, buffer, msg_len, 0, &addr, sizeof(addr))
<0 )
perror("sendto");

sendmsg()
sendmsg() .
msg_name sockaddr,
, . NULL,
, .

#include <sys/socket.h>
#include <resolv.h>
#include <sys/uio.h>
int sendmsg(int sockfd, const struct msghdr *msg,
unsigned int options);

1,
( errno).

sockfd
msg


msghdr, , 
. :
struct iovec
{

void *iov_base;
/* */
_kernel_size_t iov_len; /* */
};

389
www.books-shop.com

struct msghdr
{
_ptr_t msg name; /* */
socklen_t msg_namelen; /* */
struct iovec *msg_iov; /* */
size_t msg_iovlen; /* */
_ ptr_t msg_control; /* */
size_t msg_controllen; /* */
int msg_flags; /* */

};
options

, , 

( , send())


( , send())

int i, sd, len, bytes;


char buffer[MSGS][100];
struct iovec ip[MSGS];
struct msghdr msg;
struct sockaddr_in addr;
sd = socket(PF_INET, SOCK_DGRAM, 0);
bzero(&addr, sizeof (addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
inet_aton (&addr.sin_addr,"127.0.0.1");
bzero(&msg, sizeof (msg));
msg.msg_name = &addr;
msg.msg_namelen = sizeof (addr);
for ( i = 0; i < MSGS; i++ )
{
io[i].iov_base = buffer[i];
sprintf(buffer[i], "Buffer #%d: this is a test\n", i);
io[i].iov_len = strlen(buffer[i]);

msg.msg_iov = io;
msg.msg_iovlen = MSGS;
if ( (bytes = sendmsg(sd, &msg, 0)) < 0 )
perror("sendmsg");

sendfile()
sendfile() .
in_f d

out_fd.

390

V.

www.books-shop.com

,
.

( count) ( offset).

*offset ,

#include <unistd.h>
int sendfile(int out_fd, int in_fd, off_t *offset, size_t count);


. 1, errno
.

out_f d
in_f d
offset
count

( )
( )
,


EBADF

EINVAL
ENOMEM

#include <unistd.h>

struct stat fdstat;


int client = accept(sd,0,0);
int fd = open("filename.gif", O_RDONLY);
fstat(fd, &fdstat);
sendfile(client, fd, 0, fdstat.st_size);
close(fd);
close(client);

recv()
recv()

, .
read(), .

391

%RRNVVKRS

piracy@books-shop.com


#include <sys/socket.h>
#include <resolv.h>
int recv(int sockfd, void *buf, int maxbuf, int options);



1 .

sockfd
buf
maxbuf
options


,

, :
* MSG_OOB. , 
. , 
;
* MSG_PEEK. , . ,
;
* MSG_WAITALL. , 
. , ,
;
* MSG_ERRQUEUE. .
, ( IP 
IP_RECVERR). sock_extended_error;
* MSG_NOSIGNAL. SIGPIPE


EBADF
ENOTCONN


(. connect() accept())

ENOTSOCK

EAGAIN

, , 
, ,

EINTR

EFAULT

EINVAL

/*** (TCP, UDP) ***/


int sockfd;
int bytes, bytes_wrote=0;

/* , / */
if ( (bytes = recv(sockfd, buffer, msg_len, 0)) < 0 )

392

V.

www.books-shop.com

perror("send");
/*** (TCP) ***/
/*** SIGURG ***/
int sockfd;
int bytes, bytes_wrote=0;
/* , */
if ( (bytes = recv(sockfd, buffer, msg_len, MSG_OOB)) < 0 )
perror("Urgent message");

recvfrom()
recvfrom()
(UDP ). /
. accept().

linclude <sys/socket.h>
linclude <resolv.h>
int recvfromfint sockfd, void* buf, int buf_len, int options,
struct sockaddr *addr, int *addr_len);

.
1, errno .

sockfd

buf

buf _l

( , )

options

( , recv())

addr

addr_len

( ,
);


( , recv())

struct sockaddr_in addr;


int addr_len=sizeof(addr), bytes_read;
char buf[l024];

393

www.books-shop.com

int sockfd = socket (PF_INET, SOCK_DGRAM, 0);


/* */
bytes_read = recvfrom(sockfd, buf, sizeof(buf), 0, &addr,
&addr_len);
if ( bytes_read < 0 )
perror("recvfrom failed");

recvmsg()
recvmsg()

. SOCK_DGRAM ( ,
sendmsg()).

#include <sys/socket.h>
#include <resolv.h>
#include <sys/uio.h>
int recvmsg(int sockfd, struct msghdr *msg, unsigned int options);

,
1.

sockfd
msg
options



( , recv( ))


( , recv())

char buffer[MSGS][1000];
struct sockaddr_in addr;
struct iovec io[MSGS];
struct msghdr msg;
bzero(&addr, sizeof(addr));
msg.msg_name = &addr;
msg.msg_namelen = sizeof (addr);
for ( i = 0; i < MSGS; i++ )
{
io[i].iov_base = buffer(i);
io[i].iov_len = sizeof (buffer[i]);

394

V.

www.books-shop.com

msg.msg_iov = io;
msg.msg_iovlen = MSGS;
if ( (bytes = recvmsg(sd, &msg, 0)) < 0 )
perror("recvmsg");

. ,

.
shutdown()
shutdown() .

, ,

.
, shutdown()
.

#include <sys/socket.h>
int shutdown(int sockfd, int how);

, 0.
rrno.

sockfd

how

, , :
* SHUT_RD (0) ;
* SHUT _WR(1) ;
* SHUT_RDWR (2) ( close()).


EBADF
ENOTSOCK
ENOTCONN

395

www.books-shop.com


int sockfd;
struct sockaddr_in addr;
sockfd = socket(PF_INET, SOCK_STREAM, 0);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(DEST_PORT);
inet_aton (DEST_ADDR, &addr. sin_addr);
connect(sockfd, &addr, sizeof(addr));
if ( shutdown(sockfd, SHUT_WR) != 0 )
PANIC("Can't make socket inputonly");

, .. Socket API
, .
, .
htons(), htonl()
htons() htonl()

.
,
.

#include <netinet/in.h>
unsigned short int htons(unsigned short int host_short);
unsigned long int htonl(unsigned long int host_long);


(16
32
).

host_short
host_long

16
32


()

396

V.

www.books-shop.com


/*** 1023 ***/
struct sockaddr_in addr;
addr.sin_port = htons(1023);
/*** 128.1.32.10 ***/
struct sockaddr_in addr;
addr.sin_addr.s_addr = htonl(Ox8001200A);
ntohs(), ntohl()
ntohs() ntohl()
.

#include <netinet/in.h>
unsigned short int ntohs(unsigned short int network_short);
unsigned long int ntohl(unsigned long int network_long);

(16
32
).

network_short
network_long

16
32


()

struct sockaddr_in addr;


int client, addrlen=sizeof(addr);
client = accept(sockfd, &addr, &addrlen);
if ( client > 0 )
printf("Connected %lX:%d\n", ntohl(addr.sin_addr),
ntohs(addr.sin_port));
inet_addr()
inet_addr() . IP

.
1,
IP
(255.255.255.255). inet_aton().

397

www.books-shop.com


#include <netinet/in.h>
unsigned long int inet_addr(const char *ip_address);

He
INADDR_NONE (1)

, IP
. ( . 
, 255.255.255.255 
.)

ip_address

IP , (, 128.187.34.2)


( errno )

if ( (addr.sin_addr.s_addr = inet_addr("182.187.34.2")) ==
1 )
perror("Couldn't convert address");

inet_aton()
inet_aton() IP

.
inet_addr().

#include <netinet/in.h>
int inet_aton(const char *ip_addr, struct in_addr *addr);

, .
.

ip_addr
addr

398

ASCII IP (, 187.34.2.1)


, ; sin_addr
sockaddr_in

V.

www.books-shop.com


( errno )

struct sockaddr_in addr;


if ( inet_aton("187.43.32.1", &addr.sin_addr) == 0
perror("inet_aton() failed");

inet_ntoa()
inet_ntoa() IP

iinclude <netinet/in.h>
int inet_ntoa(struct in_addr *addr);

.

addr

( sockaddr_in)


( errno )

clientfd = accept(serverfd, &addr, &addr_size);


if ( clientfd > 0 )
printf("Connected %s:%d\n", inet_ntoa(addr.sin_addr),
ntohs(addr.sin_port));

inet_pton()
inet_pton() IPv4 IPv6

Iinclude <arpa/inet.h>
int inet_pton(int domain, const char* prsnt, void* addr);

399

www.books-shop.com

, .

domain
prsnt
addr

(AF_INET AF_INET6)
ASCII
IP
(, 187.34.2.1 FFFF:8090::3245)
, ; sin_addr
sockaddr_in sin6_addr sockaddr_in6


( errno )

struct sockaddr_in addr;


if ( inet_pton(AF_INET, "187.43.32.1", &addr.sin_addr) == 0 )
perror("inet pton() failed");

inet_ntop()
inet_pton()
.

AF_INET AF_INET6.

#include <arpa/inet.h>
int inet_ntop(int domain, struct in_addr *addr, char* str,

int len);


str.

domain
addr
str
len

400

(AF_INET AF_INET6)
( sockaddr in)

V.

www.books-shop.com


( errno )

char str[100];
clientfd = accept(serverfd, &addr, &addr_size);
if ( clientfd > 0 )
printf("Connected %s:%d\n",
inet_ntop(AF_INET, addr.sin_addr, str, sizeof(str)),
ntohs(addr.sin_port));


Socket API ,

.
getpeername()
getpeername() ,
sockfd.
addr. addr_len .
, accept().

#include <sys/socket.h>
int getpeername(int sockfd, struct sockaddr *addr,
socklen_t *addr_len);

. ,
errno.

sockfd

addr

addr_len

; ,


EBADF

401

%RRNVVKRS

piracy@books-shop.com

ENOTSOCK
NONN
ENOBUFS
EFAULT

,


addr

struct sockaddr_in addr;


int addr_len = sizeof(addr);
if { getpeername(client, &addr, &addr_len) != 0 )
perror("getpeername() failed");
printf("Peer: %s:%d\n", inet_ntoa(addr.sin_addr),
ntohs(addr.sin_port));

gethostname()
gethostname() .
name, len.

#include <unistd.h>
int gethostname(char *name, size_t len);

. ,
errno.

name
len


EINVAL
EFAULT

len ,
Linux/i386, len ,
name

char name[50];
if ( gethostname(name, sizeof(name)) != 0
perror("gethostname() failed");
printf("My host is: %s\n", name);

402

V.

www.books-shop.com

gethostbyname()
gethostbyname() DNS

IP
. , .
;
h name h addr list[0] hostent.

#include <netdb.h>
struct hostent *gethostbyname(const char *name);

hostent.

NULL. ,
. h_addr
.
#define h_addr h_addr_list[0]
struct hostent {
char *h_name;
/* */
char **h_aliases; /* */
int h_addrtype; /* */
int h_length;
/* */
char **h_addr_list; /* ;
*/

};

name

IP


ENOTFOUND
NO_ADDRESS, NO_DATA
NO_RECOVERY
EAGAIN


, IP

,

int i;
struct hostent *host;
host = gethostbyname("sunsite.unc.edu");
if ( host != NULL )
{
printf("Official name: %s\n", host>h_name);
for ( i = 0; host>h_aliases[i] != 0; i++)
printf("
alias[%d]: %s\n", i+1, host>h_aliases[i]);

403

www.books-shop.com

printf("Address type=%d\n", host>h_addrtype);


for ( i = 0; i < host>h_length; i++)
printf("Addr[%d]: %s\n", i+1,
inet_ntoa(host>h_addr_list[i]));
}
else
perror("sunsite.unc.edu");

getprotobyname()
getprotobyname() /etc/protocols

.
, HTTP, FTP Telnet,

#include <netdb.h>
struct protoent *getprotobyname(const char* pname);



protoent. NULL.

struct protoent {
char
*p_name;
/* */
char
**p_aliases; /* */
int
p_proto;
/* */
};

pname


( errno )

#include <netdb.h>
int i;
struct protoent *proto = getprotobyname("http");
if ( proto != NULL )
{
printf("Official name: %s\n", proto>name);
printf("Port!: %d\n", proto>p proto);
for ( i = 0; proto>p aliases[I] != 0;

404

V.

www.books-shop.com

printf("Alias[%d]: %s\n", i+1, proto>p_aliases[i]);


else
perror("http");


, .

.
setsockopt()
setsockopt() .
( ).

, " ".

#include <sys/types.h>
#include <sys/socket.h>
int setsockopt(int sd, int level, int optname,
const void *optval, socklen_t optlen);

. ,
errno.

sd
level
optname
optval
optlen


(SOL_SOCKET, SOL_IP, SOL_IPV6, SOL_TCP)



EBADF
ENOTSOCK
ENOPROTOOPT
EFAULT


,

optval

const int TTL=128;


/* 128 */
.

405

www.books-shop.com

if ( setsockopt(sd, SOL_IP, SO_TTL, &TTL, sizeof(TTL)) != 0 )


perror("setsockopt() failed");

getsockopt()
getsockopt() .

#include <sys/types.h>
iinclude <sys/socket.h>
int getsockopt(int sd, int level, int optname, void *optval,
socklen_t *optlen);


. ,
errno.

sd
level
optname
optval
optlen


(SOL_SOCKET, SOL_IP, SOL_IPV6, SOL_TCP)


; ,


EBADF
ENOTSOCK
ENOPROTOOPT
EFAULT


,

optval optlen

int error, size = sizeof(error);


if ( getsockopt(sd, SOL_SOCKET, SO_ERROR, &error, &size)) != 0 )
perror("getsockopt() failed");
printf("socket error=%d\n", error);

406

V.

www.books-shop.com

API

...

408
415
418
421
424

www.books-shop.com

, .

. Pthreads,
,
. , .
fork()
fork() ( ).

, .

#include <unistd.h>
pid_t fork(void);

0
>0

<0
; errno

()

EAGAIN



ENOMEM

int PID;
if ( (PID = fork()) == 0 )
{
/* */
/*** ***/
exit(status);

}
else if ( PID > 0 )
{
/* */

408

V.

www.books-shop.com

int status;
/*** ***/
wait(Sstatus); /*
SIGCHLD */

}
else /* */
perror("fork() failed");

_clone()
,

. ,

.
,

iinclude <sched.h>
int _clone(int (*fn)(void* arg), void* stacktop,
int flags, void* arg);


.
errno.

fn
stacktop
flags

, void*; 
,
( );


, ,
.
, 
.
,
:
* CLONE_VM. . ,
, 
, .
;
* CLONE_FS. : 
, ( umask).
, ;
* CLONE FILES. . 
, ,
, .

. API

409

www.books-shop.com

arg

, ;
* CLONE SIGHAND. . 
sigprocmask( ) , 
. , 
;
* CLONE_PID. .
, ( 
Pthreads). ,

, f .


EAGAIN
ENOMEM

fdefine STACKSIZE

1024

void Child(void *arg)

/* */
exit(O);

int main (void)


{ int cchild;
char *stack = malloc( STACKSIZE);
if ( (cchild = _clone(&Child, stack+STACKSIZE1,
SIGCHLD, 0)) == 0 )
{ /*** ***/

else if ( cchild > 0 )


wait();
else
perror("Can't clone task");

exec()
(
, ,
#! <> []).

,
.

410

V.

www.books-shop.com

execl(), execlp(), execle(), execv() execvp(),


execve().

#include <unistd.h>
int execve(const char* path, char* const argv[],
char* const envp[]);
int execl(const char* path, const char* argv, ...);
int execlp(const char* file, const char* argv, ...);
int execle(const char* path, const char* argv, ...,
char* const envp[]);
int execv(const char* path, char* const argv[]);
int execvp(const char* file, char* const argv[]);

. , 1.

file

; , ,
PATH

path

argv

;
, NULL (0)

arg

; 
(...). ; ,
NULL (0)

envp

;
<>=<> (, TERM=vt100);
NULL (0)


EACCES

,


EPERM

SUID SGID, 
nosuid

E2BIG

ENOEXEC

, 


EFAULT

ENAMETOOLONG

ENOENT

. API

411

%RRNVVKRS

piracy@books-shop.com

ENOMEM
ENOTDIR
ELOOP
ETXTBUSY

ENFILE
EMFILE
EINVAL
EISDIR
ELIBBAD


, 






PT_INTERP

execl("/bin/ls", "/bin/ls", "al", "/home", "/boot", 0);


perror("execl() failed"); /* IF :
*/
char *args[] = {"ls", "al", "/home", "/boot", 0};
execvp(args[0], args);
perror("execvp() failed");

sched_yield()
sched_yield() .
,

.
,

#include <sched.h>
int sched_yield(void);

0,

1.

()

( )
412

V.

www.books-shop.com


#include <sched.h>
sched_yield();
wait(), waitpid()
wait() waitpid()
. ,

. wait()

. waitpid()
. , ,
.
WIFEXITED(cayc) ,

.
WEXITSTATUS()

, exit()

return. ,
WIFEXITED .
WIFSIGNALED() true,


.
WTERMSIG(cayc) ,
. ,
WIFSIGNALED .
WIFSTOPPED() true,

. ,

options, WUNTRACED.
WSTOPSIG() ,

. ,
WIFSTOPPED .

linclude <sys/types.h>
linclude <sys/wait.h>
PID_t wait(int *status);
PID_t waitpid(PID_t pid, int *status, int options);

. API

413

www.books-shop.com


PID

, :
* < 1 , 
;
* == 1 ( 
wait());
*

== 0 , 
;
* > 0 ,
; 0 NULL,
, exit()

status
options

WNOHANG. , ,
;
* WUNTRACED. , ,
,


ECHILD


( , SIGCHLD 
SIG_IGN)

EINVAL

options

EINTR

WNOHANG , SIGCHLD;

void sig_child(int signum) /*


*/
{ int status;
wait(&status);
if ( WIFEXITED(status) )
printf("Child exited with the value of %d\n",
WEXITSTATUS(status));
if ( WIFSIGNALED(status) )
printf("Child aborted due to signal l%d\n",
WTERMSIG(status));
if ( WIFSTOPPED(status) )
printf("Child stopped on signal #%d\n" WSTOPSIG(status));

void sig_child(int signum) /*


*/
while ( waitpid(l, , WNOHANG) > 0 );

}
414

V.

www.books-shop.com


Pthreads.
pthread_create()
pthread_create()
. ,
start_fn ( arg).
void*, ,
, NULL.

#include <pthread.h>
int pthread_create(pthread_t *tchild, pthread_attr_t *attr,
void* (*start_fn)(void *), void *arg);

.

,

, errno.

tchild
attr
start_f n
arg

( ); 

,

, ; 
void*
, ;
, 
( )


EAGAIN

( 
PTHREAD_THREADS_MAX)

void* child (void *arg)


{
/* */
pthread_exit(arg); /* */

. API

415

www.books-shop.com

int main(void)
{ pthread_t tchild;
if ( pthread_create(&tchild, 0, child, 0) < 0 )
perror("Can't create thread!");
/* */
if ( pthread_join(tchild, 0) != 0 )
perror("Join failed");

pthread_join()
pthread_join() wait(),
.

#include <pthread.h>
int pthread_join(pthread_t tchild, void **retval);

.

, ,
errno.

tchild
retval

,
( )


ESRCH
EINVAL
EDEADLK

,

tchild

(. pthread_create())
pthread_exit()
pthread_exit() ,
retval.
return.

416

V.

www.books-shop.com


#include <pthread.h>
void pthread exit(void *retval);

()

retval

, ; ,


()

(. pthread created)
pthread_detach()
pthread_detach()

. .

#include <pthread.h>
int pthread_detach(pthread_t tchild);

.

, ,
errno.

tchild


ESRCH
EINVAL
EDEADLK

,

tchild

. API

417

www.books-shop.com


void* child(void *arg)
/* */
pthread exit(arg); /* */
int main(void)
{ pthread_t tchild;

if ( pthread_create(&tchild, 0, child, 0) < 0 )


perror("Can't create thread!");
else
pthread_detach(tchild);
/* */

.
,

. ,

.
pthread_mutex_init(), pthread_mutex_destroy()
pthread_mutex_init() pthread_rautex_destroy()
.

, .
pthread_mutex_destroy() ,
, , Linux ,
, .

#include <pthread.h>
/* */
pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t recmutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_mutex_t errchkmutex =
PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *mutexattr);
int pthread_mutex_destroy(pthread_mutex_t *mutex);

418

V.

www.books-shop.com

mutex

mutexattr

; NULL,
( PTHREAD_MUTEX_INITIALIZER)


()
pthread_mutex_lock(), pthread_mutex_trylock()
pthread_mutex_lock() pthread_mutex_trylock()

,
.

. ,

, .

#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);

,

. errno.

mutex


EINVAL

EDEADLK

( pthread_mutex_trylock()) 
( ,
)

EBUSY

( pthread_mutex_lock())

pthread mutex t mutex = fastmutex;

. API

419

www.books-shop.com

if ( pthread_mutex_lock(&mutex) == 0 )

{
/*** ***/
pthread_mutex_unlock(&mutex) ;
pthread_mutex_t mutex = fastmutex;
/* */
while ( pthread_mutex_trylock(&mutex) != && errno == EBUSY )
{

/*** ***/
}

/* ! */
if ( errno != ENOERROR)

/*** ***/
pthread_mutex_unlock(&mutex);

pthread_mutex_unlock()
pthread_mutex_unlock() .

#include <pthread.h>
int pthread_mutex_unlock(pthread_mutex_t *mutex);

,
.
errno.

mutex


EINVAL
EPERM


( 
, )

(. pthread_mutex_lock())

420

V.

www.books-shop.com


(
). ,

.
signal()
signal() sig_fn

signum. (


).

#include <signal.h>
void (*signal(int signum,
void (*sig_fn)(int signum)))(int signum);


typedef void (*TSigFn)(int signum);


TSigFn signal(int signum, TSigFn sig_fn);


, .

signum
sig_f n


,


( errno )

void sig_handler(int signum)

{
switch ( signum )

{
case SIGFPE:

if ( signal(SIGFPE, sig_handler) == 0 )
perrorf("signal() failed");

. API

421

%RRNVVKRS

piracy@books-shop.com

sigaction()
signal(), sigaction()

.
.

#include <signal.h>
int sigaction(int signum, const struct sigaction *sigact,
struct sigaction *oldsigact);

, .

signum

sigact

; sigaction
:
struct sigaction
{
void (*sa handler)(int);
sigset_t sa_mask;
int sa_flags;
void (*sa_restorer)(void);
};

sa_handler
sajnask
sa_flags

, 

, . :
* SA_NOCLDSTOP. SIGCHLD, ,
;
* SA_ONESHOT SA_RESETHAND.
;
* SA_RESTART.
EINTR;

* SA_NOMASK SA_NODEFER. 

sa_restorer
oldsigact

422

V.

www.books-shop.com


EINVAL

EFAULT
EINTR

; ,
SIGKILL SIGSTOP, 

sigact oldsigact ,

void sig_handler(int signum)


switch ( signum )
case SIGCHLD:

struct sigaction sigact;


bzero(&sigact, sizeof(sigact));
sigact.sa_handler = sig_handler; /* */
sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART; /* */
if ( sigaction(SIGCHLD, &sigact, 0) == 0 )
perror("sigaction() failed");

sigprocmask()
sigprocmask() ,

#tinclude <signal.h>
int sigprocmask(int how, const sigset_t *sigset,
sigset_t *oldsigset);

,
.

how

, sigset:
* SIG_BLOCK. 
, sigset;
* SIG_UNBLOCK. , sigset, 

. API

423

www.books-shop.com

sigset
oldsigset

, ,
;
* SIG_SETMASK. ,
sigset

NULL,


EFAULT
EINTR

sigset oldsigset , 


,
.
bzero(), memset()
bzero() .

, memset(),

linclude <string.h>
void bzero(void *mem, int bytes);
void* memset(void *mem, int val, size_t bytes);


bzero() . memset()

mem
val
bytes



( )


()

424

V.

www.books-shop.com


bzero(&addr, sizeof(addr));
memset(&addr, 0, sizeof(addr));
fcntl()
f c n t l ( ) .

linclude <unistd.h>
linclude <fcntl.h>
int fcntl(int fd, int cmd);
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *flock);

1 errno.
.
F_DUPFD
F_GETFD
F_GETFL
F_GETOWN
F_GETSIG





, , ,
SIGIO
.

fd
cmd


. ,
(arg flock).
:
* (F_DUPFD). , dup2 (arg, fd). 
f d arg;
* () (F_GETFD, F_SETFD). 
,
().
;
* (F_GETFL, F_SETFL).
, (),
0_APPEND, O_NONBLOCK 0_ASYNC;
* (F_GETLK, F_SETLK, F_SELKW).
F_GETLK , .

. API

425
www.books-shop.com

arg

flock

:
* & (F_GETOWN, F SETOWN).
 SIGIO;
* (F GETSIG, F SETSIG). 
, 
. SIGIO


EACCES

 ,

EAGAIN
EBADF

 ,
f d

EDEADLK

, F_SETLKW

EFAULT

flock

EINTR

F_SETLKW, . 
F_GETLK F_SETLK, ,
. 
( NFS)
F_DUPFD arg
. F_SETSIG arg 

F_DUPFD ,

APPEND , "
"

EINVAL

EMFILE
ENOLCK
EPERM

#include <unistd.h>
linclude <fcntl.h>
printf("PID which owns SIGIO: Id", fcntl(fd, F_GETOWN));
if ( fcntl(fd, F_SETSIG, SIGKILL) != 0 )
perror("Can't set signal");
if ( (fd_copy = fcntl(fd, F_DUPFD)) < 0 )
perror("Can't dup fd");

426

V.

www.books-shop.com

pipe()
pipe() , :

(fd[0]) (fd[l]).
.

#include <unistd.h>
int pipe(int fd[2]);

0,
1.

fd


EMFILE
ENFILE
EFAULT



f d

int f d [ 2 ] ;
pipe(fd); /* */

poll()
poll(), select(),

.

, .

#include <sys/poll.h>
int poll(struct pollfd *ufds, unsigned int nfds, int timeout);

, , .

, .

, .

. API

427

www.books-shop.com


ufds

pollfd. :
struct pollfd

int fd;
/* */
short events; /* */
short revents; /* ,
*/

};
f d . events revents 
.
:
* POLLIN ;
* POLLPRI () ;
* POLLOUT ;
* POLLERR ;
* POLLHUP ;
* POLLNVAL , f d ;
* POLLRDNORM ( Linux);
* POLLRDBAND ( Linux);
* POLLWRNORM ( Linux);
* POLLWRBAND ( Linux)
,
; ,

nfds
timeout


ENOMEM
EFAULT
EINTR


, 

,

int fd_count=0;
struct pollfd fds[MAXFDs];
fds[fd_count].fd = socket(PF_INET, SOCK_STREAM, 0);
/*** bind() listen)) ***/
fds[fd_count++].events = POLLIN;

for (;;)
{
if ( poll(fds, fd_count, TIMEOUT_MS) > 0 )

int i;
if ( (fds[0].revents & POLLIN) != 0 )

428

V.

www.books-shop.com

fds[fd_count].events = POLLIN | POLLHUP;


fds[fd_count++].fd = accept(fds[0].fd, 0, 0);

}
for ( i = 1; i < fd_count; i++ )

if ( (fds[i].revents & POLLHUP) != 0 )

{
close(fds[i].fd);
/***
***/
fd_count;

else if ( (fds[i].revents & POLLIN) != 0 )


/*** ***/

read()
read() fd
. ,
, , recv().

#include <unistd.h>
int read(int fd, char *buffer, size_t buf_len);

.

fd
buffer
buf_len


,
,


EINTR
EAGAIN

EISDIR

,
 ( NONBLOCK),

; ,
SIGTTIN ;

. API

429

www.books-shop.com

EBADF

EINVAL

EFAULT

buffer , 

int sockfd;
int bytes_read;
char buffer[1024];
/* */
if ( (bytes_read = read(sockfd, buffer, sizeof(buffer))) < 0 )
perror("read");

select()
select()

. ,

. ,

.
FD_CLR .
FD_SET .
FD_ISSET

.
FD ZERO .

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int select(int hi_fd, fd_set *readfds, fd_set *writefds,
fd_set *exceptfds, struct timeval *timeout);
FD_CLR(int fd, fd_set *set);
FD_ISSET(int fd, fd_set *set);
FD_SET(int fd, fd_set *set);
FD_ZERO(fd_set *set);


,
. .
, .

430

V.

www.books-shop.com


hi_f d
readfds
writefds
exceptfds
timeout

,
,
,
,
, ; 
; ( ) ,
,
NULL (0), ( )
, ,

fd
set


EBADF
EINTR
EINVAL
ENOMEM

int i, ports[]={9001, 9002, 9004, 1};


int sockfd, max=0;
fd_set set;
struct sockaddr_in addr;
struct timeval timeout={2,500000}; /* 2,5 */
FD_ZERO(&set);
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
for ( i = 0; ports[i] > 0; i
sockfd = socket(PF_INET, SOCK_STREAM, 0);
addr.sin_port = htons(ports[i] );
if ( bind (sockfd, &addr, sizeof(addr)) != 0 )
perror("bind() failed");
else

FD_SET(sockfd,&set);
if ( max < sockfd )
max = sockfd;

if ( select(max+l, &set, 0, &set, &timeout) > 0 )

for ( i = 0; i <= max; i++)


. API

431

%RRNVVKRS

piracy@books-shop.com

if ( FD_ISSET(i, &set) )
{ int client = accept(i, 0, 0);
/*** ***/

write()
write()

fd. , ,
send().

#include <unistd.h>
int write(int fd, const void *buffer, size_t msg_len);

.

, msg_len.

, ,

, errno .

fd
buffer
msg_len


EBADF
EINVAL
EFAULT
EPIPE

EAGAIN
EINTR
ENOSPC

432


,
buffer
, 
; , , SIGPIPE,
, write() EPIPE
 ( 0_NONBLOCK),

,
, , 



V.

www.books-shop.com


/*** (TCP, UDP, ) ***/
int sockfd;
int bytes, bytes_wrote=0;
/* , */
while ((bytes = write(sockfd, buffer, msg_len)) > 0 )
if ((bytes_wrote += bytes) >= msg_len)
break;
if ( bytes < 0 )
perror("write");

close()
close() ( , ).
,

. Linux 2.2.14 getdtablesize() 1024,


/usr/include/linux/limits.h NR_OPEN.

#include <unistd.h>
int close(int f d ) ;

. ,
errno.

fd


EBADF

int sockfd;
sockfd = socket(PF_INET, SOCK_RAW, htons(99));
if ( sockfd < 0 )
PANIC("Raw socket create failed");
if ( close(sockfd) != 0 )
PANIC("Raw socket close failed");

. API

433

www.books-shop.com

.
C++
C++
C++
C++
Java
Java

Java
Java

449
450
451
452
456
457
458
464

www.books-shop.com

, Java API,

C++, 13,
" C++" ( Web
).
; ( ,
), (,

) (
, ).

++

,

.
Exception < RangeException
< FiteExceptton
FiteExceptton
< NetException <:
< NetCoriversionExceptton
< NetDNSException
NetDNSException
< NetlOException
< NetConnectException
< NetConfigException

. .1. C++

Exception ()
:
Exception(SimpleString s);
: .
:
const char* Getstring();

:
RangeException
FileException

NetException

, ; 
MessageGroup
, ;
Socket
()

:
NetException(SimpleString s);
: .
: Exception
:

435

www.books-shop.com

NetConversionException
NetDNSException
NetIOException
NetConnectException

NetConf igException

, (
inet_ntop()/inet_pton()); HostAddress
, ;
HostAddress
send()/recv();
Socket
bind(), connect(),
listen() accept(); SocketServer,
SocketClient MessageGroup
/ ;

Socket

C+ +
,

C++.

SimpleString ()
:
SimpleString(const char* s);
SimpleString(const SimpleString& s);
: .
:
+ (char *);
+(SimpleString& );
const char* GetString();

: ()

HostAddress ()
:
HostAddress(const char* Name=0, ENetwork Network=eIPv4);
HostAddress(HostAddressS Address);
: , .
:
void SetPort(int Port);

int GetPort(void) const;
,
ENetwork GetNetwork(void)

const;

436

V.
www.books-shop.com

struct sockaddr*
GetAddress(void)const;
int Getsize(void) const;
int ==(HostAddresss
Address) const;
int !=(HostAddresss
Address) const;
const char* GetHost(bool
byName=l);





'

:
Exception
NetConversionException
NetDNSException

C+ +
, ,

Message ( )
: ().
:

.
:
virtual char* Wrap(int& Bytes)
const;
bool Unwrap (char* package, int
Bytes, int MsgNum);

: ().

TextMessage ()
:
TextMessage(unsigned short Bytes);
TextMessage(const char* Msg, unsigned short Len);
: .
: Message

437

www.books-shop.com

:
=(const char* str);
=(const TextMessage* s);
+=(const char* str);
+=(const TextMessages s);
const char* GetBuffer(void) const;
char* Wrapfints Bytes) const;
bool Unwrap(char* package, int
Bytes, int MsgNum);
GetSize(void) const;
void SetSize(int Bytes);
int GetAvailable(void) const;

: ().

C+ +
, .

: SocketServer, SocketClient,
Datagram, Broadcast MessageGroup.

OpenSSL (SSLServer SSLClient).


Socket < SocketStream < SocketServer
< SocketClient
< Datagram
< Broadcast
< MessageGroup
. .2. Socket C++

Socket ()
:

Socket(void);
Socket(int sd);
Socket(ENetwork Network, EProtocol Protocol);
Socket(Sockets sock);
: ,
.
:
void Bind(HostAddress& Addr);
void CloseInput(void) const;

void CloseOutput(void) const;

438

V.
www.books-shop.com

int Send(Message& Msg, int


Options=0) const;
int Send(HostAddress& Addr,
Messages Msg, int Options=0)
const;
int Receive(Message& Msg, int
Options=0) const;
int Receive(HostAddress& Addr,
Messages Msg, int Options=0)
const;
void PermitRoute(bool Setting);
void KeepAlive(bool Setting);
void ShareAddress(bool Setting);
int GetReceiveSize(void);
void SetReceiveSizefint Bytes);
int GetSendSize(void);
void SetSendSize(int Bytes);
int GetMinReceive(void);
void SetMinReceive(int Bytes);
int GetMinSend(void);
void SetMinSend(int Bytes);
struct timeval
GetReceiveTimeout(void);
void SetReceiveTimeout(struct
timevals val);
struct timeval
GetSendTimeout(void);
void SetSendTimeout(struct
timeval& val);
ENetwork GetType(void);
virtual int GetTTL(void);
virtual void SetTTL(int Hops);
int GetError(void);








/
/
/
/
SIGIO
/
SIGIO
/ , 

/ , 

()
/
, 

:
NetException
FileException
NetConnectException
NetIOException
NetConf igException

439

www.books-shop.com

SocketStream ()
:
SocketStream(void);
SocketStrearn(int sd);
SocketStream(ENetwork Network);
SocketStream(SocketStreams sock);
: ,
(SOCK_STREAM).
: Socket
:

int GetMaxSegmentSize(void);
void SetMaxSegmentSize(short Bytes);
void DontDelay(bool Setting);

/
/

:
NetConfigException

SocketServer ()
:
SocketServer(int port, ENetwork Network=eIPv4, int QLen=15);
SocketServer(HostAddressS Addr, int QLen=15);
: TCP
.
: SocketStream
:
void Accept(void (*Servlet) (const
Sockets Client));

Servlet(), Socket

void Accept (HostAddressS Addr, void


(*Servlet)(const Sockets Client));

:
Exception
NetConnectException

SocketClient ()
:
SocketClient(ENetwork Network=eIPv4);
SocketClient(HostAddress& Host, ENetwork Network=eIPv4);

440

V.
www.books-shop.com

: TCP
.
: SocketStream
:
void Connect(HostAddress& Addr);

:
NetConnectException

Datagram ()
:
Datagram(HostAddress& Me, ENetwork Network=eIPv4,
EProtocol Protocol=eDatagram);
Datagram(ENetwork Network=eIPv4, EProtocol Protocol=eDatagram);

: UDP
.
: Socket
:
void MinimizeDelay(bool Setting);
void MaximizeThroughput(bool
Setting);
void MaximizeReliability(bool
Setting);
void MinimizeCost(bool Setting);
void PermitFragNegotiation(EFrag
Setting);

:
NetConfigException

Broadcast ()
:
Broadcast(HostAddress& Me);
: , .
: Datagram
: ().
:
NetConfigException

441

%RRNVVKRS

piracy@books-shop.com

MessageGroup ()
:
MessageGroup(HostAddress& Me, ENetwork Network=eIPv4);
: .
: Datagram
;
Connect(HostAddress& Address);
void Join(HostAddress& Address, int
IFIndex=0)
void Drop(HostAddress& Address);

:
NetConfigException
NetConnectException
RangeException

Java
, Java

.
lOException < ProtocolException
< UnknownHostException
< UnknownServiceExceptbn
< SocketException
< BindException
< ConnectException
< NoRouteToHostException
. .. Java

java.io.IOException ()
:
IOException();
lOException(String msg);
: ,

.
: Exception
:
java.net.ProtocolException
java.net.UnknownHostException

Socket
DNS

java. net. unknownServiceException

442

V.

www.books-shop.com

java.net.SocketException

()

:
SocketException();
SocketException(String msg);

: ,
bind(), connect(), listen() accept(); Socket, Server

Socket, DatagramSocket MulticastSocket.


: IOExceptian
:
java.net.BindException

/ (
, ,
)

java.net.ConnectException

, ,

java.net.NoRouteToHostException

Java
,

java.net.DatagramPacket

()

:
DatagramPacket(byte[] buf, int );
DatagramPacket(byte[] buf, int len, InetAddress addr, int port);
DatagramPacket(byte[] buf, int Offset, int len);
DatagramPacket(byte[ ] buf, int Offset, int len, InetAddress addr, int port);
: , ,
/ .
:
InetAddress getAddress();

/ /

void setAddress(InetAddress addr);

byte [ ] getData();

void SetData(byte[] b u f ) ;
void SetData(byte[] buf, int offset, int
len);
int getLength();
void setLength(int length);

443

www.books-shop.com

p , 

/ /

int getOffset();
int getPort();

void setPort(int port);

: ().
java.net. InetAddress ()
: ().
: , Internet;

, .
:
InetAddress getByName(String host);
InetAddress getAHByName(String host);

InetAddress getLocalHost();

String getHostAddress();
byte[] getAddress();

boolean isMulticastAddress();

, 

String getHostName();
:
UnknownHostException

 Java
Java ,

. ,
. , .
Object < InputStream
< OutputStream
< Reader
< Writer

< ByteArraylnputStream
< ObjectlnputStream
< ByteArrayOutputStream
< ObjectOutpufetrearn
< BufferedReader
< PrintWriter

. .4. ! Java

444

V.
www.books-shop.com

java.io.InputStream

( )

:
InputStream();
: .
: Object
:
int available();

int read();
int read(byte [] arr);
int read(byte [] arr, int


reset(),

,
mark()/reset()


,

offset,

void close();
void mark (int readlimit);
boolean markSupportedf);

int length);

void reset();

long skip();

:
IOException

java.io.ByteArraylnputStream ()
:
ByteArrayInputStream(byte[] buf);
ByteArrayInputStream(byte[] buf, int offset, int length);
:
(, ).
: InputStream
: (; InputStream).
: ().

java.io.ObjectlnputStream

()

:
ObjectInputstream(InputStream );
:

; InputStream Socket.

445

www.books-shop.com

: InputStream
:
int available();
void close();
void defaultReadObject();
int read();
int read(byte[] arr, int
offset, int len);
int readFully(byte[] arr);
int readFully(byte[] arr, int
offset, int len);
boolean readBooleanf);
byte readByte();
char readChar();
double readDouble();
float readFloat();
int readInt();
long readLong();
short readShort();
int readUnsignedByte();
int readUnsignedShort();
String readUTF();
Object readObject();

, 




, 
; readFully()
, , 

Object;

:
IOException
ClassNotFoundException
NotActiveException
OptionalDataException
InvalidObjectException
SecurityException
StreamCorruptedException

java.io.OutputStream ( )
:
OutputStream();
: .
: Object
:

446

V.

www.books-shop.com

void close));
void flush();
void write(byte b);
int write(byte[] arr);
int write(byte[] arr, int
offset, int len);

:
IOException

java.io.ByteArrayOutputStream ()
:
ByteArrayOutputStreain();
ByteArrayOutputStream(int size);
: .
: OutputStream
:
void reset();
int write(byte[] arr, int
offset, int len);
byte[] toByteArray();
intsize();
String toString( String
encoder);
void write (int b);
void writeTo(OutputStream );


,





OutputStream'

: ().

java.io.ObjectOutputStream ()
:
ObjectOutputStream(OutputStream );
:

; OutputStream Socket.
: OutputStream
:
void close();
void defaultwrite0bject();

447
www.books-shop.com

writeObject()
int flush();
int reset();
void write(byte b);
int write(byte[] arr);
int write(byte[] arr, int
offset, int len);
void writeBoolean(boolean b);
void writeByte(byte b);
void writeBytes(String s);
void writeChar(int c);
void writeChars(String s);
void writeDouble(double d);
void writeFloat(float f ) ;
void writeInt(int i);
void writeLong(long l);
void writeShort(int us);
void writeUTF(String s);
int writeFields();
void writeObject(Object o);


,

,


object

:
IOException
SecurityException
java.io.BufferedReader()
:
BufferedReader(Reader i);
BufferedReader(Reader i, int size);
: ,
;

; size .
: Reader
:
void close();
void mark(int readlimit);
boolean markSupported();
int read();
int read(byte[] arr, int
offset, int length);

448


,

,
mark()/reset()

, 

V.

www.books-shop.com

String readLine();
boolean ready();

( )
true,

void reset();
long skip(long n);

:
IOException
java.io.PrintWriter ()
:
PrintWriter(Writer );
PrintWriter(Writer , boolean autoFlush);
PrintWriter(OutputStream );
PrintWriter(OutputStream , boolean autoFlush);
: ; autoFlush

println().
: Writer
:
boolean checkError();
void close();
int f l u s h ( ) ;
void print(boolean b);
void print(char c);
void print(char[] s);
void print(double d ) ;
void print(float f ) ;
void print(int i);
void print(long 1);
void print(Object obj);
void print(String s);
void println();
void println(boolean b ) ;
void println(char c);
void println(char[] s);
void println(double d);
void println(float f ) ;
void println(int i);
void println(long 1);
void println(0bject obj);
void println(String s);
void write(byte b);

true,



;
Object String.valueOf()

, 
; autoFlush,

449

www.books-shop.com

int write(byte[] arr);


int write(byte[] arr, int
offset, int len);
int write(String s);
int write(String s, int offset,

int len);


,


,

:
IOException
SecurityException

java
Java IPv4: Socket, ServerSocket, DatagramSocket
MulticastSocket. .

java.net.Socket ()
:
Socket(String host,
Socket(InetAddress
Socket(String host,
Socket(InetAddress

int port);
addr, int port);
int port, InetAddress lAddr, int lPort);
addr, int port, InetAddress lAddr, int lPort);

: ,

(TCP).
: Object
:
void close();
InetAddress getInetAddress();
InputStream getInputstream();
boolean getKeepAlive();
void setKeepAlive(boolean bn);
InetAddress getLocalAddress();
int getbocalPort();
OutputStream getOutputStream();
int getPortf);

450

InputStream, 

, 


,


OutputStream, 

V.
www.books-shop.com

int getReceiveBufferSize();
void setReceiveBufferSize(int size);

int getSendBufferSize();
void setSendBufferSize(int size);
int getSoLinger();
void setSoLinger(boolean on, int
linger);
int getSoTimeout();
void setSoTimeout(int timeout);

boolean getTcpNoDelay();
void setTcpNoDelay(boolean on);
void shutdownInput();
void shutdownOutput();

/ ( 
),

/

/ , 
; 
, , 


:
IOException
SocketException

java.net.ServerSocket ()
:
ServerSocket(int port);
ServerSocket(int port, int backlog);
ServerSocket(int port, int backlog, InetAddress bindAddr);
:
,

.
: Object
:
setSocketPactory(SocketImplFactory
fac);

, 

:
Socket accept();
void close();
InetAddress getInetAddress();
int getLocalPort();
int getSoTimeout();
void setSoTimeout(int timeout);


Socket

,


/


451

%RRNVVKRS

piracy@books-shop.com

IOException
SocketException

java.net.DatagramSocket()
:
DatagramSocket();
DatagramSocket(int port);
DatagramSocket(int port, InetAddress bindAddr);
: UDP
.
: Object
:
void close();
void connect(InetAddress addr, int
port);
void disconnect();
InetAddress getInetAddress();
InetAddress getLocalAddress();
int getLocalPort();
int getPort();
int getReceiveBufferSize();
void setReceiveBufferSizefint size);
int getSendBufferSize();
void setSendBufferSize(int size);
int getSoTimeout();
void setSoTimeoutfint timeout);
void receive(DatagramPacket p);
void send(DatagramPacket p ) ;






,



/
/
/


:
IOException
SocketException

452

V.
www.books-shop.com

java.net.MulticastSocket ()
:
MulticastSocket();
MulticastSocket(int port);
: UDP
.
: DatagramSocket
:
InetAddres s getInterf ();
/ ,

void setlnterface(InetAddress

addr);
int getTimeToLive();
/

void setTimeToLive(int TTL);



void joinGroup(InetAddress addr);

void leaveGroup(InetAddress addr);
void send (DatagramPacket , ist.
TTL
TTL);
:
IOException
SocketException

453
www.books-shop.com

46
43

ARP,

45

CIDR,

D
42; 47

DHCP,

Ethernet

42; 46; 101


76

29,112

FTP,

HTTP,

GET

ICMP,

ICMPv6,

IGMP,

454

66; 84
366
84; 128
84
127

110; 337;
339, 342,343

340
'374
339
68
64
352
376

333

IP,
108;


337;



IPv6,
48; 346; 349;

346; 377;

348;



IPv4

Java

Runnable
259;
Serializable

TCP

TCP

UDP

109
47
312
341
59
42
203
60
29
354
378
351
349
351
351
205
351
375
348

255
256
444
256
256
255
255
249
250
256; 257
442
259
259, 260
257
267
249
250
252
253
254; 259
450
258


www.books-shop.com

251

MAC, 42, 101; 327; 332, 333

OpenSSL,
320

321
323

OSI,
105; 108; 293

106
108; 299

108

107

107
TCP/IP
112

107

105

P
Pthreads,
139; 145; 160
757; 158

160

R
RDP,
RPC,

83
108; 293
316
298

s
SSL,


SUID,

320
321
323
49

/,
88
TCP,
72, 110

312
/
88

75

111

206

75

80
81
UDP
71; 73


64
TCP/IP
312

42


109
110


28; 42
112

112
OSI
108

108

29; 228
Telnet

U
UDP,

94

96

110

92

94

93
96

82; 86
TCP
81

69

95
94


64

MAC
42; 101; 327;

IPv6

352;
IPv6
330;

309
332; 333
47
346
330; 332
377; 378

375; 377
348
43
42
45; 327

455

www.books-shop.com

45
26
46
46
43; 327
29
45; 327
226; 309

Java
249

132, 190

107

37; 53; 127;
202; 206; 209

203; 329;
333; 334
IPv6
'205; 352

334

332; 333

330
IPv6
353

332

6bone
354

157

158

158

313; 318; 334



314

314

202

203

180

171; 172; 208

177

180

181

179

168; 170; 171

170

170

170

170

180
Java
256

171

37; 182

172

172

175

173
176

77J

171;
177

172;
185

208

456

97; 126; 158

159;

159;

145
138
159
159
159
138
160
133
132
136
755
152
132
160
314

238

244
155; 156; 158
PTHREAD_ERRORCHECK_
MUTEX_INITIALIZER_NP
158
PTHREAD_MUTEX_
INITIALIZER
757

228


www.books-shop.com

PTHREAD_RECURSIVE_
MUTEX_INITIALIZER_NP
157

147

316; 317

56
146

87

226

75

257
BufferedReader
448

256
ByteArrayInputStream
445

256
ByteArrayOutputStream
447

CharArrayReader
256
256
CharArrayWriter
253
DatagramPacket

443
DatagramSocket
253; 255
452

256
FilelnputStream
256
FileOutputStream
256
FileReader
256
FileWriter
256
FilterReader
256
FilterWriter
260
Frame
250
InetAddress
444

InputStream
250; 256; 257
445

256; 257
InputStreamReader
442
IOException
254
MulticastSocket
259
getInterface()
259
getTimeToLive()
259
setInterface()
259
setTimeToLive()
453

256; 257
ObjectInputStream
445

ObjectOutputStream
256; 257
447

OutputStream
250, 256; 257

446
OutputStreamWriter
256
PipedInputStream
256
PipedOutputStream
256
PipedReader
256
PipedWriter
256
PrintStream
256
PrintWriter
256; 257

449
Reader
256
SequenceInputStream
256
ServerSocket
252

451
Socket
250, 257

close()
257

450
SocketException
443
StringReader
256
StringWriter
256
Thread
259;
260
Writer
256

241

256

274

283

273

242

274

241

282

286

241

242

241

259;
260

242

242

241

242

243

43

46

""
227
SSL
321

52

32; 40

26; 30

35
39

457

www.books-shop.com


EACCES
31; 120
EAGAIN
37; 54; 124; 173; 207
EBADF 37; 39; 52; 120; 121; 124
EBUSY
158
EFAULT
52; 146
EINTR
185;
215
EINVAL 31; 37; 48; 52; 120; 161
EMFILE
146
EMSGSIZE
54
ENETUNREACH
54
ENOTCONN
38
ENOTSOCK
38; 54
EOPNOTSUPP
121; 124
EPIPE
52; 127
EPROTONOSUPPORT
31
ESRCH
161
EWOULDBLK
38; 173

ping
337

341
traceroute
343

28

267

42

155;
158

333

334

334

43; 46

45; 327

334

97; 132; 134; 135

107

37

238

243

284

239; 269

458

241
281


59
ICMP
68
TCP
71; 73
UDP
69

60

102

28

67

TTL
63; 102; 343

61

64
.
61

62

64

63

62

62

103

63

62; 204

56; 67

338

38; 62; 67

64; 65

66

45

45; 327

241

29

48

49

90; 119

48;
203; 206

365

50

50

50

50

34;

50
50

www.books-shop.com


132
stderr
135; 165; 221

147
stdin
755; 165; 221

147
stdout
135; 165; 221

147

157

158

158
()
165

160

1
35

139

755

136

ifconfig
349
init
135; 160, 220
rpcgen
293; 300; 302; 304

301

300
tcpdump
76; 77

132
.

146

342

162

136

136

225; 226;

297;

HTTP
SSL

R

223;


306
305
29,6
296
305

295
127
323
123
298
224
117
189
229

189

32; 40

26; 30

35
191
122

118

39

121

193

25

193

757

226; 309

184; 220
SIGALRM
152; 161; 219
SIGCHLD
SIGFAULT
153
SIGFPE
220
SIGHUP
153
SIGINT
SIGIO
54; 177; 180; 181;
209; 210; 220
SIGPIPE
52; 276; 218
153
SIGSTOP
153
SIGTSTP
153
SIGTTIN
153
SIGTTOU
53; 179; 210; 219
SIGURG
101


102
107

277

152
154

152


372

757

158

158

158
155

155; 156;

158
155; 158
157
28
117
26

459

www.books-shop.com


296


77; 113
Java
249

258
TCP
80; 250; 252
UDP
82; 86; 253

254

259

56; 120

63; 68;
337; 338; 339
IPv6
351

IP_ADD_MEMBERSHIP
203
IP_DROP_MEMBERSHIP 203
IP_HDRINCL 61; 62, 203; 337
IP_MULTICAST_IF
204,259
IP_MULTICAST_LOOP
204
IP_MULTICAST_TTL 204,259
IP_MTU_DISCOVER
204
IP_OPTIONS
204
IP_TOS
204
IP_TTL
63,204
IPV6_ADD_MEMBERSHIP 205
IPV6_ADDRFORM
205
IPV6_CHECKSUM
205
IPV6_DROP_MEMBERSHIP 205
IPV6_DSTOPTS
205
IPV6_HOPLIMIT
205
IPV6_MULTICAST_HOPS 205
IPV6_MULTICAST_IF
205
IPV6_MULTICAST_LOOP 205
IPV6_NEXTHOP
205
IPV6_PKTOPTIONS
205
IPV6_UNICAST_HOPS
206
SO_BROADCAST
201,328
SO_DEBUG
201
SO_DONTROUTE
202
SO_ERROR
202, 209,217
SO_KEEPALIVE 201, 202; 206
SO_LINGER
202, 258
SO_OOBINLINE
202; 210
SO_PASSCRED
202
SO_PEERCRED
202
SO_RCVBUF
202, 258
SO_RCVLOWAT
202,220
SO_RCVTIMEO
185
SO_SNDBUF
203

SO SNDLOWAT
460

203

185; 203
48; 203;
207;331
SO_TYPE
203
SO_REUSEPORT
331
SO_TIMEOUT
258
TCP_NODELAY
258
TCP_KEEPALIVE
206
TCP_MAXRT
206
TCP_MAXSEG
206
TCP_NODELAY
206; 207
TCP_STDURG
206

368

SOL_IP
203; 369
SOL_IPV6
205; 370
SOL_SOCKET 201; 368
SOL_TCP
206; 371

330

90; 119

100

ip_mreq
330
ipv6_mreq
353
linger
202
pollfd
184; 200
protoent
339
sigaction
152
sockaddr
90

119

33
sockaddr_in
34
sockaddr_in6
34; 350

245
SO_SNDTIMEO
SO_REUSEADDR

185

/etc/protocols

/etc/services

netinet/in.h
sys/socket.h
sys/types.h

339; 404
364
49; 90; 121
365
32; 63
32
32
313

www.books-shop.com


314

314

_clone()
135; 139; 160

142; 409
CLONE_FILES
143
CLONE_FS
143
CLONE_PID
143
CLONE_SIGHAND
143

CLON_V
143
accept()
117; 119; 121; 123;
153; 170; 177; 181; 192, 193; 229

215
EAGAIN
124
EBADF
124
EOPNOTSUPP 124

122; 383
alarm()
185; 220
bind()
32, 49; 71; 83; 90; 92, 93;
117; 119; 123; 203; 206

275
EACCES
120
EBADF
120
EINVAL
120

INADDR_ANY
91; 330

90; 119; 381


bzero()
35

424
close()
117; 119, 202

216
EBADF
39

39; 433
connect()
40; 80; 82; 86;
90, 91; 117; 170

215

32; 384
()
162; 163; 220

410
1()
163

410
execle()
164

410
execlp()
163

410
execv()
164

410
execve()
410

164

execvp()

exit()
138; 141
fcntl()
175;
178;
208; 210
F_SETFL
174

173; 425
O_NONBLOCK 38; 174
fork() 139; 143; 160; 163; 192; 194

216

137; 408
gethostbyname()
57

216

403
gethostname()
402
getpeername()
401
getpid()
137
getpriority()
159
getprotobyname()
339; 404
getsockopt()

216

201; 406

368
htonl()
57; 91

396
htons()
35; 51

396
inet_addr()
57

397
inet_aton()
35; 51

398
inet_ntoa()
57

399
inet_ntpp()
350; 400
inet_pton()
350; 399
kill()
154
listen()
117;
119; 193

216
EBADF
727

EOPNOTSUPP
727

121;
382
memset()
424
ntohl()
51

397
ntohs()
57

397
pipe()
EFAULT
146
EMFILE
146

146; 427

410

182; 427

461

%RRNVVKRS

piracy@books-shop.com

POLLERR
184
POLLHUP
184
POLLIN
184
POLLINVAL
184
POLLOUT
184
POLLPRI
184

185
pthread_create()
143; 161

216

139; 415
pthread_detach()
EINVAL
161
ESRCH
161

161; 417
pthread_exit()
416
pthread_join()
416
pthread_mutex_destroy()
418
pthread_mutex_init()
418
pthread_mutex_lock()
757

419
pthread_mutex_trylock()
158

419
pthread_mutex_unlock()
157

420
read()
40; 48; 52; 71; 82; 117;
119; 127; 170; 171; 203; 208
EAGAIN
37
EBADF
37
EINVAL
37

35; 429
recv()
40, 48; 53; 86; 90;
119; 127; 172; 173; 177;
180; 186; 203; 209; 299

216
ENOTCONN
38
ENOTSOCK
38

37; 391
MSG_DONTWAIT
37
MSG_OOB
37; 206; 210
SG_
37
MSG_WAITALL 37; 209
recvfrom()
78; 83; 90; 93;
122, 203; 343

87

86; 393
recvmsg()
203

394
sched_yield()
412
select() 177; 195; 196; 197; 199; 228

198

462

182; 430

185
send()
48; 83; 86; 90, 119;
172, 175; 177; 180; 203; 208

216
EAGAIN
54
EBADF
54
EMSGSIZE
54
ENOTSOCK
54
EPIPE
54

53; 387
MSG_DONTROUTE
53
MSG_DONTWAIT 54; 209
MSG_NOSIGNAL 54; 218
SG_
53; 210
sendfile()
390
sendmsg()
68; 203; 205

389
sendto()
68; 83; 88; 90,
203; 340, 341

86; 388
setpriority()
159
setsockopt() 62; 180, 330, 337; 341

216

201; 405

368
shmget()
146
shutdown()
119

216

39; 395
sigaction()
SIG_DFL
153
SIG_IGN
153

152, 422
SA_NOCLDSTOP
153
SA_NODEFER
153
SA_NOMASK
153
SA_ONESHOT
153
SA_RESETHAND
153
SA_RESTART
153;
186; 216
signal()
152

421
sigprocmask()
423
sleep()
186
socket()
37; 40; 52; 80, 113;
117; 119; 121; 203

216

PF_INET
PF_INET6

33
33; 350

www.books-shop.com

PF_IPX
33
PF_PACKET
31
,
359
31
EACCES
31
EINVAL

31
EPROTONOSUPPORT

0, 380

30
SOGK_PACKET 77; 113
63; 68;
SOCK_RAW
337; 339
SOCK_STREAM
119
, 363

78
socketpair()
385
sysctl()
206
vfork()
165
wait()
152; 160; 219

413
waitpid()
WEXITSTATUS() 162

WIFEXITEP()
162

219; 413

40; 48; 71; 82; 117; 119;


184; 203; 207; 208
EBADF
52
EFAULT
52
EINVAL
52
EPIPE
52

52; 432

50

write()

201; 327; 328; 329

318; 319

319

319

318

318

318

319

319

311

463

www.books-shop.com


Linux
..
. .
..
. .
.. , .. ,
. .

"".
101509, , . , . 43, . 1.
. . 090230 23.06.99
.

10.08.2001. 70x100/16.
Times. .
. . . 33,9. .
. . 27,11.
5000 . 1480.
" "
,
.
197110,
, ., 15.

www.books-shop.com