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

TRANSPORTA UN SAKARU INSTITTS


OC UNIX WINDOWS

2006

681.3
952
Transporta un sakaru institts

..
OC UNIX WINDOWS: . . : , 2006.
316 .

,
" ", " ", "

",
"

"

.
" ",
.
"
", .

,
UNIX(*NIX) Windows.
.

, . . . .

ISBN 9984-668-56-8

.., 20062003

Transporta un sakaru institts,


20062003

.........................................................................................................................................................6
1. 1 TCP/IP...............................................................................................................8
2. TCP/IP.............................................................................................................................8
1. .........................................................................................................8
2. ..........................................................................................................11
2. IPv4 (Internet Protocol)........................................................................................12
3. IP-.....................................................................................................................13
4. IPv4.....................................................................................................................20
3. IPv6......................................................................................................................23
5. IPv6......................................................................................................................................25
6. ...........................................................................................................................26
7. .................................................................................................................................28
8. IPv6..........................................................................................................................................28
9. IPv6..........................................................................................................30
10. IPv6...............................................................................................................................31
4. ICMP .......................................................................................................................................32
11. ICMP...................................................................................................................................32
12. ICMP....................................................................................................................................33
13. ICMP ................................................................................................................35
5. IGMP........................................................................................................................................42
14. ...................................................................................................................43
15. IGMP-....................................................................................................................................44
16. ..............................................................................................................................45
17. (queries) (reports) IGMP..........................................................................................45
18. ............................................................................................46
19. ...............................................................................................................................47
20. ............................................................................................................47
21. ..........................................................................................................48
6. ARP...........................................................................................................................................49
22. ARP..............................................................................................................50
7. TCP..........................................................................................................................................53
23. TCP.........................................................................................................................................53
24. ................................................................................................................................54
25. TCP............................................................................57
25.1.1.1. ............................................................................................................................57
25.1.1.2. ..............................................................................................................58
25.1.1.3. ......................................................................................60
25.1.1.4. ...........................................................................................................61
26. TCP...........................................................................................................................62
27. TCP...................................................................................................66
28. .....................................................................................................................67
29. TCP..........................................................................................................................................68
30. .............................................................................70
31. TCP-.............................................................................................................72
32. ............................................................................73
33. TCP .....................................................................73
34. TCP...................................................................................................................75
8. UDP..........................................................................................................................................78
1. 2 ......................................................................................................................81
9. .......................................................................82
10. - .................................................................84
11. ................................................................................................................................85
3

12. .......................................................................................................................85
35. ...................................................................................................................................87
35.1.1.1. . ................................................87
35.1.1.2. .......................................................................................89
13. .................................................................................93
36. connect()...................................................................................................................................93
37. bind() .......................................................................................................................................95
38. listen()......................................................................................................................................97
39. accept().....................................................................................................................................99
40. .............................................................................................100
41. ..................................................................................................103
42. select()....................................................................................................................................105
43. ................................................................................108
44. ......................................................................................................................109
45. ioctl() fcntl() .......................................................................................................................112
46. ...........................................................................................................116
47. ......................................................................................................119
48. ............................................................................124
14. UNIX-like / ...................................................................................128
15. UNIX- ..............................................................................................136
49. inetd......................................................................................................................137
16. .........................................................................................................................137
50. setsockopt()................................................................................................................139
51. getsockopt()................................................................................................................144
52. ...............................................................................................146
17. .......................................................................................................................................148
18. Nagle.....................................................................................................................................149
19. TCP/IP.................................................................................153
SYN 154
-...............................................................................................................................................154
-................................................................................................................................................154
1. 3 Windows Sockets....................................................................................................157
20. ...............................................................................................................................................157
21. -, WinSock..................................................159
22. -, Windows........................................................................162
23. .....................................................................163
24. Windows...................................................................................166
53. Windows-.................................................................................................166
54. WinSock API.......................................................................................................170
55. WinSock API.....................................................................................................174
55.1.1.1. WSAAsyncSelect()........................................................................................................174
55.1.1.2. WSAAsyncGetXByY...........................................................................................183
25. ...........................................................................................184
56. ................................................................................................185
57. WSAGetLastError()....................................................................................................186
58. ................................................................................................................................187
26. TCP- Windows ......................................................................187
59. WinTCP....................................................................................................................................188
60. WinTCP.....................................................................................................................................189
...............................................................................................................................................192
1. 4 Winsock 2.0......................................................................................................236
27. Winsock 2.0 API........................................................................................238
61. WSAAccept()........................................................................................................................239
62. WSAConnect().......................................................................................................................240
63. WSADuplicateSocket()..........................................................................................................240
Shared Sockets............................................................................................................................................241
64. WSAGetQOSByName().........................................................................................................241
4

65. WSAHtonl()...........................................................................................................................242
66. WSAIoctl().............................................................................................................................242
67. WSAJoinLeaf()......................................................................................................................243
68. WSARecv()............................................................................................................................244
69. WSARecvDisconnect()..........................................................................................................244
70. WSARecvFrom()....................................................................................................................245
71. WSASend()............................................................................................................................245
72. WSASendDisconnect()...........................................................................................................246
73. WSASendTo()........................................................................................................................246
74. WSAProviderConfigChange()................................................................................................246
28. API Winsock 2.0...............................................................247
75. WinSock Service Provider .................................................................................................247
76. SPI...................................................................................................................248
29. / Winsock 2.0...................................................................................................257
30. I/O .....................................................................................................285
31. WinSock 2.0.............................................................287
77. API ....................................................................................................................287
77.1.1.1. AcceptEx().....................................................................................................................287
77.1.1.2. ConnectEx(), DisconnectEx().......................................................................................290
77.1.1.3. TransmitFile(), TransmitPackets().................................................................................290
77.1.1.4. WSARecvMsg() ...........................................................................................................292
78. RSVP.........................................................................................292
79. Helper API............................................................................................294
80. ..........................................................................................................................300
1. 5 ............................................................................304
32. NetBIOS..............................................................................................................................304
81. NetBIOS.................................................................................................305
82. NetBIOS..........................................................................................................307
82.1.1.1. NetBIOS-..............................................................307
82.1.1.2. NetBIOS- WinSock..................................311
33. .......................................................................................312
.................................................................................................................................................322
...............................................................................................................................................324

,
, -, ,
. .
1) :

-, ,
.
-, ,
, .
TCP, IP, ICMP .
, NetBIOS.
(Berkeley)
UNIX- API [19], [17], [38], [25], WinSock 1.1, 2.0,
WinSock API WinInet API [39], [36], [2],
/++, MS Visual C++, Delphi . .
Windows.
, TCP/I,
. NetBIOS
.
- -
FTP, HTTP, DNS, SMTP, POP3 IMAP, proxy-,
Firewall , , ,
FlashGet DAP,
Wingate WinRoute, Ping Traceroute,
( CommView NetWatcher),
Traceplus32, tcpdump WinDump, , (update)
(, , Windows Update,) online, , KaZaa, DC++ .
.
2)
( - -).
HTML (
4.0 ), Java, JavaScript, VBscript, XML (Extended Markup Language), SSL, CSS,
CGI . ., HTML ,
Java Development Kit . .
3) -.
CGI,
FastCGI API MS ISAPI, Netscape NSAPI, IBM ICAPI, SSI, ASP ActiveX
.., HTTP 1.1 .
Perl, ,
PHP.
4) ,
, ,
.
6

HTML JavaScript,
-,
. (, ), ,
. . (
) , -
.
5) ,
, - .
X.25, X.400 , .
PPP,
.

(.. .1 )
" ", , .
TCP/IP,
.
IPv4 TCP.

"-".
" ", UNIX,
,
Windows, TLI.
Windows Sockets - WinSock 1.1
WIN32 API.
Windows,
, .
WinSock 2.0
. API Windows
Windows-, Windows 95 Windows Server 2003.
/,
,
. WinSock SPI,

, ,
, Ad-aware .
,
WinSock 2.0, , ..
,
, NetBIOS
.

.
, ( , )
, .
,
" , , ", "
" " "
" ",
, ,
.
lusin@tsi.lv

1. 1 TCP/IP

TCP/IP. ""
,
.
TCP/IP ,
Request for Comment (RFC) [33], [34], [35]. RFC
, .
TCP/IP RFC, RFC .
Transmission Control Protocol/Internet Protocol (TCP/IP)
, .
(Department of Defense, DoD) 25
Arpanet ,
.
TCP/IP (Vinton Cerf) (Robert
Kahn). ARPA
. ARPA
Internet Protocol (IP), TCP/IP
.
- TCP/IP
Berkeley. 4.x BSD System
(Berkeley Software Distribution), BSD Networking Releases.
.
UNIX IP
. ,
.
TCP/IP UNIX, BSD, LINUX
(Windows NT, 9, 2000 ) IBM PC
,
.
TCP/IP :
,

.

TCP/IP, .
intranet-,
WWW.
,
, .

"-".

2.
1.

TCP/IP

,
ISO/OSI (International Standard

Organization/Open System Interconnection),


.
TCP/IP [3], [9], [37], [31], [15], [22], [21], [13] ,
, TCP/IP
OSI . TCP/IP 4 . 1.1.

. 1.1. TCP/IP

( IV) OSI.
TCP/IP ,
: Ethernet, Token
Ring, FDDI, 100VG-AnyLAN, "-" SLIP
PPP, X.25, frame relay.
, ATM
.
TCP/IP RFC,
IP .
( III) ,

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

. IP ,
.
,
RIP (Routing Internet
Protocol), ARP RARP ,
ICMP (Internet Control Message Protocol)
IGMP (Internet Group Management Protocol).
( II) .
TCP (Transmission Control Protocol)
UDP (User Datagram Protocol). TCP
9

1
0

. UDP
, IP,
.
, OSI
.
( I) .
TCP/IP
. ,
FTP, Telnet,
SMTP POP3, ,
HTTP, WWW, SOAP,
RPC .
FTP (File Transfer Protocol) .
FTP TCP.
FTP . ,
, ,
. , FTP . ,
,
. FTP-
,
Anonymous. FTP
20 21 ( , ).
-,
.
TCP/IP FTP ,
. ,
FTP, ,
TFTP (Trivial File Transfer Protocol).
,
UDP.
HTTP ,
World Wide (WWW), SOAP (Simple Object Access
Protocol) .
telnet ,
.
. telnet
, ,
, - telnet
, , , Kerberos.
SNMP (Simple Network Management Protocol)
.
.
, , .. SNMP
, .
,
, . SNMP
, ,
,
.
RPC (Remote Procedure Call) ,
,
. ,
Windows DCOM, OM++.

1
1

, ,
, ,
- TCP/IP.
2.


"". , ,
(header) - .1.2 ( TCP).

. 1.2.

..
"" (. . 1.3).

1
2
. 1.3.

, "ICMP" "IGMP",
. .1.1 , IP,
IP. , IP, ,
ICMP IGMP IP-.
"ARP" "RARP". , Ethernet,
Ethernet, IP-.
,
. , Ethernet
, - Internet Protocol (IP) 0x0800;
Address Resolution Protocol (ARP) 0x0806 ..
IP
, .
TCP UDP
(. 1.7.2)
tcpdump. , tcpdump
,
BPF (BSD Packet Filter - ),
UNIX , DLPI (Data Link Provider Interface)
SVR4.
5.

2. IPv4 (Internet Protocol)


TCP/IP IP. ,
IPv6 (. 1.3),
"" ,
( IPv4 IP).
"" - .
IP (Internet Protocol),
.
IP (Internet Protocol) TCP/IP.
, . ,
IP .
, . IP
, . ,
, , IPX
Novell NetWare.
IP ,
. .
- .
,
. IP , ,
.
IP . , ,
. I
, .
, . ,
, . ,
, ,
.

1
3

IP , ().

.
:
IPv9

3.

IP-


.
(messages), TCP (segments), UDP I
(packet) (datagram),
(frame).
IP . (. 1.4):
0

15 16
31

TOS 8
HLEN 4
VERS

16

4-

4
16
DF MF
-13
TTL 8
8
16
IP-
IP-

. 1.4. IP-

4- (32- ) .
32- : 07,
815, 1623 , , 2431. big
endian (big endian ,
, "")
TCP/IP . (network byte order).
1.1.

IBM PC
IBM 370
DEC VAX, PDP
MOTOROLA 68000
PYRAMID

little endian

big endian

X
X
X
X
X

, , , , little
endian (little endian ,
),
. (
) "host byte order" .
4 0100.
00101 (5 , .. 20 ).
01111 60 .
(TOS Type Of Service) 8
0-2

("Precedence") :
111
1

7
/.

1
4

110
101 CRITIC-ECP "Critical and Emergency Call Processing".
, , ,
.
100
011
010
001
000
3-6 :
3 (Delay)

,
4 (Throughput)
,
5 (Reliability)
,
6 (Cost)

.
D,T,R,C.
.
TOS , .
TOS, TOS
.
,
, .
- 16 IP- 65536
, .
IP- ,
IP- , , 576 . 576 ,

. ,
512 64 . IP-
, 576 ( , IP-
).

. (. 1.2.2)
, , ,
MTU.
;

.
"
" MTU, Maximum Transfer Unit ,
. Ethernet 1500 (
1514 ), FDDI 4096, Token Ring 4464 , ATM - 9188 , 296 128
( .25.) SNAP Ethernet_802.3
1492 ( ),
proNET-10 2044 .
MTU=576. . TCP
MSS Maximum Segment Size (. 1.7.1).
MSS, 536. 536+40 (40
TCP IP) 576. MTU IPv4,
MTU, 68 .

PMTU -- Path Maximum Transfer Unit --
-- , ,
, , .

.
DF "Dont Fragment" IP-
. , IP-
,. IP-
. , ICMP1

1
5

" , "
(Fragmentation needed but don't fragment bit set). ,
MTU
MTU (MTU path discovery). ,
, " ,
", " " - "Black Hole".
PMTUBlackHoleDetect
.
MF, , " " (More
Fragments). ,
. (Fragment Offset)
.
, ,
.
TCP ,
TCP , ( IPv6 ).
, , ,
, IPv4 .
TTL (Time-To-Live)
. TTL
1, , ,
. , , (
).
HOP ().
. .
(by default) TTL IP-
. , Windows 9x/NT/2k - TTL=128, Solaris 2.x Intel/Sparc - TTL=255, Solaris 8 Intel/Sparc TTL=64, IRIX 6.x SGI - TTL=60, NetApp OnTap 5.1.2-5.2.2 - TTL=54 32,
64 128 (max=255),
.
TTL=0,
ICMP - 11 1Time Exeeded ( ).
,
. 1.2 . 255
.
1.2

ICMP

IGMP

GGP

"-"

TCP

EGP

""

17

UDP

27

RDP

28

IRTP

29

ISO TP4

ISO 4

80

ISO IP

ISO

89

OSPF

" "

() .
IP , 0.
1

1
6

16- (ne's complement


.)
16- . 16-
. IP- , 16-
. , ,
, , , 1,
.
( ), IP .
. - ,
, . ICMP, IGMP, UDP TCP
. (, )
,
.
IP- IP-, .
? RFC-1071,
- 1.
IP 32- .

Land. IPv4- IP- ( IP) Internet,
( Source Address) ,
Destination Address. TCP- Source
Port Number Destination Port Number. , IP-,
. , ,
- , .

IP .
IP , .
; , .
. , ,
. ,
( ) .
, .1.5.
0

1-2

3-7

. 1.5.

0 :
1 ;
0 .
: 0 "" 2 " ".
. .1.3 ,
IP; "-" " " , "
". "+" , ,
( ).
1.3. IP

+(11)

( )

1
7
0

LooseSourceRouting ( )

StrictSourceRouting ( )

+(4)

Stream ID.
SATNET ()

Internet Timestamp ( )

" " ,
IP- .
32 .
. "Stream ID" ""
, " " "Internet
Timestamp" traceroute.
,
,
. " " IP-
, , IP- . . 1.6
.
, (7 ).
, IP-,
. , , IP-, ,
.
4- . 9 IP-.
40 , .
0
8
16
24
------------------------------------------| (7)
|
|
|
-------------------------------------------------------|
IP-
|
-------------------------------------------------------|
IP-
|
-------------------------------------------------------|
.......
|
----------------------------------------------------------------------------------------------------. 1.6. IP-

, , ,
(
, ).
. , ,
, , . ,
4- IP- , ,
.
- IP-.
, .
, ,
;
, .
"Loose/Strict Source Routing" ( 0, 3 9
),
.

1
8

, , ,
. ,
Net
IP- Net, , .
,
, ,
, . ,
, ;
.
IP . , Strict Source Routing, IP- . 1.7.
0
8
16
24
-------------------------------------------| (137)
|
|
|
--------------------------------------------------------|
IP-
|
--------------------------------------------------------|
IP-
|
--------------------------------------------------------|
.......
|
-----------------------------------------------------------------------------------------------------. 1.7. IP-,

, ,
.
;
, . ,
Loose Source Routing, IP-.
, IP-,
.

. , ,
, , , .

. ,
. , , ,
. ,
IP-, (
; , ,
) , , .
, A B, M1
M2. "Destination Address" M1,
M2 ( . 1.7 4,
, 11).
M1 , , ,
(M2) "Destination Address", 4,
M2 3,
( M2). M2
, B ,
4. ,
(12) , .
,
,
.
1

1
9

32- : IP- , , 32-


. . 1.8 .

0
8
16
24
31
---------------------------------------------------------| (68)
|
|
| | |
---------------------------------------------------------|
IP-
|
---------------------------------------------------------|

|
---------------------------------------------------------|
.......
|
---------------------------------------------------------. 1.8. . ,


( ). 4-
() ,
- ( -40 ). 4-
, .
(.1.9) :

0
1
3

, IP-
IP- (, . 1.8)
IP- , ,
IP- IP- .

. 1.9.

, ,
. ,
,
. , ,
, ,
; , . , ,
.
, ,
IP- ,
. , IP-
.
, , .
.
.
, "Loose/StrictSourceRouting"
() .
"Destination Address"
,
,

2
0


.
IP- .
, (20 ),
.
IP-, ,
.
? IP . , ,
, ,
.
, . ,
, .
32- .

{127.x.x.x, <ANY>} " , loopback" RFC-1112
, localhost.

4.

IPv4

,
, " " MTU
(Maximum Transfer Unit). ,
, .
. ,
MTU . ,
MTU , MTU .
IP
. , . " ", ,
, IP , - ,
IP- .
, IP
. .
. ,
Windows-,
(breaking point), IP MTU
. , .
() .
IP- " "
IP-. , IP-
.
MTU. . 1.4
IP-. , 16
, .
,
65535 .
IP-, , 1 65536 ( 0 65535).
, ,
0 8191, 8192 .
8 , . , 1
, 2 . .
65528 (8191*8).

2
1

65528 :
65528 7 65535 ( ).
. IP ()
. , IP, .
"
" IP- , . "" ,
( , ). "-" ,
, IP ,
.
. MTU=128, 730 . ,
- 128 , 12820=108 . 108 8,
8- . , - 104. :
730=7*104+2. , 7 20+104=124
- 20+2=22 - 8 . ,
( ), .
UNIX .
104 6 , 6*104=624
. 6- , 106 .
20 , 7- 126 (, 124),
MTU. , 8-
. Windows- 8 , UNIX 7!
,
(
,
, DoS) .


IP- IP- , IP , :
1. IP- ;
2. ( ) IP- IP;
3. IP- .
. IP
IP- , ,
.
C IP-
( UNIX- , , 30 ).
. IP-,
. , , IP
.
- . ,
, IP-.
"-", , IP
.
, IP
. IP ,
.
, .
. -,
. -
. ,
2

2
2

. -, ,
, , , .
: , .
TCP MTU, 576 ,
. .
512 TCP IP- .
MTU, ,
.
TCP/IP-,
, , , MTU
, .



, .
, , .
, .
more-fragments . (
) , .
, .
. ,
, ,
" " "" ,
. , IP- (,
)
.
N , 8
(64 ). + MTU ,
.
8- . NFB (
).
,
. "more fragments" 1.
,
. "more fragments" ,
.
6 NFB.
N .
. IP-
IP- 9876 300 (
DF 0). IP-
, MTU 128 .
IP- IP-.
IP-
|

(300 )

IP-

1 | 1 104

IP-

2| 2

104

IP- 3
3 | 92

IP- 1 :
1.
2.

9876;
5 ( );
2

2
3

3.
124 ();
4. MF
1;
5. 0 ( ).
IP- 2 :
1.
9876;
2.
5 ( );
3.
124 ();
4. MF
1;
5. 13 ( ).
IP- 3 :
1.
2.
3.
4.
5.



MF

9876;
5 ( );
112 ();
0;
26 ( ).

, ,
IP- ( ) 8.
104 (13 ), 108,
128 (128 20 = 108, 20 ).
, IP - IP-,
- RFC-791:
, , .
,
.
, "more fragments" ,
, " ".

3. IPv6
IPv6.
, IPv4.
, TCP/IP 1970- -
1980
, IP, TCP, UDP ICMP, .
,
TCP/IP .
, TCP/IP
( , )
.
, .
TCP/IP,
. 1997 Microsoft Corp.
TCP/IP Windows NT,
, [11].
, -
TCP/IP, .
.

, 100 ,
1000 .
.

2
4

intranet
TCP/IP, ,
, .
,
.
.
, , frame relay ATM,
.
,
(, Ethernet). ,
,
IP.
.
90- ,
30 , 95-
.
,
IP-. IPv4- 32 . ,
, ,
IP-, IP-
. , 1981 200 ,
2000 - 75 .
IPv4.
IPv4.
( A, B, C, D E),
. 16777214 , 65534 ,
254 . - ,
- .
, , 16 . ( ),
254 ( ).
16 384 .
A, B C
" " IP-. IP-
32- , ( ),
: , ,
, , , .
IPv4
- NAT (Network Address Translation),
. " "
10.0.0.0 10.255.255.255, - 172.16.0.0 172.31.0.0 -
192.168.0.0 192.168.255.0 - ,
NAT-,
, IP-.
,
2005-6 . :
" , "Fake -" , -".
IPv4- RFC3330 http://www.iana.org/assignments/ipv4-address-space.
IPv4- ,
,
,
.

2
5

IPv4 , (QoS
Quality of Service), , ,
, ,
(
).
, IPv4,
[11]:
;
;
;
IP-;
IPv4;
;
;
;
.
IETF - Internet Engineering Task Force - 90 . 1995
RFC-1752 The Recommendation for IP Next Generation Protocol.
IP Next Generation (IPng).
, RFC-1883, Internet Protocol version
6 (IPv6).
IPv6:

IP-.
. IPv6 128 ,
296 , IPv4.
.
Iv6- . ,
( 40 IPv6 20 IPv4),
(8 12).
IPv6 (CRC). , ,
, .
,
.
, IP-.
IP-, ,
.
IPv6 . NDP
(Neighbor Discovery Protocol - )
IPv4 ARP ICMP, .
ARP- ,
,
, Ethernet.
5.

IPv6
IPv6 IPv4.

IPv6 : 128 16 .
: 340 282 366 920 938 463 463 374 607 431 762
211 456 1015 . IP-
IP-. , IPv6
DHCPv6,
, . IPv4,
NAT-, IP-,
IP-.
2

2
6


, .
( ) IPv6 5 ,
, , :

, 6 , ,
- ( IPX),
.
2.
IPv6 ,
, -
IP-, .
,
,
.
, ,
. .
, IPv4
OSPF, RIP-2, BGP4. ,
IPv6.
CIDR Classless InterDomain Routing.
CIDR , , .
. ,
, 100 , 3 5-6
.

, .
CIDR
IPv4. , 254 65
534 . ,
, , ,
, . -
,
.
IPv6 IPv6-: (unicast), (multicast)
(anycast). Unicast .

- (point-to-point). Multicast
. ,
, ,
. anycast ,
.
IPv6 8 16- ,

0123:4567:89AB:CDEF:0123:4567:89AB:CDEF.
. , IPv6,
IPv6-.
.
6.

. 1.10 IPv6.
128 . IPv6 aggregatable
global unicast addresses .
, (
) .
6 , IPv6- .
2

2
7


. 1.10. IPv6

,
. ,
.
IP-, IPv4.
( , link-local,
1111111010),
, ( , site-local,
1111111011), .

.


IPv6 , IPv4. . 1.11
IP- 128 . 8 1.
(Flags) 4 , 0.
, , 0.
11111111

. 1.11 . IPv6

, .
(Scope) 4 ,
. . 1.4.
1.4.

34

67

2
8
F


IPv6 (anycast).
, (
) .
, ,
, , .
,
. IPv6
(Source Routing),
- .

. ,
- Source Routing,
unicast, anycast,
.
anycast unicast.
. ,
, anycast.
7.

IPv4, IPv6 , .
0.0.0.0.0.0.0.0 , .
.
0.0.0.0.0.0.0.1 (loopack, ).
.
, , .
8.

IPv6
IPv4, IPv6 (. 1.12).
(Version) 4 6, IP.

(Priority) 4 IP IP- . 0 7
, .
. 1.5.

2
9
. 1.12. IPv6

1.5.

(, )

(, )

(, HTTP FTP)

(, Telnet)

(, )

8 15 , ,
, .
, , ,
8, 15, , ,
, .
(Flow label) 24
. ,
.

().
, , ,
.
, ,
.
(Payload length) IPv4, 16
IP-, .
. IPv4, ,
IPv6- 65575 .
(Next header) 8 ,
IPv6-.
, IPv6-. , IPv4.
( limit) 8 ,
IP-.
IPv4 (TTL) IPv6
(Hop Limit). IPv4 TTL
, .
, .

. IPv4 TTL
( - ).
- ,
, TTL .
TTL

128- IP- .
, IPv6- ,
. ,
IPv6- ,
. ,
2

3
0

IP-
.
- Payload (data). , , ,
.
9.

IPv6

IPv6 IPv6-
(. . 1.13). (Next header)
.
, .

TCP

IPv6
=TCP

IPv6

=

=TCP
IPv6
=

TCP

TCP

=TCP

. 1.13. IPv6

IPv6 .
. 1.13 : Next Header ,
TCP. Next Header ,
, ,
TCP. Next Header
, . ,
.
(Hop by Hop Options Header)
( )
. ,
64 ( Jumbo Payload).
(Routing Header)
, IPv4.
, . IPv4
. IPv6 ,
.
8- (Fragment Header) ,
. ,
TCP/IPv4,
, ,
MTU. , IPv6 MTU,
MTU . MTU
, IPv6 IPv4,
- , .
.
IP Security
. IPv6, Iv4-. ( ,
IPv4, .)

3
1

ESP-
IPSec. , IPv6,
IPv4.
(Authentication Header, )
( , IP- ,
) , , IP-
. AH
. AH
, ,
. ,
, IP-
.
MD5.
AH -
,
. ,
.
"" IP-. IPv6
, ,
" ".
ESP- (Encapsulated Security Payload, ESP)
: , .
, , ESP-
, . ESP-
, , , DES
. ESP-. ESP-:
(tunneling) IP- (transport)
, , TCP.
(Destination Options) . ,
. , Iv6-,
.
:
( )
;
(
Destination Options,
);
,
IPv6;
, Hop-by-Hop Options,
;

. , ,

.
40 IPv6.
10.

IPv6

IPv6 Iv4 IPv6.


Iv4 IPv6 . IPv6
IPv4 (. 1.14).
96

32- IPv4

3
2
. 1.14. IPv4- IPv6

, IPv4, (tunneling),
( ) .
IPv6- Iv4. ,
Iv6- , Iv4,
. Iv4-
.
(. 1.15) IPv6-agpeco, IPv4 (IPv4-mapped
Iv6 address). , IPv4.

. 1.15. IPv6-apec, IPv4

, ,
, , ,
, IPv6.
6bone, Sprint.
IPv6 100 ,
IPv6. 6bone
41 , , .
6Bone .
WorldCom
VBSN.
IPv6 ATM. 2000
6bone, 6INIT. EU Fifth Framework.
-, IPv6.

4.

ICMP

IP-
.
TCP/IP - .
, , , ,
(Internet Control Message
Protocol, ICMPv4), IPv4.
IPv6 ICMPv6.
3- - ICMPv4, IGMP ARP.
ICMP ,
. ,
, TCP UDP, I.
, ,
, I, RAW SOCKET (. 2.10).
, .
, , I
I (. 3.)
11.

ICMP

TCP/IP IP : I
(IGMP). I, , TCP UDP,
3

3
3

IP. , IP, ICMP .


IP ICMP - . ,
IP, , TCP UDP.
IP ,
. , IP
,
( IP ).
TCP/IP ,
. send ,
, TCP/IP .
, , .
, TCP/IP.
,
-. ,
, . ,
, ,
. -
, .
ICMP ,
. ,
, . , ICMP
.
,
. ICMP IP-. ICMP
- ICMP -
. ICMP - ,
, .
12.

ICMP

ICMP , -
. ICMP
.
, ICMP . , -
- . ,
ICMP-, -
. , .
ICMP , "" ,
-. - ,
, - .
IP- .
.
, ,
,
. , ,
- .
-.
TCP/IP ,
,
. , , ,
.
, , ICMP
- . ICMP IP,
3

3
4

ICMP, , IP. , ICMP .


, ICMP- (1.1.3.5),
, . ,
ICMP , , ,
. . ,
.
ICMP-: - .

-
, ICMP -
. , ICMP- IP-
. -
IP- 64 ( ) .
, - .
-
. - ICMP
. ICMPv6
ICMPv4.

ICMP
TCP/IP , ,
ICMP-. , - ICMP
.
. ., ,
ICMP-
ICMP-. IP-
. ,
, ICMP-
(broadcast storm).

ICMP- , ,
, IP- ICMP-,
. , ,
. IP- ,
ICMP- .

ICMP-
ICMP - . TCP/IP ICMP IP-. ICMP- : 8 Type 8- Code.
ICMP-.

. 1.16. ICMP

3
5

"" (Type) "" (Code) 16- .


.
, ICMP-.
. , ICMP IP- ( , )
64 ( ) . , IP- TCP-,
8 TCP-, ,
, .
. ICMP-,
15 . 1.6.
1.6. ICMP

13.

0
3
4
5
8
9
10
11
12
13
14
15
16
17
18

(echo reply)
(destination unreachable)
(source quench)
(redirect)
(echo request)
(router advertisement)
(router solicitation)
(time exceeded)
(parameter problem)
- (timestamp request)
- (timestamp reply)
() (information request)
() (information reply)
(address mask request)
(address mask reply)

ICMP

. 1.5, ICMP ,
. .
, 3, " ", 16 "".

" "
ICMP ,
. ,
3 -.
ICMP, "
" (destination unreachable) . (015)
" " 1.7.
1.7. ICMP " " ( 3)

(network unreachable)

(host unreachable)

(protocol unreachable)

(port unreachable)

, (fragmentation needed and DF set)

(source route failed)

(destination network unknown)

(destination host unknown)

3
6
8

- () (source host isolated)

(destination network administratively prohibited)

10

(destination host administratively prohibited)

11

(network unreachable for type-of-service, TOS)

12

(host unreachable for type-of-service, TOS)

13

- (communication administratively prohibited by filtering)

14

He (host precedence violation)

15

(precedence cutoff in effect)

IP . IP
, , . 1.6 ,
, . , ,
, , ,
.

. 1.17.

. 1.17 ICMP- " ".


, . 1.16.
, (Code) 0 15.
, ICMP- IP-, ,
64 ( ) .
, IP-
, - , ,
, .
. ,
.
ICMP , ICMP IP.


,
IP-. ,
"", , .
.
. ,
.
, ,
. ,
ICMP
.
, , ICMP - . . 1.18
.

3
7

. 1.18. ICMP-

- ,
, IP- ICMP-. ,
ICMP- , ICMP-
IP- ( ) IP- ( 32-
ICMP-). IP- ,
, IP- , .

. 1.8 ( 5).
1.8. ICMP- "" ( 5)

( )

(TOS)

(TOS)

, ,
" " (TOS) IP- . TOS
. IP-, . 4.5.2,
ICMP ,
, . ICMP
. ,
, . ,
, ICMP-co .
. , ,
.
.
ICMP, Redirect .
(code 0) Redirect datagrams for the Network
; default ; . (code 1) ; Redirect datagrams for the
Host
. IP ; ,
( Destination IP ;
), IP ; , ,
( Gateway).
, IP ; ;
!
ICMP ; . , ICMP ,
Redirect datagrams for the Network

3
8

,
. , ,
. IP-
TTL, .
1.9. ICMP- " " ( 11)

TTL

. ,
. , , .
ICMP- 11 1-Time Exeeded ( ).

" "
Parameter Problem (
), .
I-, 1.11.
1.11. ICMP- " " ( 12)

IP-

. 1.19. ICMP- " "

1 ,
TCP/IP ().
" IP-" ,
. . 1.19 ICMP "
". (pointer) ,
ICMP-. 1 (" ")
.

" "
,
, , .. ,
. TCP
. , ,
. IP ,
.
,
"" , - ICMP-co
" " ( 4). " " (Source Quench
, ) -
3

3
9

. , "
" IP.
ICMP-co.
, .
ICMP- " ",
. ICMP-
, . ,
. ICMP " " ,
" ", 4.
" " ,
0 .
source quench " ".
, ,
. UNIX-
TCP/IP ICMP- . TCP-,
, " ".
UDP- ,
/ .
RFC-1812 , .

- ICMP
, I -,
, , . .
, .

" "

. ,
, ICMP
.
ICMP : " "
Router Solicitation ( 9) " " - Router Advertisement ( 10).
- (,
), ,
. " " , . ICMP " " ICMP-, .
, - ,
. -
, .

4
0

. 1.20.

. 1.20 . "
" " ",
" " IP- .
. 1.20, ICMP- ,
IP. " " ICMP-
, .
" " 32- .
. , (32-
32- ). " " ,
. TTL IP! ICMP-
. , , 450 600 ,
" " 30 . "
"
.

" "
" "- TimeStamp - ( 13 14)
. . 1.21
.

(13 14)
(0)

. 1.21. ICMP- " "

, :
. -
. ICMP .
4

4
1

" " , . ,
. -
" ", . ,
- " " ,
. " " ,
,
.

""
ICMP- "" Echo Request Echo reply ,
. ICMP- " ",
" " , ,

. - "" ICMP,
, Ping (Packet INternet Grouper). ,
Ping - "",
. , ,
( , TCP/IP ICMP-)
. . 1.22 - "".
, ,
.
(8 0)

(0)

. 1.22. ""

ICMP- Echo Request Ping of Death.


ICMP-,
.
, , ,
. ,
, IP-, .
:
ping -l 65510 <IP- >
- IP- (20 ) + ICMP +
ping (8 ) + 65510 . 65535 ping-.
, ping
.
,
.

-
(InterNIC) ,
.
. .
IP- ,
. , IP. RARP - IP- .
, IP- .
4

4
2

C RARP- IP-
, . ,
ICMP- 17 ( .
1.23) 18.

. 1.23. "- "

ICMP-
, .
.

(BOOTP - Bootstrap Protocol)
TFTP, UDP 67 68 .

5. IGMP
IP- (unicast), (broadcast) (multicast).
.
,
.
- -
.
,
, .
, unicast,
, .
,
.
( )
, , .
( )
.
"" .

,
, online-, - ,
..
( , .).

TCP. UDP
: , .. ,
,
, .
(IGMP Internet Group
Management (Membership) Protocol), ,
.
,
. , (
)
4

4
3

,
.
, ,
.
, IP- .
. - ,
, , ,
.
IGMP 2 RFC-2236. IGMP
, .
DVMRP (Distance Vector Multicast Routing Protocol),
MOSPF (Multicast OSPF), PIM
(Protocol-Independent Multicast) . ,
FreeBSD mrouted multicasting route daemon DVMRP.
14.


" ". IP- IP- A, B, C
D, . . [6].
(.1.25) -, ..
, . -
IP-
.
. IPv4- D '1110'.
28- .

. 1.24 IPv4

- IP- 224.0.0.0
239.255.255.255. , ,
IP-. " " , 32- ,
23- "" . ,
, IP- "" .
OSI - (DataLink Layer) (Network Layer). , ,
Ethernet FDDI, , .

IP- ,
.
IP-
Ethernet-.
IP-, 224.0.0.0 239.255.255.255,
(. 1.25) MAC-,
Ethernet-, 001-00-5E.

4
4

01

00

5E

. 1.25

,
. IP ,
Ethernet- . ,
, IP_ADD_MEMBERSHIP (.
2.9) , MAC, .
. , ,
() .
, , ,
, .
(DVMRP, MOSPF, PIM),
.
(IGMP)

ICMP, IGMP IP-. ICMP, IGMP
IP-. , , IGMP
, . . 1.26 IGMP IP.

. 1.26. IGMP IP-

, IP- IGMP-, IP, 2.


15.

IGMP-
. 1.27 8- IGMPv1 (RFC-1112, 1992 .)

. 1.27. IGMPv1

4
5

IGMP (IGMP version) 1 (


). IGMP (IGMPv1 type) 1
, , 2 , .
(checksum) , ICMP.
IGMPv2 (RFC-2236, 1997 .) (.1.29)

. 1.28. IGMPv2

IGMPv2 -:
0x11 = - Membership Query.
:
- , , ,
.
- - , , ,
.
IP- ,
.
0x16 = 2 .
0x17 = .
, IGMPv1:
0x12 = 1 .
8-15 Membership Query ( )
Max Response Time (8 ) .

- .
16.

,
( ,
.)
, .
, .
, .
, - API .
"", .
.
.
, , ,
, . IP,
Berkeley UNIX, API .
17.

(queries) (reports) IGMP

IGMP- ,
, .
. IGMP-, .
,
, , .
, .
4

4
6

1. , ,
. , , ,
( ), .
2. IGMP- (. ),
, - - .
.
0,
, .
3. IGMP- IGMP- ,
.
,
,
. , ,
( )
, ,
.
. 1.29 IGMP-: , , ,
. ,
,
.

. 1.29. IGMP

IGMP ,
, , UDP.
18.


224.0.0.1 " " Membership Query "Group Address".
; ,
, 125 . ,
. - Membership Report,
, . "Max Response Time"
Membership Query , Membership
Report ( 10 .)
: , ,
.
Membership Report ,
"Group Address". , ,
, .
,
.

Membership Report, .

4
7

, ,
. (
260 .), , .
, Leave Group
224.0.0.2 (" "); , ,
"Group Address". , Membership
Query . Leave Group,
Membership Query . ,
"Max Response Time" ( 1 .),
Membership Report, ,
. 2 .
, IGMP,
IP- ( ,
Membership Query IP- , ,
IGMP). .
, , IGMP
, , IP,
.
19.

. 1.29 , TTL IP-, ,


1. TTL 0 "" .
TTL 1,
. TTL
.
ICMP- , .
IP- ICMP " " (time exceeded), TTL 0.
TTL. Traceroute, TTL.
, ,
TTL. ,
.
TTL (expanding ring
search) . TTL 1,
, TTL 2, 3 .
.
20.

224.0.0.0 238.255.255.255
. 239...
.
224.0.0.0 224.0.0.255 ,
, .
, TTL.
,
.
224.0.0.1 . 1.29 , IGMP- IP-
224.0.0.1. (all-hosts).
,
.
, ,
4

4
8

. (
). "" ,
.
224.0.0.2 (all-routers).
.
224.0.0.4
DVMRP,
.
224.0.0.5 224.0.0.5 OSPF.
224.0.0.6 OSPF-.
224.0.0.9 RIP-2.
224.0.0.10 IGRP-.
224.0.1.1 NTP
PIM ..
:
224.0.0.3 .

Multicast RFC-1112,
, .
0 " IP-".
,
IPv4 ( IPv6). :
, .
1 " , IP-".
, .
IP-, " 0" " 1".
2 " IP-".
.
.
, TCP/IP (IGMP).
. 2.9.3.
21.

1992
- Multicast Backbone
(MBONE). IETF,
-
.
MBONE ,
,
, . 1996 MBONE
2800 . , ,
, , MBONE, .
MBONE , ,
.
,
.
IP-,

4
9

IP-.
MBONE DVMRP.
MBONE
UDP.
SAP (Session Announcement Protocol) SDP
(Session Description Protocol). , SAP/SDP
[19].
, IGMP
,

.
UDP.
,
.
- , ,
, .
.
Flooding, Spanning Tree, Reverse Path Broadcasting, Truncated Reverse Path Broadcasting,
Reverse Path Multicasting, Core-Based Tree.
, DVMRP, MOSPF, PIM[5].
,
.
,
, , .
,
,
.

6. ARP
,
ARP
Address Resolution Protocol. . 1.30 - -,
WinDump.
1- 4-, ARP-, .
- .

. 1.30. - -

Ethernet- ARP- 195.216.160.130 (


DNS, ISP). ARP- DNS-
4

5
0

MAC- 44:45:53:54:00:00 ( M- dialup-) MAC-


20:53:52:43:00:00. ARP- - .
, -
4.
: MAC Media Access Control ,
MAC- 48- Ethernet-.
22.

ARP

, - ""
. Ethernet- [1], Token-Ring, FDDI, ATM .. ..
MAC, .

MAC- MAC-. MAC-
Ethernet-, .
Ethernet- IP-? ARP, ,
IP- Ethernet-.
IP-, IP, Ethernet
.
, "",
ARP-. ARP-
. IP- Ethernet-.
IP- Ethernet- IP-.
. 1.31 ARP :
IP address
223.1.2.1
223.1.2.3
223.1.2.4

Ethernet address
08-00-39-00-2F-C3
08-00-5A-21-A7-22
08-00-10-99-AC-54

. 1.31. ARP

6- Ethernet- 16- (
) .
ARP- , IP- Ethernet- ,
. IP- ,
. IP-
. , Ethernet- . (), Ethernet-.
.
, TELNET,
TCP, TCP- TCP IP-.
IP- , TCP IP-.
IP- Ethernet,
Ethernet- ( ) .
, .
ARP- "/" ARP.
ARP ?
" , ... ". ARP-
, :
5

5
1

4. (broadcast 255.255.255.255) ARP- . .


Ethernet-.
5. IP .
Ethernet-
ARP; Ethernet- ""
Ethernet- ARP- ARP.
ARP : " IP- ,
, Ethernet-"
ARP- . 1.32.

. 1.32. ARP-

ARP IP- ,
IP-, Ethernet-.
ARP- ", IP- ,
MAC-." ARP- "/"
(. 1.33):

. 1.33. ARP-

-. Ethernet
Type Ethernet- ARP- ARP-. ARP ARP- IP- ARP-.
(. 1.34) :

. 1.34. ARP-

ARP :
5

5
2

1.
2.
3.
4.

ARP- .
IP- .
ARP- IP-to-Ethernet ARP-.
IP- ARP-,
IP- Ethernet-.
5. Ethernet- IP- .
ARP-
ARP-, .
- , ARP-,
. IP , .
.
Ethernet . . 1.35
( ), , ,
Ethernet. ,
. (
"raw formats") Ethernet_II Ethernet_802.3,
. 4 ,
Ethernet_II, ""
, :
Internet Protocol (IP) 0x0800;
Address Resolution Protocol (ARP) 0x0806;
AppleTalk 0x809B;
Xerox Network System (XNS) 0x0600;
NetWare IPX/SPX 0x8137.

. 1.35. Ethernet

Ethernet [1]. RARP


. IP- ,
"", X.25 ATM, IP MAC.
ARP ?
ARP- ( ) ARP
( Solaris, ARP , ARP , ),
" ARP-".
, - IP- MAC,
, IP-
MAC. ,
. , "".
5

5
3

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

7.

TCP

TCP/IP TCP (Transmission Control Protocol) .


.
.
RFC-793 [34].
TCP:

() ;
() ;
( ) ;
"" ;
16-
;
" " (sliding window)
;
.
TCP, TCP Extension for Transactions
(T/TCP), RFC-955, 1379
1644. FreeBSD Linux SunOS.
" TCP - Fast TCP." Fast TCP
,
.
, ,
.
TCP - 5 .
"Tiny TCP".
23.

TCP

TCP . ,
TCP ,
. , "
". TCP. ""
"" ,
. 0, 3, 125 599 , .
TCP ,
( " ") ( PSH . 1.7.4
1). TCP,
, .
, , ,
MSS (Maximum
Segment Size), . ,
IPv4- ,
IPv45

5
4

. MSS MTU MTU-40 (40


TCP IPv4). TCP-
MTU . ,
, , IP- MTU=576, .
,
, IP-.
TCP-IPv4 , TCP-IPv6 ,
, .
24.


(Well Known Numbers, Assigned Numbers - . ). ,
, . ,
, UNIX
(magic numbers).
TCP/IP
. UNIX-
/etc/protocols RFC-1340 Assigned Numbers.
/etc/protocols:
# Internet (IP) protocols
# from: @(#)protocols

5.1 (Berkeley) 4/17/89

# Updated for FreeBSD based on RFC 1340, Assigned Numbers (July 1992).
ip
icmp
igmp
ggp
ipencap
st
tcp
egp
pup
udp
hmp
xns-idp
rdp
iso-tp4
xtp
idpr-cmtp
rsvp
vmtp
ospf
ipip
encap
..

0
1
2
3
4
5
6
8
12
17
20
22
27
29
36
39
46
81
89
94
98

IP
ICMP
IGMP
GGP
IP-ENCAP
ST
TCP
EGP
PUP
UDP
HMP
XNS-IDP
RDP
ISO-TP4
XTP
IDPR-CMTP
RSVP
VMTP
OSPFIGP
IPIP
ENCAP

# Internet protocol, pseudo protocol number


# Internet control message protocol
# Internet Group Management protocol
# Gateway-gateway protocol
# IP encapsulated in IP (officially ``IP'')
# ST datagram mode
# Transmission control protocol
# Exterior gateway protocol
# PARC universal packet protocol
# User datagram protocol
# Host monitoring protocol
# Xerox NS IDP
# "Reliable datagram" protocol
# ISO Transport Protocol class 4
# Xpress Tranfer Protocol
# IDPR Control Message Transport
# Resource ReSerVation Protocol
# Versatile Message Transport
# Open Shortest Path First IGP
# Yet Another IP encapsulation
# Yet Another IP encapsulation

protocols,
. 5,

http://compnetworking.about.com/library/ports/blports_glossary10.htm.
,
.
, TCP UDP.
WKS (Well Known Services) .
5

5
5

: , FTP,
World Wide Web ..
/etc/services. ,
.
/etc/services:
tcpmux
1/tcp
echo
7/tcp
echo
7/udp
...
ftp
21/tcp
# 22 unassigned
telnet
23/tcp
# 24 private
smtp
25/tcp
# 26 unassigned
time
37/tcp
time
37/udp
rlp
39/udp
whois
43/tcp
domain
53/tcp
domain
53/udp
bootps
67/tcp
bootps
67/udp
bootpc
68/tcp
bootpc
68/udp
tftp
69/udp
gopher
70/tcp
gopher
70/udp
finger
79/tcp
www
80/tcp
www
80/udp
..

# TCP port service multiplexer

mail
timeserver
timeserver
resource
# resource location
nicname
nameserver # name-domain server
nameserver
# BOOTP server
# BOOTP client
# Internet Gopher
http # WorldWideWeb HTTP
# HyperText Transfer Protocol

World Wide Web FTP,


RIP, bootp, BIND,
, .
TCP/IP , ,
TCP UDP,
.
IP, .
IP- ,
TCP/IP. ( TCP 6) IP
.
(, 80) , .
. 1.36.

5
6

. 1.36.

TCP/IP .
, WKS Well Known Services
( - ephemeral - -
.)
, ,
, ,
( UNIX d
daemon , httpd).
TCP UDP ,
WKS. HTTP
, , ,
.
(. 1.37). .
, - (Source) 8080, WKS
(-) 80 (Destination). SYN ACK 1.7.4.
, , WKS,
, , WKS. ,
WKS,
. (IP-, ) (
""). , , http- ,
, 144.206.130.137:80, , , 144.206.130.138:8080.
5 Well Known Numbers -
.

. 1.37.

, TCP UDP 16-


. , .
. ,
TCP/IP, FTP-, , TCP 21 FTP. Telnet- 23. TFTP (Trivial File Transfer Protocol)
5

5
7

UDP 69 , Lovesan
tftp get, .
DNS 53 (. - 4). ,
TCP/IP, 0
1023.
( - Internet Assigned Numbers Authority (IANA).)
1992 1 255.
256 1023 UNIX- .
UNIX-, .
IANA 0 1023.
- UNIX-
Telnet rlogin.
. Telnet TCP/IP
23. .
rlogin, , UNIX ( -UNIX
).
80- 513.
BSD- TCP/IP
1024 5000. 5000
( ). , Amerika Online
5190,5191,5192, ,
BSD- TCP/IP.
Solaris 2.2 . , TCP
UDP 32768.
UNIX- .
.
0 1023 (, rlogin,
rsh) -.
,
, :
0-1023 ,
1024-49151-
49152-65535 () .
IANA
http://www.iana.org/assignments/port-numbers, .
, TracePlus/Ethernet ,
, IANA.


.
, . ,
, , .

RFC 147 - The Definition of a Socket, 7 May 1971 - .

25.

TCP

25.1.1.1.

TCP ,
( ) .
TCP
(sliding window). , ,
,
5

5
8

,
TCP.
,
TCP ( TCP
NACK). ,
, , .
(, TCP 1 ACK . 1.7.4),
, .
W, N,
, N+W.
,
.
" "
. :
"" ,
TCP- TCP-, .
, ,
TCP-. TCP-
() (). Receive Window,
- Send Window.
, TCP , ,
RCV.NXT RCV.NXT+RCV.WND-1 (. 1.7.8), ,
. ,
, .
, -
1/2-32 .
TCP,
TC- -
- ( acknowledgement).
.
TCP- , .
, . RWIN
RWIN=n*MSS, n=2,4,8 10, MSS=MTU-40, 40
( ) TCP IPv4. ,
, .
,
.
4.2BSD by default () 2048
. 4.3BSD 4096 . SunOS 4.1.3, BSD/386, SVR4
4096 . , Solaris 2.2,
4.4BSD, AIX 3.2, , 8192
16384 .
API
. .

25.1.1.2.

,
( ).
""
, , :

5
9

.
, TCP.
,
, ,
. ,
,
, .

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

, ,
.

. 1.38.


, ,
. ,
, . . 1.39
N .
, ,
, 1 N. 1
N-1 1.
1 , ,
- 1 ( )
(
TCP .)

6
0

. 1.39. ""

- , N ,

. (sliding window)
() , ,
.
,
.
,
.
, RFC-793 TCP ,
. RFC 5 :

(ACK) ;
(Delayed ACK); 500 ms
. , ACK ;
() (ummulative ACK),
ACK n ACK
k < n;
(Negative ACK), ,
; ;
() (Selective ACK, SACK), ,
, ().

:
TCP (Delayed ACK),
. " ACK" ,
TCP ACK ,
"ACK-", .

25.1.1.3.

(.1.40) ,
4 , 4 , 4-
, :

() - 1,2,3,5,6,7,8 (4- );
ACK 1,2,3,3,3,3,3 ( 1,2,3);
4 ( ) ACK 8;

6
1

.1.40

. ACK ( 200 ),
: -, , -, 200
, ACK- ACKs piggybacking.
,
,
.
, TCP ,
. TCP.

.
PUSH .

25.1.1.4.

, . ,
.
, - .
"" TCP,
, , .
, .
.
"" ( URG TCP- 1).
6

6
2

,
.
1.7.6 2.9.1.
-
. ,
, , ACK-, . ,
TCP
. , TCP
RST URG .
- ,
(. TCP).
,
.
26.

TCP
TCP .

. 1.41. TCP

(SOURCE PORT) 2 , -;
(DESTINATION PORT) 2 , ;
(SEQUENCE NUMBER) 4 , ,
; TCP
PAWS
;
(ACKNOWLEDGEMENT NUMBER) 4 ,
, ;
;
(Data Offset) 4 , TCP,
32- .
, OPTIONS;
6

6
3

(RESERVED) 6 , ;
(CODE BITS) 6 ,
, :
URG () .
ACK . -,
- ( ). ,
,
TCP, .
.
:
ACK=1 , .
TCP ( ACK, ).

PSH ;
:
PUSH- TCP-.
TCP-,
. , PUSH-,
, TCP -.
TCP ,
TCP-, PUSH . ,
, , PUSH .
TCP- , , ,
TCP , , .
, TCP- PUSH-, ,
.
, , API TCP- ,
PUSH , PUSH- .
PUSH- , TCP ,
. Berkeley PUSH-,
"" . PUSH-
write() , .
Berkeley PUSH-,
.

RST . (
), ,
- . ,
,
, ,
. RST
RST.
, SYN_SENT (. ),
(RST) SEQ.
, .
SYN_SENT ( RST
SYN), RST , ACK
SYN. RST ,
. ()
LISTEN, .
SYN_RECEIVED, LISTEN.
CLOSED.
- ,
CLOSED, .
"" (reset) TCP ,

,
.
6

6
4

SYN ,
; , , SYN;
FIN
.
:
,
. RFC-1025 ,
(SYN, URG, PSH, FIN 1 ), "" (
, - " ", "
" ..).

(WINDOW) 2 ,
; ,
IP-TTL, .
Window TCP- . ,
AIX - , Window=0x3F25. TCP/IP Windows
NT5, OpenBSD FreeBSD, Window=0x402E;

(CHECKSUM) 2 , .
/ ,
8 16- . (0)
.
0;
(URGENT POINTER) 2 ,
URG, , ,
;
(OPTIONS) ;
, ,
; SYN ACK+SYN (
TCP . .)
(PADDING) ,
, 32- ;
.
SYN.
() TCP,
SYN
TCP- , , .
,
. .
(firewall),
(incoming) SYN- ,
-.
SYN- (, )
, "-" .
- ,
, TCP- "" , .
, TCP- SYN-,
SYN- ACK ()
-
. TCP- SYN-
, ACK- !

TCP
6

6
5

TCP .
, TCP RFC-793,
, (nop) MSS.
.1.42.

. 1.42. TCP

1 , .
0 1 .
, .
NOP " " ,
, 4 . , TCP
4.4BSD, tcpdump TCP SYN:
<mss 512, nop, wscale 0, nop, nop, timestamp 146647, 0>

MSS
MSS,
. MSS SYN-.
MSS , 536 ,
( IPv4)
576 .


wscale TCP 16 32 .
TCP- ,
16- , 16-
. TCP "" 32- .
1- 0 ( ) 14.
14 1.073.725.440 (65535 * 2 14).
SYN; ,
.
, SYN.
, , SYN-,
, , ,
6

6
6

SYN-.
.
, ,
, ,
0.
, .
Host Requirements RFC , TCP
. ( , ,
SYN.) , TCP
, . ,
.
,
S R . 16
, , R ,
. ,
, 32- , S
(16- ) TCP-.


(timestamp)
. ,
RTT (Round Trip Time, ) ACK.
( " ACK", " ", TCP
ACK.)
RTT , , 8
. , , RTT.
,
. , ,
SYN-. SYN- ,
.

(TCP Selective Acknowledgement SACK, RFC-2018).


(SACK) - ,
.
, ,
.
RFC-1072
IETF. ,
, : NETBLT,
XTP, RDP, NADIR VMTP.
2 :

Sack-Permitted (SACK ). 4.
SYN-.

SACK. 5 .

.1.42 .
Windows , Win98SE.
27.

TCP

.
,
. , TCP-
6

6
7

.
( ), ,
. TCP
URG Urgent Pointer, ,
. ,
Out Of Band OOB. , [19]
, 2.9.1.1,
" " , . ,
" " "
", , .
URG ,
. , ,
( , ..)
? ,
.
, . ,
, .
[19]. ,
FTP, telnet rlogin.
28.

TCP
.
. TCP.
, , ..
, . ,

, ,
.
, ,
TCP , ( ).
, .
, N ,
.
.
, ,
.
, , , .
0 2**32-1.
TCP , ,
.
. TCP
. ( TCP IP .)

- -. ,
(. 2.4). - .

.
TCP IP, IPv4-.
- TCP. - -,
IP- .
TCP. TCP -
.

6
8

- ( I-), TCP-
- , , .
(
), ,
. .
29.

TCP

,
. ,
. , TCP
, .


TCP , .
,
, . TCP
, .
, .

(Retransmission TimeOut, RTO).
. , ,
. ,
, .
(-) ,
TCP.
- ,
, .
, ,
"" .
-
, . TCP -
.
(
RTT, Round Trip Time),
RTO. RTT
, .
. - ,
. ,
2. -
.
TCP ,
. ,
. TCP
[7] .
" ". .

. ,
.
. ,
,
. ,
.
6

6
9

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


, .
(quiet timer) TIME_WAIT (. 1.7.13),
, ;
,
IP . 2MSL
TCP- Maximum Segment Lifetime.
RFC-793, MSL 2 ., TIME_WAIT 4
. . , , BSD, MSL 30 .,
TIME_WAIT 1 .
30 . 2 . , TIME_WAIT,
, 2MSL .
, , 2MSL, ,
2MSL
, 2MSL
.
,
, ,
, .
, TCP
.
, RFC-793 , TCP
MSL .
" " (quiet time).
, MSL.

( IP-).
.


(persistence timer) ,
, ,
, .
, ,
. , ,
, , .
, . , - ,
, , .
. 60 .
TCP- " " (
- 5 .)

7
0


. , TCP
"". , , ,
, , ,
( ) . ,
- - .
- , ,
, . -
TCP- ,
. " " (NOP),

. , TCP/IP.
(keep-alive).
(keep-alive timer) ,
(idle timer) .
.
, ,
5 45 . 360
.
Windows 4.1.6.
30.

TCP .
(Transmission Control Block, ),
, ,
.
.
.
,
. 1.9.
1.9.


SND.UNA

Send Unacknowledged

SND.NXT

Send Next

SND.WND

Send Window

SND.UP

Sequence number of last urgent set


URG=1

SND.WL1

Sequence number for last window

SND.WL2

Acknowledgment number for last window


update

SND.PUSH

Sequence number of last pushed set

ISS

Initial send sequence number


RCV.NXT

Sequence number of the next received set

RCV.WND

Number of sets that can be received

7
1
RCV.UP

Sequence number of last urgent data


URG=1

RCV.IRS

Initial receive sequence number

.
LISTEN, SYN_SENT, SYN_RECEIVED, ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2,
CLOSE_WAIT, CLOSING, LAST_ACK, TIME_WAIT, CLOSED
( , , TCP,
.)
:
LISTEN
SYN_SENT

TCP.
.
.
SYN_RECEIVED ,
.
ESTABLISHED ,
. .
FIN_WAIT_1
TCP,
.
FIN_WAIT_2
TCP.
CLOSE_WAIT .
CLOSING
TCP
.
LAST_ACK
,
TCP (
).
TIME_WAIT
, ,
TCP (. 2.11)
CLOSED
.
TCP .
(, , , , , ),
, , SYN, ACK, RST FIN,
.
TCP .
,
. TCP , ,
,
. . 1.43
"" ,
. ,
. TCP .

7
2

. 1.43. TCP-

31.

TCP-

TCP
, TCP
, connection oriented.
,
. TCP
, .
TCP
( , end-points).
IP- ( ) .
.
TCP-.
:

(
). TCP (active
open).

TCP- -
, .

TCP-
(passive open), , .

,
( , )
(active port).

- .
.
.
7

7
3

, TCP
ACK
.
. , , .
, .
- TCP-
. ,
TCP- "
", " " . , -
TCP, - TCP .
, , TCP SYN . SYN|ACK ,
. TCP- RST ,
. ,
..
TCP,
.
32.

, TCP
, .
, , ,
.
.
ISN Initial Sequence
Number. ISN ,
, ISN.
,
. , Linux
1.2.8 ISN = +1000000, , .
Windows NT4.0 ISN=10, .
, RFC-793 , ISN 32- ,
4 .
4.4BSD ( Berkeley )
1.
64000 0 9,5 . (
, 8 , 4 .)
, , , 64000.
ISN Host Requirements RFC.
: ISN [10].
TCP- - , TCP ( )
-, , .
33.

TCP .

(three way handshake,


, .1.44):

(SYN, Seq_Client=ISN MSS, Mss_Client),
(SYN_SENT).
7

7
4

, (SYN,
ACK Seq_Client+1=ISN +1,
Seq_Server=ISN Mss_Server), SYN_RECEIVED.
ACK Seq_Server+1=ISN +1
, ESTABLISHED,
ESTABLISHED.

. 1.44 TCP-

, ( SYN), , TCP reset (RST) SYN ACK,


. SYN-,
, SYN-,
RST. Firewall ,
.
TCP -,
, 75 . (BSD TCP.) ,
. , () , ,
.. TCP
SYN-, ,
- .
tcpdump :
1 -> : S 14:14 (0) win 4096 <mss 1024>
SYN
2 -> : S 18:18 (0) ack 15 win 4096 <mss 1024>
SYN
3 -> : . ack 19 win 4096
1 14:14 (0) , ISN 14,
0. , 15, :
SYN, FIN, RST, ,
, ,
. TCP .
1-2 4096 MSS 1024 .
SYN.
- , TCP- reset (RST)
SYN ACK, . .

7
5

. 1.45.

34.

TCP

() TCP- .
, .
, TCP
(). graceful close
.
. ,
. (.1.45).
( , -)
() , , ,
TCP- FIN ACK. ACK
,
.
, CK,
LOSE_WAIT FIN ACK,
(LAST_ ACK).
, FIN ACK , ACK-,
TIME_WAIT, , time-to-live.
, , .

TIME_WAIT TCP
TIME_WAIT [19][18]
TCP-.
, TIME_WAIT
, " " .. FIN-. ,
TCP- .
. 1.46 .
close(), TCP- FIN,
FIN_WAIT_1 ( FIN).
FIN , FIN_WAIT_2 (
7

7
6

FIN- ). FIN-,
TIME_WAIT.

. 1.46. TIME_WAIT

, -
. ,
TIME_WAIT MSL (MSL maximum segment lifetime),
TTL,
. , TIME_WAIT ,
.
:
, FIN-
, ,
TIME_WAIT.

? , - ,
, .
, , TCP
. , ACK ( ,
), FIN, ,
TIME_WAIT, RST. TIME_WAIT
,
. 2SL-,
TIME_WAIT .
, TIME_WAIT -
" ", ,
.
IP- , TCP

. , IP- , ,
-,
. TCP ,
SN , .
?
, TCP-

7
7

RST-. , RST- ,
.
,
, .
.
""
, , .
TIME_WAIT ,
, , , . ,
[19].
TIME_WAIT,
. RFC-1337,
, TIME_WAIT.
"" (
) , ,

.
RFC-1337 TCP ,
TIME_WAIT RST,
TCP-.
. 2.9.1
SO_LINGER TIME_WAIT.
, ""
TIME_WAIT .
l_linger linger , RST, ,
TIME_WAIT. TIME_WAIT. ,
,
TCP-.
TCP .
, , Netscape -. .
MS Internet Explorer (IE) - (
FIN-ACK ) RST,
, IE ...
. firewall SYN, reset',
SYN- ,
connect().
,
. .
.
, , , .
TCP ,
. , UNIX, , UNIX
, . TCP
-. ( )
.
"" (half-close).
TCP "".
"" , .
.
, FIN , ,
. - ,
.
7

7
8

,
, , .
TCP ,
.
TCP .
. , ,
.
, .
,
.
.
. 1.47

1
2
3
...

IP

IP

. 1.47.

. :

( ,
,
, . .).

IP-

IP . 0.0.0.0.

, , .

IP-

IP- .

Windows
(. 4.5.3)

8. UDP
TCP , .
. pooo User Datagram
Protocol (UDP ). , ,
Domain Name Service (DNS - ), Trivial File Transfer Protocol (TFTP
) Remote Procedure Call (RPC
). , ,
.
,
. UDP ,
. UDP TCP,
, TCP.
UDP . UDP- TCP. UDP- . 1.48.
, 16 .

(16 )

(16 )
7

7
9

(16 )

. 1.48. UDP

UDP- :

.
(, ), , , .

.
- ICMP
. TCP .


, TCP;
, . , ,
, ,
IP .
UDP_CHECKSUM (*nix) 0 (. 2.9.1),
. , UDP
"" , .
UDP
IP (.. 16- ), . ,
UDP ,
16- . ,
,
. , UDP TCP
-. 9.
UDP
UDP ,
UDP-. , UDP
p ,
. ,
, UDP-p
.
, ,
, UDP . ,
UDP-p .
,
.
. ,
, UDP p-
, IP-p , UDP-p.
UDP-
, IP-p , IP-,
UDP-. ,
-p .
, UDP,
(. 1.49). IP- IP-
IP-p ,
. (17 UDP)
UDP UDP-p ( ).
IP-,
.
7

8
0

. 1.49. UDP

, UDP,
, , , ,
. , .
, ,
, .
, , UDP ,
TCP/IP .

RFC-3828 "" (UDP-Lite), UDP,
,
(discard). ,
UDP-Lite c UDP.


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.

TCP ?
OSI TCP/IP?
.
, TCP.
? TCP
.

? .
,
TCP.
UDP.
TCP?
Next Header IPv6?
UDP? ?
MTU MSS? TCP-?
IP- 8?
IP-
?
ICMP?
ping traceroute? .
TTL IP, IGMP DNS?
TCP-? .
?
,
.
,
.
8

8
1

20.
21.
22.
23.

IP TCP? .
? ?
TCP-?
ACK ?

1. 2
- ,
Windows-
? ,
8

8
2

Delphi -
Delphi 6 Internet (TServerSocket TlientCocket) FastNet,
Indy Delphi 7. WINHTTP (-WinInet),
MFC-.
, ,
, .
, :

, (
, ),
VCL- .

,
,
.

Windows Socket, (
Winsock2.0) ,
/ Windows-
.

9.

(API Application
Programming Interface) , TCP/IP, :

(sockets API)

(TLI Transport Layer Interface).

, AT&T, XTI (X/Open Transport


Interface), , X/Open,
. XTI
TLI. 2.1 ,
.

. 2.1

,
.
(
) ,
.
8

8
3

UDP (User Datagram Protocol), TCP/IP, IPX,


Novell NetWare. "
" (connectionless).
.

,
, , ,
.

. ,
IP, .
, ,
. ,
, TCP SPX. NetBIOS (.
5.1) , ).
" " (connection-oriented).
.
(
NetBIOS) ,
. ,
.
(Application Programm Interface - API)
,
.
(ARPA)
TCP/IP UNIX- . .
-
TCP/IP (TCP/IP API). TCP/IP (TCP/IP
sockets) (Berkeley sockets) . 2.1.
BSD UNIX 4.1c 1982 .
, . 2.1 TLI/XTI,
*nix , NetBIOS,
, Windows
, ( NetBIOS
5.1). , NetBIOS
NetBEUI, "" TCP/IP ( , IPX/SPX
.)
(UNIX, LINUX, Free BSD, AIX,
MACOS, Windows 9-NT-2K XP) .
,
IPC, InterProcess Communication.
:

,
,
, ,
.


, (overlapped - Windows) /,
- ( ) ,
, , .
UNIX.
, Microsoft Windows, ,

8
4

(
, WindowsMe).
,
Windows, .
, , ,
, . , 2
(UNIX-).
( Windows).

10. -
,
- UNIX. TCP/IP
UNIX, UNIX
. ,
, .
Windows
,
UNIX " ".
UNIX .
, ,
, . , UNIX
. , ,
. UNIX
(file descriptor, fd).
, .
, , , ..
,
"".
- , - UNIX.
, ,
Open-Read-Write-Close. , "
", .
UNIX -
, - ,
.
, - , -
" "
.
- , ,
"-".
API - UNIX,
-, . API
-, . UNIX
- ,
-.
, - UNIX,
"" , " "
. , ()
-
. ( )
, .

. , , IP, 8

8
5

(IP-), .
- UNIX - " " - ,
.
, ,
- UNIX,
API ( ).
, ,
UNIX. , -
, , .
.
, UNIX,
, UNIX.
*nix- /++.

11.
.

, . ,
, ,
.
, ,
,
, , , . .
, ,
,
.
,
.
, . ,
UNIX, -
- UNIX.
:
, , , .
, TCP RFC 793, 2.7
"well-known sockets", "well-known numbers",

" "- . 1.7.2.

UNIX ( ),
(, , , ,
: ).
, . - ,
. , .
.
(),
.
. ,
API, .

. .

12.
(
) , (socket descriptor, sd) -
8

8
6

. ,
(endpoint),
-.
,
. , ,
,
. - ,
,
.
, TCP/IP
.
, -
. .
( IP) . TCP/IP UNIX,
-
, : API TCP/IP -,
.
, ""
(socket).
Socket (, ) - ,
.
TCP/IP , socket
(. ) .
Socket- /
, , :
1. ;
2. ;
3. (/);
4. .
,
.
- . ,
socket(), ,
. ,
() , .
UNIX ,
, .
socket():
int socket(int domain, int socket_type, int protocol);

sd = socket {address_family, sock_type, protocol);


sd (socket descriptor ), 1.
:
sd , fd .

, : ( ),
( ) . ,
, TCP/IP IPX/SPX.
:
(. .) 4.1 BSD
socket() 4 , , .

, , :
, . "protocol" ,
, TCP. socket()
.
8

8
7

errno() ,
. errno- :
EPROTONOSUPPORT
;
EMFILE
;
ENFILE
;
EACCESS
,
;
ENOBUFS
.
35.

TCP/IP ,
UNIX. TCP/IP, UNIX API .
, API TCP/IP, .
API
.

35.1.1.1.

, socket(), ,
, " ."

,
.
: , Windows
, UNIX- - ?
API,
.
. ,
.
,
, :

, .

,
.
-
. UNIX (path) UNIX, /dev/printer,
UNIX . UNIX
, , AF_UNIX.

(). PF_INET, ,
(Protocol Family) TCP/IP. , ,
"PF_". PF_UNIX UNIX, a PF_NS .
(Address Family) .
.
,
. ,
, "AF_".

, winsock2.h:

8
8

#define AF_UNIX
#define AF_INET
#define AF_IMPLINK
#define AF_PUP
#define AF_CHAOS
#define AF_NS
#define AF_IPX
#define AF_ISO
#define AF_OSI
#define AF_ECMA
#define AF_DATAKIT
#define AF_CCITT
#define AF_SNA
#define AF_DECnet
#define AF_DLI
#define AF_LAT
#define AF_HYLINK
#define AF_APPLETALK
#define AF_NETBIOS
#define AF_VOICEVIEW
#define AF_FIREFOX
#define AF_UNKNOWN1
#define AF_BAN
#define AF_ATM
#define AF_INET6
#define AF_CLUSTER
#define AF_12844
#define AF_MAX

1
2
3
4
5
6
AF_NS
7
AF_ISO
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

/* local to host (pipes, portals) */


/* internetwork: UDP, TCP, etc. */
/* arpanet imp addresses */
/* pup protocols: e.g. BSP */
/* mit CHAOS protocols */
/* XEROX NS protocols */
/* IPX protocols: IPX, SPX, etc. */
/* ISO protocols */
/* OSI is ISO */
/* european computer manufacturers */
/* datakit protocols */
/* CCITT protocols, X.25 etc */
/* IBM SNA */
/* DECnet */
/* Direct data link interface */
/* LAT */
/* NSC Hyperchannel */
/* AppleTalk */
/* NetBIOS-style addresses */
/* VoiceView */
/* Protocols from Firefox */
/* Somebody is using this! */
/* Banyan */
/* Native ATM Services */
/* Internetwork Version 6 */
/* Microsoft Wolfpack */
/* IEEE 1284.4 WG AF */

, AF_FILE, AF_UNIX AF_INET6.


AF_FILE ,
UNIX. PF_FILE .
AF_UNIX AF_FILE, . (PF_UNIX
PF_FILE.) AF_LOCAL.
AF_INET6 AF_INET, IPv6. PF_INET6
.
,
, . , TCP/IP
- (PF_INET) (AF_INET) .
, PF_INET, AF_INET
socket().
PF_INET AF_INET ,
, . ,
.
TCP/IP (), , : PF_INET
, AF_INET .
UNIX- <sys/socket.h>.
AF_MAX , ,
FreeBSD 32 , AF_MAX =33.
, , BSD, AIX, Solaris
AF_ROUTE,
(raw) (. 2.9) .

8
9

35.1.1.2.

DARPA- ""
( ) (
). .
UNIX ""
sockaddr,
, ,
<sys/socket.h> 16 . UNIX (kernel) (
Windows.)
struct sockaddr
{
u_short sa_family;
char
sa_data[14];
}

/* */
/* 14 */

sa_family

sa_data
2

14

. 2.2. sockaddr

. . 16 .
:
struct sockaddr
{
uint8_t sa_len;
sa_family_t sa_family;
char sa_data[14];
}

/* */
/* */
/* 14 */

sa_len (
TCP/IP ).
, ,
(sockaddr *) ,
C-.
uint8_t, sa_family_t _t ,
Posix.1g.(. 3.1.)

POSIX OSE (POSIX - Portable Operating System Interface for Computer Environments, OSE - Open
System Environment) (Portable Standards Committee)
IEEE (IEEE Computer Society). POSIX

(API) ().
POSIX
SystemV Release 4 Unix.

3.1 , Posix 1g

int8_t

8-

<sys/types.h>

uint8_t

8-

<sys/types.h>

int16_t

16-

<sys/types.h>

uint16_t

16-

<sys/types.h>

int32_t

32-

<sys/types.h>

9
0
uint32_t

32-

<sys/types.h>

sa_family_t

<sys/socket.h>

socklen_t

, uint32_t

<sys/socket.h>

inaddr_t

Iv4-, uint32_t

<netinet/in.h>

inport_t

TCP UDP, uint16_t

<netinet/in.h>

u_char, u_short, u_int


. Posix.lg , . ANSI size_t,
32- .
u_1ong,

c IPv4 sockaddr .
sockaddr_in (in Internet): sockaddr_in
UNIX- <netinet/in.h>.
struct sockaddr_in
{
short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
}

/*
/*
/*
/*

AF_INET */
(. 2.5.12)*/
. */
*/

sin_family

sin_port

sin_addr

sin_zero

. 2.3. sockaddr_in

, 4.2BSD, sin_addr
in_addr, (union),
IP- , :

u_char (4 ,

u_short (2*2

u_long

) S_un_b;

) S_un_w;

(4 , ) S_addr,
:

struct in_addr
{
union {
struct { u_char s_b1,s_b2,s_b3,s_b4; } S_un_b;
struct { u_short s_w1,s_w2; } S_un_w;
u_long S_addr;
}
}

S_un;

in_addr , unsigned
long.
, socket(),
TCP-, (
TCP):
Local IP

Remote IP

Local port
2

. 2.4. TCP

IPv6 sockaddr_in6:
struct sockaddr_in6

Remote port
2

9
1
{
short int sin6_family; /*
. AF_INET6.*/
struct in6_addr sin6_addr;

/* IPv6 -.*/

uint32_t sin6_flowinfo;

/* . */

uint16_t sin6_port;

/* . */

RFC-2133 ,
.
, . ,
, ,
. ,
(. connect(), bind()).
UDP TCP .
, ,
.
:
#include <sys/types.h> <sys/socket.h>.

IPX/SPX IPX- :
struct sockaddr_ipx
{
short sa_family;

/* AF_IPX */

char

sa_netnum[4];

/* */

char

sa_nodenum[6];

/* */

unsigned short sa_socket;


}

UNIX
UNIX, (, )
UNIX, 108 .
inode .
( unlink(), .
2.5.2). ,
.
UNIX, ( /tmp),
. UNIX
, . sockaddr_un
UNIX <sys/un.h>.
BSD :
struct sockaddr_un
{
short sun_family;
char sun_path[108];
}

/* AF_UNIX */
/* */ }

4.4 BSD :
struct sockaddr_un
{
u_char sun_len;
u_char sun_family;
char sun_path[104];
}

/* */
/* AF_UNIX */
/* */

1024 , UNIX,
, .

9
2

- (32 ).
- . 198.144.204.1.
, , .
" ", .
, garfield.cs.wisc.edu 128.105.1.3,
80690103 , 2154365187 .


,
. <sys/socket.h>.
:
SOCK_STREAM - ;
SOCK_DGRAM - ;
SOCK_RAW
- .
Linux
:

SOCK_RDM
(reliably-delivered message - ).
.
SOCK_PACKET .
SOCK_SEQPACKET ( ).
, SOCK_STREAM. ,
read() ,
.
.
SOCK_STREAM SOCK_DGRAM.
. [19] (
), UNIX
- AF_ROUTE, UNIX-like .

protocol
socket() .
, .
TCP/IP IPPROTO_. , TCP
IPPROTO_TCP, IPPROTO_UDP
UDP. , socket() :
sd = socket (F_INET, SOCK_STREAM, IPPROTO_TCP);

,
(F_INET), TCP (IPPROTO_TCP) ,
(SOCK_ STREAM).
0, TCP/IP
.

socketpair()
" " ,
UNIX socketpair(),
:
#include <sys/socket.h>
int socketpair(int domain, int type, int protocol, int socket_vector[2]);

. ,
, socket _vector [0] socket _vector [1].
AF_LOCAL, 0.
SOCK_STREAM, SOCK_DGRAM. SOCK_STREAM " " stream pipe.
9

9
3

, , . ,
SOCK_SEQPACKET,
, , .
, ,
, ,
. MSG_EOR.
, . - "" ,
. -,
, .
( *nix-). "
" "-IP-",
, , . ,
, "-IP-"
. , , IP-
. IPC , IP-
, .
"-IP-" , "" .
,
.
. , ,
AF_INET. UNIX, , AF_UNIX.
. ,
, , .
, .
UNIX .
UNIX .
.

13.
36.

connect()

,
, .
(point-to-point) .
, TCP ( )

(
), .
- TCP/IP ,
. - .
-
.
-
connect(). connect()
,
( )
. connect():
int connect(int sockfd, const struct sockaddr *serv_addr, int addrlen);

res = connect(sd, name, namelen);, sd , name


( ), namelen ,
0 ( ),
. 1, , name
.
const ,
"-" .
9

9
4

" "
, ,
.. - connect() TCP-
" ".

, ()
RST (ECONNREFUSED),

,
;

TCP
;

TCP .

, connect() (-1)
. ,
, :
EADDRNOTAVAIL ;
EAFNOSUPPORT

EINPROGRESS

- ,
;

EALREADY

-
;

EBADF

ENOTSOCK

EISCONN

EADDRINUSE

ETIMEDOUT

,
, ;
, "server is down",
;

ECONNREFUSED

.
- ;

ENETDOWN
EHOSTDOWN

,
;

ENETUNREACH
EHOSTUNREACH
( ), -
,
.
,
.
:
. 2.5.9

,
,
.
connect(), ,
socket(). ,
. ,
.

9
5

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

.
connect(), ,
( ), . (
) ( ,
). , ,
. connect(),
, ,
" ".
connect() ,
TCP- (
.)

, UDP (. ) (raw) ,
send() recv(), ..
connect() bind() (. 2.5.5).
.
, - ,
connect(), ,
socket().
:
TCP- SYN-
connect(), (, 5,8 ., 24 . )
, 75 . ( 4.4BSD, 45 . - Windows) connect()
. , connect()
"" .

37.

bind()

connect() .
, .
, .

.
- ( ) .
-, ,
,
. , ,
, -, ,
.
bind()
( ) .
int bind(int sd, const struct sockaddr *name, int addrlen);

9
6

sd , name ,
.
, . 2.1.
addrlen .
IP- INADDR_ANY ( = 0)
, . INADDR_ANY
" ",
. bind()
, ( INADDR_ANY),
.
INADDR_ANY , IP-
; , ,
-. Linux, bind()
INADDR_ANY,
. INADDR_LOOPBACK (127.0.0.1)
. INADDR_BROADCAST - 255.255.255.255
.
,
1024-5000 (
). bind() getsockname() (. 2.5.13),
.
:
IPv6 INADDR_ANY .

res=bind(sd, name, addrlen);

0 (res = 0), res = -1.


bind(),
- , FTP, HTTP,
(
UDP-) .
errno :
EBADF
ENOTSOCK
EADDRNOTAVAIL
EADDRINUSE
EINVAL
EACCESS

;
;
;
, ;
;
.


Berkeley 0IPPORT_RESERVED-1.
.
2.1 bind() UNIX:
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <iostream.h>
#define NAME "socket"
int main(void) {
int sd, length;
struct sockaddr_un name; // name - a UNIX-

9
7
char buf[1024];
//
// UNIX,
sd = socket(AF_UNIX, SOCK_DGRAM, 0);
if(sd<0)
{
cerr<<" \n";
exit(1);
}
// UNIX-
name.sun_family = AF_UNIX;
strcpy(name.sun_path,NAME);
if(bind(sd,&name,sizeof(struct sockaddr_un))<0)
{
cerr<<" \n";
exit(1);
}
cout<<"socket -->"<<NAME<<"\n";
if (read(sd, buf, 1024) <0)
//
cerr<<" \n";
cout<<"-->"<<buf<<"\n";
//
close(sd);
//
// unlink() .
unlink(NAME);
}

UDP-,
, (.. connect() ), bind()
? - bind() UDP . UDP
, .
, ,
bind().
, , UDP-, , bind()
connect()?
-, " ", .. UDP . -,
(IP-
), connect(), connect()
. "", UDP
"" .
"" UDP-
(. 2.5.5).
38.

listen()

, . -,
, .
, ,
. ,
.
, ,
, .
() ( )
. , .
UNIX (lightweight processes), Windows
(threads). . 2.5 ) ,
. 2.5 ) . 3-4
, .
3
(, UNIX- fork(),
9

9
8

TCP-), (), ,
.
. - ( -)
.
.
,
"" , ..
. ,
. ,
, , ,
, . , TCP
(), UDP .

. 2.5.

, ,
() ()?
. ,
, .
listen().
listen() ,
"" . ,
, , ,
, .
, "listen - " . listen()
" ". -
,
"" .
:
, "" ,
-.

: ""
. ,
. listen() :
9

9
9
int listen(int sd, int backlog);

sd , backlog
( , ,
5). .
.
,
, .
, TCP
- . backlog 0
( 0, 1).

TCP/IP backlog .

, , .
, , -
, .
, listen() ,
TCP UDP .
TCP- listen() :

- (.. ,
handshake);

- (.. ,
handshake
).

backlog,
1 , (
).

2.12.
, , (UDP),
, -/ (
, recvfrom()). , .
listen() 0 1 .
39.

accept()

, bind()
() . -
connect() ,
. , ,
. , connect() bind()
.
, ,
. , bind(),
.
accept(), , listen().
accept():
int accept(int sd, struct sockaddr *client_addr, int *addrlen);

sd , ( , listen()),
client_addr ( , NULL)
, , addrlen
. NULL addrlen .

1
0

accept() .
, TCP.
, accept() .
, newsd = accept(sd, addr, addrlen);
, (!) , sd,
newsd . accept(),
IP TCP , IP-
( ) .
-1.
accept(),
, .
, accept()
.
accept(),
connect() ,
.
40.

,
.

send()

.
.

write()

.
.

writev()

.
.

sendto()

.
.

sendmsg()

.
.


sendto() recvfrom() TCP,
. sendto() TCP-
- to tolen - .

,
, .
(IP- )
.
,
, . send(), write() writev()

. ,
. writev(), write(),
, .
writev() , .
write():
size_t write(int sd, const char *message_buffer, size_t buffer_length);

. write() ,
, .
1

1
0

, .
, .
, 1
errno.
writev():
size_t writev(int sd, const struct iovec *io_vector, int vector_length);

. , , . ,
.
; . writev() ,
.
, .
writev() , .
, writev() -,
, .

, , .
.2.6 -.
/ scatter-gather I/O.

readv()/writev() sys/uio.h.

, 1
errno.

. 2.5. , writev()

write() ,
, writev(). ,

, writev(). send() ,
. send():
int send(int sd, const void *buf, int buflen, unsigned int flags);

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

1
0

MSG_DONTROUTE. c ,
, .
MSG_DONTWAIT. , -
,
, - .
MSG_OOB. send() , .
TCP 1 .
recv() ,
. , Telnet
Ctrl+C. -
( , RFC793 RFC1122).
.
:
, send() ,
, ,
. ,
. ,
( TCP/IP).

:
MSG_PEEK. , MSG_PEEK,
.
. MSG_PEEK recv()
recvfrom() (..
).
, , FTP. ,
TCP .
MSG_WAITALL. 4.3BSD Reno. ,
,
.
:
, MSG_EOR (OSI )
MSG_EOF (T/TCP).

write(), writev() send() res


. ,
. - res
buflen.
-1.
errno ,
.
,
: sendto() sendmsg().
. sendto()
. , send(). , ,
. , ,
. ,
,
recvfrom() c. . sendto():
sendto(int sd, const void *message_buf, size_t buf_length, int special_lags, const struct
sockaddr *socket_address_structure, socklen_t address_structure_length);

"" UDP. connect(),


UDP-, ,
sendto() ,
socket_address_structure, - . , sendto()
. , ,
:
res = sendto(sd, message_buf, buf_length, special_lags, NULL,0);

1
0

, recvfrom() (. ) recv().

, UDP connect(), "
" , TFTP. DNS
UDP, DNS- connect().

sendmsg() ,
.
sendmsg(). ,
:
res = sendmsg (sd, message_structure, special_f lags);


. sendmsg() writev() ,
.
, writev(),
. . 2.7 , sendmsg().
0

31



/
/

. 2.7. , sendmsg()

(, 4.4BSD) .
41.

, .
: read(), readv(), recv(), recvfrom(), recvmsg() ,
. , recv() send()
, recv() , a send() .
writev() readv(). writev() ,
readv() . ,
.
recvfrom() recvmsg() sendto() sendmsg(). . 2.1
:
2.1.

send()

recv()

write()

read()

writev()

readv()

sendto()

recvfrom()

sendmsg()

recvmsg()

,
, . ,
1

1
0

TCP .
, .
, .
: recv(), read() readv().
.
, ,
readv().

"" , 1.
- , ..
, recv()
.
"-"
, - , recv() ,
send(). , send() 1 .
:
k=recv(sd,file,1024*1024,0);
if(k!=1024*1024)
{

.....
}
recv() 1 !
recv() TCP ,
message_buffer, buffer_length .
. ,
. ,
, recv().
recv() , , TCP
,
. recv() 0, ,
.
(, - ),
(.. 1).
TCP/IP.
:

EBADF
ENETDOWN
ENOTCONN
EINTR
EFAULT
ENOTSOCK
ESHUTDOWN
EWOULDBLOCK
EAGAIN

sd .


,
.

.

shutdown()
,

,
,


-
1

1
0

EINVAL
ECONNABORTED
ECONNRESET

, - ,
.
bind()
-

recvfrom().
UDP , ? recvfrom():
recvfrom(int sd, void *message_buf, size_t buf_length, int special_lags, struct
sockaddr *remote_socket_address_structure, socketlen_t *address_structure_length);

UDP , ,
remote_socket_address_structure, ,
"sys/socket.h".
/ ,
API /
. select(),
, SO_RCVTIMEO
SO_SNDTIMEO,
2.9.1.
42.

select()

,
"select()". select()
*nix-. select():
int
select(int
number_of_sockets,
fd_set
*readable_sockets,
*writeable_sockets, fd_set *error_sockets, struct timeval *timeout);

fd_set

select() . ,
(number_of_sockets), (
, 64).
readable_sockets, writeable_sockets error_sockets
fd_set, .
(readable_socket) ,
recv() recvfrom().
, (writable_socket) , .
, send() sendto().
select() , ,
(exception) error_sockets.
.
number_of_sockets 1
, UNIX .
:
Windows- - number_of_sockets
0.

select(), timeval
:
struct timeval
{
int tv_sec;
int tv_usec;
};

/* */
/* */

,
UNIX- 100 , .

1
0
timeval

0, select() timeout ,

timeout NULL, timeout


, - , ..
.
select():
res = select (number_of_sockets, readable_sockets, writeable_sockets, error_sockets,
timeout);

res >0 "" ;

res = -1 (, -
;)

res = 0 -
.


.
select() /
- ,
a . 2.8:

. 2.8

, , recvfrom(). , :

( ),
recvfrom()
( );

, recvfrom()

.
recvfrom().

, , "" .
.
select() ,
, ,
select(). select()
.
select() ,
. select() res
, - .
, select() ,
. select(), ,
, - . ,
, , , -
(, ). select()
, .
1

1
0

select(), ,
, . select()
, , -.
select()
.
select(), ,
. ,
. , , ,
, , , .
select() ,
, , ,
, . ,
, .
, long integer
; FD_SETSIZE. UNIX-
FD_SETSIZE 64 ( 256).
select() " /". ?
, ()

.
( [19]), (
, ) - .
1. , :

low water-mark (
setsockopt() SO_RCVLOWAT, . 2.9.1)
. TCP UDP low water-mark 1.
,
( , ).
TCP- ( FIN).
(
).
(TCP), .
, .
(-1) rrn c .
, , , getsockopt()
SO_ERROR (. 2.9.2), .
2. , :


, (UDP).
, ,
(, ,
).
SO_SNDLOWAT.
2048 TCP UDP.
, , .
SIGPIPE.
, .
(-1) rrn,
. , , ,
getsockopt() SO_ERROR.
3. , , ,
(out-of-band)
.
1

1
0


3 :
- SIGIO: , -.
, ;
- SIGURG: , -. ,
;
- SIGPIPE: , . , .

SVR3-4 select() poll(),



.
43.

, ""
( - fd).
- fd_set. :
FD_ZERO (fd_set *set)

FD_SET (int fd, fd_set *set)

fd

FD_CLR (int fd, fd_set *set)

fd

FD_ISSET (int fd, fd_set *set)

fd

2.2 , "" 2.5 , "-"


STDIN ( ):
2.2

#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
#define STDIN 0
/* */
main ()
{
struct timeval tv;
fd_set readfds;
tv.tv_sec = 2;
tv.tv_usec = 500000;
FD_ZERO(&readfds);
FD_SET (STDIN, &readfds);
/* writefds errorfds */
select (STDIN+1, &readfds, NULL, NULL, &tv);
/* Enter*/
if (FD_ISSET (STDIN, &readfds))
printf (" ! \n ")
else
printf ("Timed out \n ");
}

number_of_sockets
, sockfd+1,
, STDIN,
fd = 0 , Windows- , ..
.
2.3 sd1
sd2:
2.3
#include <sys/time.h>
#include <sys/types.h>

1
0
fd_set read_sd;
struct timeval wait;
int sd1,sd2,nb;
...
for (;;)
{
wait.tv_sec = 1; /* */
wait.tv_usec = 0;
FD_ZERO(&read_sd);
FD_SET(sd1, &read_sd);
FD_SET(sd2, &read_sd);
nb = select(FD_SETSIZE, &read_sd, (fd_set *) 0, (fd_set *) 0, &wait);
if (nb <= 0)
{
printf ("select , select timeout.\n");
}
if (FD_ISSET(sd1, &read_sd))
{
printf (" 1 .\n ");
}
if (FD_ISSET(sd2, &read_sd))
{
printf (" 2 .\n ");
}
}

select() . ,
, listen() "" ,
, ,
readable_socket.
,
( )
.
,

,
timeval=0.
44.

- UNIX-
, , ,
[19].
/.

/ .
?
connect() .2.9.

1
1

. 2.9 connect()

connect()
, ()
connect() .
connect() timeout (
, timeout ),
" " ,
.
,
: connect(), accept(), write(), send(), read()
recv() . . .
.
, recv()
TCP-,
-
.
: recv(),
, -
. , ,
.
- recv() ""
, ""
, - , , read() recv(),
,
, (, ).
select() .
, "" recv(),
select() -
TCP .
( ), .
, .
2.4 ReceiveNBytes()
int ReceiveNBytes(int sd, char *pBuffer, int iStillToReceive)

1
1
{
int
iRC
= 0;
int
iReceiveStatus
= 0;
timeval ReceiveTimeout;
fd_set fds;
FD_ZERO(&fds);
FD_SET(sd, &fds);
ReceiveTimeout.tv_sec = 0;
// 0,5.
ReceiveTimeout.tv_usec = _500000;
//.. ..
while(iStillToReceive > 0)
{
//
iRC = select(0, &fds, NULL, NULL, &ReceiveTimeout);
//
if(!iRC) return -1;
// - select()
if(iRC < 0) return WSAGetLastError();
//
iReceiveStatus = recv(sd, pBuffer, iStillToReceive, 0);
// recv()
if(iReceiveStatus < 0)
{
return WSAGetLastError();
}
else
{
//
iStillToReceive -= iReceiveStatus;
pBuffer += iReceiveStatus;
}
}
return 0;
}

.
, . UNIX-
.
( /)
,
, /
.
/ :
( ), ,
.
:
. , , recv() read(),
,
select().
connect(), , . .
select(). ,
, connect() ,
. connect()
,
.

1
1

/, , UNIX- ,
/,
(InterProcess Communication - IPC), ..
, .
, " signal.h ".
/ ,
SIGIO. :
1. ,
( , ) SIGIO.
sigaction() signal().
2.
(, recvfrom().)
3. ,
SIGIO,
recvfrom(), ,
. .
"" / Posix.1g
UNIX- .
, ,
. / Posix.1g
aio_ [19].
45.

ioctl() fcntl()

,
ioctl() ( FIONBIO) fcntl() ( FNDELAY, BSD
O_NDELAY System V). (ioctl input/output control, fcntl file control)
UNIX-
/ , ,
: , . ""
.
:
#include <sys/ioctl.h>
int ioctl(int sd, int cmd, char *argp);

sd , cmd ,
, argp ().
ioctl()
. , , ,
, . cmd argp
,
. ioctl()
(, ).
. cmd
, , argp .
, cmd, <sys/ioctl.h>.
ioctl() (
Linux/i386 421 .)
ioctl()
, fcntl()
- - cmd.
#include <unistd.h>
#include <fcntl.h>
int fcntl(int fd, int cmd);
int fcntl(int fd, int cmd, long arg);
int fcntl(int fd, int cmd, struct flock *lock);

, UNIX-like .
1

1
1

2.2 fcntl() ioct1(),

fcntl()

F_SETFL

-, F_SETFL

ioct1()

O_NONBLOCK

FIONBIO

O_ASYNC

FIOASYNC

F_SETOWN

SIOCSPGRP FIOSETOWN

F_GETOWN

SIOCGPGRP FIOGETOWN


TCP

FIONREAD

SIOCATMARK

,
,
.
,
fcntl() .
, ,
/ /, ,
FNDELAY FASYNC fcntl().
fcntl()
:

/.
_NONBLOCK, F_SETFL .

/.
_ASYNC, F_SETFL, SIGIO,
.

F_SETOWN , (
) SIGIO SIGURG.
, /,
(out-of-band) .
:
O_NONBLOCK .
FIFO . , open()
, " ". O_NONBLOCK, open() . O_NONBLOCK
: ,
, , .


. TCP- sd F_SETFL
O_NONBLOCK.
#include <fcntl.h>
#include <unistd.h>
sd = socket (AF_INET, SOCK_STREAM, 0);
fcntl (sd, F_SETFL, O_NONBLOCK);

accept() EWOULDBLOCK;
connect() EINPROGRESS;
,
;
1

1
1

recv(), read() recvfrom() -1 ( FIONBIO FNDELAY


ioctl()) 0 (O_NDELAY- fcntl()) ;
EWOULDBLOCK EAGAIN.
connect()
[4].
:
if(connect(sd, (sockaddr*)&serv_addr, sizeof(serv_addr)) != 0)
{
/* , , .*/
/* errno */
if(errno == EINPROGRESS)/* EINPROGRESS ,
*/
{
...
}
else
{
/* . */
}
}
else
{
/* connect(),
.*/
}


(, select() sd connect()).
2.5
.
.
fd_set rsds, wsds;
struct timeval tv;
tv.tv_sec = 0; tv.tv_usec = 500;
FD_ZERO(&rsds);
FD_ZERO(&wsds);
int max_sd = -1;
/* . ,
handshake TCP- (SYN), (ACK)
*/
FD_SET(sd, &wsds);
FD_SET(sd, &rsds);
if(sd > max_sd) max_sd = sd;
select(max_sd+1, &rsds, &wsds, NULL, &tv);
/* select() -
, . , , ,
getsockopt() (. 2.9.2) */
if(FD_ISSET(sd, &wsds) || FD_ISSET(sd, &rsds))
{
socklen_t err_len;
int error;
err_len = sizeof(error);
if(getsockopt(sd, SOL_SOCKET, SO_ERROR, &error, &err_len) < 0 || error != 0)
{ /* .*/ }
else
{ /* . */ }
}
.
.


sd,
(return(0)) .

1
1

, :
1. int flags,sd;

2.

/* .
, */
flags=fcntl(sd,F_SETFL,0);
fcntl(sd, F_SETFL, fcntl(sd, F_GETFL, 0) & ~O_NONBLOCK);

fcntl()
. &
.
Posix.
getsockopt()
connect() ( [19]) :
1. connect(). ,
EISCONN,
.
2. read() c buf_len=0.
connect() , read() ,
0. read() .
3. getsockopt() getpeername() (. 2.5.13.3),
ENOTCONN ( ),
getsockopt().
,
/ .
,
/ .
/.
UDP- c recvfrom()
.
, recvfrom() ,
,
-1, errno EWOULDBLOCK.

. 2.10 UDP

, (
) ,
1

1
1

.
. 6.
46.

/
. , ,
, .
1.7.12. ,
, .
, ,
, , , TCP-
.
, ,
, , .
, ,
, ,
. ,
, , .

, EOF.
close(),
: close(sd); sd .
, " ", ,
close() sd, ,
, , - . ,
, TIME_WAIT.
close()
(. 1.7.13).
API UNIX-
shutdown(), close() , ,
, - .
#include <sys/socket.h>

/* UNIX */

int shutdown( int sd, int how );


#include <winsock.h>

/* Windows */

int shutdown( SOCKET sd, int how );

: 0- ; -1 (UNIX) SOCKET_ERROR (Windows) .


, shutdown() UNIX Windows
API. UNIX-like how
shutdown() , Posix.1g
WinSock , - . 2.2.
2.3. how shutdown()
UNIX

Windows

Posix.1g

SD_RECEIVE

SHUT_RD

SD_SEND

SHUT_WR

SD_BOTH

SHUT_RDWR

.
how=0. .
EOF,
- .
,
shutdown(), - TCP
.

1
1

UNIX , ( -
) , .
, TCP- ACK-
, .
WinSock
,
. , shutdown(sd,0) Windows .

how=1. . ,

.
, TCP FIN, , .
(half close) " ".
shutdown() , (*nix
Windows).

how=2. , shutdown()
, how=0, how=1.

shutdown(sd,2) close() closesocket()


WinSock API Windows, . shutdown()
how=2 , Windows- closesocket()
, shutdown() how=2.
WinSock shutdown() how=2 ,
how=0 .
close()
shutdown(). shutdown() -,
2. , (
how=0 2) .
, shutdown() ,
(, fork()).
shutdown() how=1 .
close() Windows- closesocket()
.
( ) ,
shutdown() 0 1 close().
shutdown() how=1, ,
EOF, .
close() closesocket() , TCP FIN-,
.. .
shutdown() UDP-. shutdown()
how=1 2 , , ,
how=0 UDP-.
shutdown() (orderly release)
, ,
(. .2.11)

1
1

. 2.11. close() ) shutdown() )

TCP - -.
. 2.11 TCP-, "" .
ACK-. , ,
close() FIN-, ,
-1. ACK FIN
. -1 TCP-
RST ( ) .
. 2.11 TCP-,
shutdown() c how=1 (
) FIN-. ,
. ,
, .
:
TCP- - ,
/
TCP .



. ,
" ",
. UNIX lsof,
. , , UNIX -
, , ,
.
1

1
1

Once the application is in the ESTABLISHED state, there are two paths for closure. If your application
initiates the closure, it is known as an active socket closure; otherwise, the socket closure is passive. Figure
1-2 illustrates both an active and a passive closure. If you actively initiate a closure, your application sends a
FIN packet. When your application calls closesocket() or shutdown() (with SD_SEND as its second
argument), your application sends a FIN packet to the peer, and the state of your socket changes to
FIN_WAIT_1. Normally, the peer responds with an ACK packet, and your socket's state becomes
FIN_WAIT_2. If the peer also closes the connection, it sends a FIN packet and your computer responds by
sending an ACK packet and placing your socket in the TIME_WAIT state.

47.

" "
? " ",
, .
4 ,
(hosts), (networks), (protocols)
(services).

UNIX /etc/hosts, /etc/networks/, etc/protocols /etc/services. UNIX
,
"",
, . .
<netdb.h>.
:



( )
( )
( )
( )


,
:
gethostbyname() gethostbyaddr().
gethostbyname()
- hostent:
struct hostent *gethostbyname(const char *host_name);

gethostbyname("www.microsoft.com").
:
gethostbyname2(),
.
DNS (IPv4)
(IPv6), ,
CNAME.
gethostbyaddr() hostent:
struct hostent *gethostbyaddr(const char *inaddr, int inaddr_type);

. , inaddr, -
, - , - 192.145.38.56. ,
inaddr_type, ; ,
inaddr_type AF_INET. IPv6,
size_t
1

1
2

.
hostent. DNS PTR
(IPv4 IPv6).
hostent :
struct hostent
{
char *h_name;
char **h_aliases;
int h_addrtype;
*/
int h_length;

/* .*/
/* , */
/* ; AF_INET

/* . AF_INET 4
*/
char **h_addr_list;
/* IPv4 (IPv6) .
, . */
#define h_addr h_addr_list[0]/* h_addr */
};

, gethostbyaddr() gethostbyname() ,

, .
, , name
() .
UNIX- /etc/hosts.
DNS (Domain Name Service),
DNS. -
, . /etc/hosts
gethostbyname(), , . DNS
, ,
.
hostent .
,
.
API . ,

, - .
API , ,
, , :
API , ,
, ,
, .
gethostbyname() gethostbyaddr() ,
h_errno, errno!
h_errno, :
extern int h_errno;

, h_errno:
HOST_NOT_FOUND

TRY_AGAIN

,
. .

NO_RECOVERY

NO_ADDRESS NO_DATA


, -.

1
2

gethostbyaddr() gethostbyname()
, DNS. ,
, , .
DNS,
.
:
, .
- ,
.
gethostbyaddr() gethostbyname() ( getXXbyYY()) .

"" (resolver).
. . [19]
:
,
IP- , .
UNIX ,
, gethostbyaddr() gethostbyname()
. , sendmail,
DNS- MX,
.
_res. ,
DNS- , [24],
.

sethostent(), gethostent() endhostent()


,
sethostent(), gethostent() endhostent(). ,
, (hosts ..).

( ).
sethostent (int stayopen);

. gethostent()
. stayopen , ,
gethostbyname() gethostbyaddr() (
).
struct hostent *gethostent();

.
, .
endhostent();

.
,
:
2.6
#include <stdio.h>
#include <netdb.h>
int main (void)
{
struct hostent *pe;
int i, j;
char *pstr;
sethostent (1);/* */

1
2
while ((pe = gethostent()) != NULL)
{
printf (" : %s\n", pe->h_name);
printf (" :\n");
for (i = 0; (pstr = pe->h_aliases[i]) != NULL; i++)/* NULL */
{
printf (" %s\n", pstr);
}
printf (" : %d\n", pe->h_addrtype);
printf (" : %d\n", pe->h_length);
printf ("IP- :\n");
for (i = 0; (pstr = pe->h_addr_list[i]) != NULL; i++)
{
for (j = 0; j < pe->h_length; j++)
{
printf (" %d", (unsigned char) pstr[j]);
}
printf ("\n");
}
}
endhostent ();/* */
return 0;


, Compuserv, AOL, Swift, FidoNet, Relcom . .
getnetbyaddr() getnetbyname(),
() . ,
, , .
getnetbyaddr() getnetbyname()
/etc/networks netent ( net entry
) :
struct netent
{
char
char
int
in_addr_t
};

*n_name;
**n_aliases;
n_addrtype;
n_net;

/*
/*
/*
/*

*/
*/
*/
*/

, .
:

setnetent(stayopen)
.
stayopen int , ,
getnetbyname() getnetbyaddr() .
getnetent()
/etc/networks,
.
endnetent()
.

getprotobynumber(protocol), getprotobyname(name),
. /etc/protocols
protoent :
1

1
2
struct protoent
{
char *p_name;
char **p_aliases;
int p_proto;

/* */
/* */
/* . protocol
socket() */

};

, .
setprotoent(stayopen)

getprotoent()
/etc/protocols,
.
endprotoent()

. socket()
protocol , ,
, .

()
Service database database-
.
getservbyname() getservbyport(),
. /etc/services.
servent :
struct servent
{
char *s_name;
char **s_aliases;
int s_port;
char s_proto;
};

/*
/*
/*
/*

*/
*/
,
*/

*/

getservbyname():
struct servent *getservbyname (const char *servname, const char *proto);

getservbyname() ,
proto. ,
. , ; ,
, -
, DNS
UDP TCP. , . ,
Telnet-,
:
servname,

sp = getservbyname ("telnet", (char *) NULL );.

, Telnet-, TCP
:
sp = getservbyname ("telnet", "tcp");
2.7 getservbyname()
struct servent *se;
...
if ((se = getservbyname("daytime", "tcp")) == NULL)
{
fprintf(stderr, " , .\n");
}

getservbyport():
struct servent *getservbyport (const char *port, const char *proto);

1
2

getservbyport() port,
() proto. port
. , :
2.8 getservbyport()
struct servent *se;
...
if ((se = getservbyport(htons(53), "udp")) == NULL)
{
fprintf(stderr, " ,

.\n");

,
. ,
. ,
.
?
.
, - .
,
Internet Assigned Numbers Authority (IANA).
,
. . ,
.

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

utsname,
, :
#define _UTS_NAMESIZE 16
#define _UTS_NODESIZE 256
struct utsname
{
char sysname[_UTS_NAMESIZE ];
char nodename[_UTS_NODESIZE ];
char release[_UTS_NAMESIZE ];
char version[_UTS_NAMESIZE ];
char machine[_UTS_NAMESIZE ];
};

48.

/* , 4.4BSD */

/*
/*
/*
/*
/*

*/
*/
*/
*/
*/



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

" " - "big-endian". ""
, " network
byte order".
IBM- -
"" ,
1

1
2

- . " ",
- "litle-endian". Motorolla
.
, 247 :

247 - ;

742 - .

,
" host byte order".
, ,
-
, - .
, getservbyname() gethostbyname() inet_addr()
, ,
sockaddr_in.
.
htons() ntohs(), sin_port. htonl()
ntohl(), sin_addr. (, struct in_addr
long unsigned int.) "netinet/in.h".
unsigned short int htons (unsigned short int hostshort);

hostshort .
unsigned short int ntohs (unsigned short int netshort);

netshort .
unsigned long int htonl (unsigned long int hostlong);

hostlong .
unsigned long int ntohl (unsigned long int netlong);

netlong .



32- IPv4.
<arpa/inet.h>.
inet_addr() - , ,
32- IPv4- :
in_addr_t inet_addr(const char *addr_str);

:
ina.sin_addr.s_addr = inet_addr ("132.241.5.10");

INADDR_NONE .
inet_ntoa()
-
, ("ntoa"
"number to ascii"):
char *inet_ntoa(struct in_addr char inaddr);

:
printf ("%s", inet_ntoa (ina.sin_addr));

, inet_ntoa() IP-
IP- - .
:
1

1
2
2.9 inet_ntoa()
struct inaddr_in inaddr1,inaddr2;
char *addr1, *addr2;
.
.
addr1 = inet_ntoa (inaddr1.sin_addr); /* , 200.155.122.110 */
addr2 = inet_ntoa (inaddr2.sin_addr); /* , 198.201.6.20 */
printf (" 1: %s\n ", a1);
printf (" 2: %s\n ", a2);

:
1: 198.201.6.20
2: 198.201.6.20
, strcpy()
.
IPv6 ,
IPv6 IPv4 inet_pton() inet_ntop().
presentation ( ), n number (
).
int inet_pton(int addr_family, const char *addr_str_ptr, void *addr_prt);

: 1- , 0
, -1 .
const char inet_ntop(int addr_family, const void *addr_prt, char *addr_str_ptr,
size_t len);

: , NULL .
:
inet_lnaof()

- - .

inet_makeaddr() - .
inet_netof ()

- .

inet_network()

.

getpeername() getsockname().
"get",
getpeername() getsockname().
"sys/socket.h".
int getpeername (int sd, struct sockaddr *addr, size_t *length_ptr);

getpeername() sd
,
sockaddr, addr length_ptr.
*length_ptr. length_ptr
, addr. ,
(). ,
. getpeername() 4.2BSD.
:
"peername" , "" ,
() . " ()"
, - .

0 , :
1

1
2

EBADF

- sd - .

ENOTSOCK

- - .

ENOTCONN

- .

ENOBUFS

- .

UNIX- , fork(),
,
, , ,
, , [20].
fork() exec()
, ""
.
:
fork() , exec()
" " ,
, .

, "" ,
, , , Telnet
inetd() . 2.8.
, exec() (
) ,
exec()
,
,
0,1 2, inetd().
2.9.
2.10
#include
#define BACKLOG 5
.
.
int
listensd, acceptsd;
sock1en_t
client_len;
struct sockaddr_in server, client;
/* IPv4 */
listensd = socket(AF_INET, SOCK_STREAM, 0);
/* IPv4 */
/* server{} */
.
.
bind(listensd, &server, sizeof(server));
/* */
listen(listensd, BACKLOG);
/* */
for ( , , ) {
client_len = sizeof(c1ient);
acceptsd = accept(listensd, &c1ient, &c1ient_len);
if (fork() == 0)
{
close(listensd);
/*
*/
/*
*/
dup2(acceptsd, STDIN_FILENO);
/* */
dup2(acceptsd, STDOUT_FILENO);
/* */
dup2(acceptsd, STDERR_FILENO);
/* */
close(acceptsd);
/* acceptsd */
xec();
/* */

1
2
}
close(acceptsd):
}
.
.

/* */

:
STDIN_FILENO, STDOUT_FILENO STDERR_FILENO Posix1
UNIX- 0,1 2 (STDIN, STDOUT STDERR).

, 3
? , , TCP-
, .. , STDIN
, STDOUT- ,
STDERR .
getpeername().
,
, , .
getsockname()
int getsockname (int sd, struct sockaddr *addr, size_t *length_ptr);

getsockname() ,
addr length_ptr. , length_ptr ;
addr,
.
.
:
1. connect()
TCP, bind(), getsockname()
IP- , .
2. TCP- bind(),
.
3. TCP, bind() IP INADD_ANY, (
accept() ), getsockname(),
IP- . sd ( )
, .
get getaddrinfo()
getnameinfo(), Posix.1g. getaddrinfo(),
, addrinfo.
IPv4 IPv6
, , .
[19]

14. UNIX-like /
- TCP-
-,
TCP- (. 2.12)
. read() write() send() recv().

1
2

. 2.12. TCP- -

TCP-
,
. TCP. , , :



TCP- ( )
( )

. TCP-
, , 3490 (
, 1024). :
Tcp_client.exe www.aport.ru .
numbytes,
.
2.11 UNIX TCP-
#include <stdio.h>
/* */
#include <unistd.h> /* */
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <netdb.h>
#define port 3490
/* (),
*/

1
3
#define MAXDATASIZE 100 /* , */
int main( int argc, char *argv [])
{
int sd, numbytes;
/* */
char buf [MAXDATASIZE];
/* */
struct hostent *he;
/* he hostent */
struct sockaddr_in their_addr;
/* */
if (argc! = 2)
{
fprintf (stderr, " : hostname\n ");
exit (1);
}
if ((he=gethostbyname (argv [1])) == NULL) /* DNS
IP- */
{
herror ("gethostbyname");
/* herror() */
exit (1);
}
/* , , */
if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
{
perror ("socket");
/* perror() */
exit (1);
}
their_addr.sin_family = AF_INET;
/* */
their_addr.sin_port = htons (port);
/* short, */
their_addr.sin_addr = * ((struct in_addr *) he -> h_addr);
bzero(&(their_addr.sin_zero), 8);
/* struct */
/* struct sockaddr_in their_addr */
if (connect (sd, (struct sockaddr *)&their_addr, sizeof (struct sockaddr)) == -1)
{
perror ("connect");
/* */
exit (1);
}
if ((numbytes=recv (sd, buf, MAXDATASIZE, 0)) == -1)
{
/* */
perror ("recv");
exit (1);
}
/* */
buf [numbytes] = '\0 ';
printf (" : %s ", buf);
close (sd);
/* , , */
return 0;
}

TCP-
( ):




, ,

2.12 UNIX TCP-


#include
#include
#include
#include

<stdio.h>
<unistd.h>
<stdlib.h>
<errno.h>

1
3
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
/* WNOHANG*/
#define MYPORT 3490
/* , */
#define BACKLOG 10
/* */
int main()
{
int sd, newsd; /* sd, newsd */
struct sockaddr_in my_addr;
/* */
struct sockaddr_in their_addr; /* () */
int sin_size;
/* , , */
if ((sd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
{
perror ("socket");
exit (1);
}
my_addr.sin_family = AF_INET;
/* */
my_addr.sin_port = htons (MYPORT);
/* short, */
/* - IP- */
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
/* struct */
/* - */
if (bind(sd, (struct sockaddr *)&my_addr, sizeof (struct sockaddr)) == -1)
{
perror ("bind");
exit (1);
}
/* MYPORT */
if (listen (sd, BACKLOG) == -1)
{
perror ("listen");
exit (1);
}
while(1)
/* accept()*/
{
sin_size = sizeof (struct sockaddr_in);
if ((newsd = accept (sd, (struct sockaddr *)&their_addr, &sin_size)) == -1)
{
perror ("accept");
continue;
/* , */
}
/* */
printf (" : %s\n ", inet_ntoa (their_addr.sin_addr));
if(!fork ())
{
/* */
/* , , newsd */
/* - */
/* 14 */
if (send(newfd, " , ! \n", 14, 0) == -1)perror ("send");
close(newsd);
/* newsd */
exit (0);
/* */
}
/* -*/
close (newsd);
/* newsd */
while (waitpid (-1, NULL, WNOHANG) > 0);
/* */
}
/* accept()*/
}
/* */

1
3

, UNIX-,
.
UNIX fork(). , (,
child) (, parent) .
- , ,
( ,
). init .
()
. exec()
.
wait(). exit().
,
:
- ,
wait(), ;
wait(),
"", .. , ,
.
,
init().
, fork() ""
2 ,
close(newsd), , , ,
.
while (waitpid (-1, NULL, WNOHANG) > 0);

-.
.
wait(), waitpid()
. -,
pid. ,
1 , .
WNOHANG. ,
() waitpid(),
-. wait()
- pid.
- NULL , -
.

- UDP-
-, UDP- (. 2.13)
.

1
3

. 2.13. UDP- -


bind() connect() .

UDP-
UDP- , :
Udp_client.exe localhost Hello, World!
2.13 UNIX UDP-
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/socket.h>
#define MYPORT 4950
/* , */
int main(int argc, char *argv[])
{
int sd;
struct sockaddr_in their_addr;
/* */
struct hostent *he;
/* he hostent */
int numbytes;
if (argc != 3) /* , */
{
fprintf(stderr, "usage: talker hostname message\n");
exit(1);
}
if ((he=gethostbyname(argv[1])) == NULL) /* - */
{
herror("gethostbyname");
exit(1);
}
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
/* UDP- */

1
3
perror("socket");
exit(1);
}
/* () */
their_addr.sin_family = AF_INET;
/* */
their_addr.sin_port = htons(MYPORT);
/* short, */
their_addr.sin_addr = *((struct in_addr *)he->h_addr);
bzero(&(their_addr.sin_zero), 8);
/* */
if ((numbytes=sendto(sd, argv[2], strlen(argv[2]), 0, (struct sockaddr *)&their_addr,
sizeof(struct sockaddr))) == -1)
{
perror("sendto");
exit(1);
}
printf("sent %d bytes to %s\n",numbytes,inet_ntoa(their_addr.sin_addr));
close(sd);
return 0;
}

UDP-
"" (, 4950.)
2.14 UNIX UDP-
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#define MYPORT 4950
/* , */
#define MAXBUFLEN 100
main()
{
int sd;
struct sockaddr_in my_addr;
/* */
struct sockaddr_in their_addr;
/* ,
() */
int addr_len, nb;
char buf[MAXBUFLEN];
if ((sd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
/* */
my_addr.sin_port = htons(MYPORT);
/* short, */
my_addr.sin_addr.s_addr = INADDR_ANY;
/* IP- */
bzero(&(my_addr.sin_zero), 8);
/* */
if (bind(sd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
addr_len = sizeof(struct sockaddr);
/* "" , */
/* recvfrom() */
if ((nb=recvfrom(sd, buf, MAXBUFLEN, 0, (struct sockaddr *)&their_addr, &addr_len)) == -1)
{
perror("recvfrom");

1
3
exit(1);
}
/* */
printf("Got packet from %s\n",inet_ntoa(their_addr.sin_addr));
printf("Packet is %d bytes long\n",nb);
/* */
buf[nb] = '\0';
printf("Packet contains \"%s\"\n",buf);
/* */
close(sd);
}

, UDP- listen() accept().

TCP/UDP
bzero(). API
UNIX. T : bzero(), bcopy() bcmp()
,
, . , BSD.
System V: memset(), memcpy() memcmp().
void *bcopy (void *from, const void *to, size_t size)
memmove(), , . . .
void *bzero (void *block, size_t size) - memset(),
, . . .
bzero( buf, sizeof( buf) );
/* buf, BSD. */
memset( buf, 0, sizeof( buf) );
/* buf, System V. */
.sin_zero ,

. 0 UNIX
"panic". , ? ,
"",
.

Windows , ,
.

perror() herror().
#include <stdio.h>
#include <errno.h>
void perror(const char *s);
void herror(const char *s);

perror() (STDERR )
, ,
. . ( s NULL
*s NULL) s, "connect".
- , , ,
.
, .
, -1 errno
(
errno.h). .
perror() . ,
errno :
, (, ,
, ). , , , perror(), errno .
herror().
gethostbyname() gethostbyaddr()
.
h_errno, , ,
1

1
3

. , ,
herror(), perror().
, gethostbyname(),
:
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>

"localhost". , 127.0.0.1.

15. UNIX-
UNIX-
, , login, shell, telnet,
ftp, pop3 .. ""
, .
( inetd) /etc/inetd.conf
/etc/services.
select(). ,
, select() (. 2.14).
inetd xinetd, IPv6
. xinetd RedHat 7-
. ,
xinetd inetd .

inetd
UNIX- .

. 2.14. inetd TCP-

, inetd,
:

, inetd:
socket(), bind(), listen(), accept().
0,1 2 (
). -
exit() .
/etc/services /etc/inetd.conf.

TCP- inetd , ,
, stdin, stdout stderr,
. ,
1

1
3

0, 1 2. inetd (/etc/ inetd.conf), inetd


. ,
, . . 2.14.
, .
, .
.
inetd TCP .
49.

inetd

"/etc/inetd.conf" inetd, .
, , ,
, . , "*",
.
:
service style protocol wait username program arguments .
service , .
, "/etc/services". inetd service, ,
.

style protocol .
,
"SOCK_", , "stream" "dgram".
, "/etc/protocols". "tcp"
"udp" .

wait "wait" "nowait". "wait" ,



. "nowait" , , inetd
, , . TCP wait "nowait".

user , . inetd
root, ID
. "root" ;
, Telnet FTP, username .
root ,
, .

program - .
, .
,
.

"/etc/inetd.conf":
ftp stream tcp nowait root /libexec/ftpd ftpd,
talk dgram udp wait root /libexec/talkd talkd .
"/etc/inetd.conf" ,
inetd , inetd SIGHUP.
ID inetd, , ps.

16.
TCP/IP
.
1

1
3


(TCP, UDP, IP), IP, TCP UDP
.
. "sys/socket.h".
, ,
TCP/IP
. ,
.. , Windows,
, , UDP_CHECKSUM Windows
UDP_CHECKSUM _COVERAGE.
Windows MSDN.

. 2.15

getsockopt() optname
.
int getsockopt (int sd, int level, int optname, void *optval, size_t *optlen_ptr);

, optval.
*optlen_ptr ; ,
, .
optval int.
getsockopt() 0 -1 .
errno :
EBADF

sd .

ENOTSOCK

sd .

ENOPROTOOPT

ptname .

setsockopt() , optname
.
int setsockopt (int sd, int level, int optname, void *optval, size_t optlen);

optval, optlen.

: , , ,
. (on/off),
optval , , - ,
. optlen sizeof (int). , optval
, , optlen -
. , Windows BOOL,
MSDN DWORD. BSD 4.*, int. POSIX
, socklen_t.

1
3

setsockopt() , getsockopt().
level :
2.

int SOL_SOCKET
int IPPROTO_TCP
int IPPROTO_IP
int IPPROTO_UDP
int IPPROTO_ICMPV6
int IPPROTO_IPV6


TCP
IPv4
UDP
ICMPv6
IPv6

:
IPv6 . IGMP IPv4 IPv4.
setsockopt() getsockopt() ,
.

50.

setsockopt()


; "sys/socket.h". , ,
getsockopt(), Unix- . Windows
,
MSDN.
SO_DEBUG

TCP-. int; "".
trpt.
SO_REUSEADDR
bind()
. ,
-, IP- .
IP- (aliases ),
(primary) IP- .

. ,
UDP [19].
,
, FTP, .
.
int; "".

"" . ,
TIME_WAIT, TCP ,
"" , 2MSL,
"Address already in use".
SO_REUSEPORT
4.4BSD
.
1

1
4

SO_KEEPALIVE
, TCP- keepalive
probe . ,
. int;
"". TCP- 120 ,
(, )
TCP- .
SO_DONTROUTE
.
,
. .
int; "".
SO_LINGER
close() TCP-.
close() ,
, FIN.
close() ,
linger.
struct linger
{
int 1_onoff;

/* / . */

int 1_1inger;

/* . Posix1.g - ,
*/

};

:
int l_onoff
. ,
SO_LINGER , . 1_1inger .
l_onoff , l_linger.
int l_linger
l_onoff ( ), l_linger=0,
" 0 ", TCP- .. FIN,
RST (hard close). l_linger ,
, close(), . TCP-
(graceful close),
. close() EWOULDBLOCK,
.


Windows- API
shutdown(), closesocket().

SO_DONTLINGER
.
SO_LINGER l_onoff=0.
SO_BROADCAST
, UDP- .
int; "".
,
(Ethernet, Token Ring . .).
- .
,
, . , UDP
IP- ,
1

1
4

, . ,
, , :
, EACCESS.
SO_SNDBUF
(get) (set) .
size_t .
SO_RCVBUF
(get) (set) .
size_t .

, WinSock SO_SNDBUF SO_RCVBUF
TCP [MSDN], Windows
Alun
Jones
:
[http://groupsbeta.google.com/group/microsoft.public.win32.programmer.networks/browse_thread/thread/3f4ea7497cb02a6a/73e5239c03d
bad25?q=arkadyf+%22large+tcp+window%22#73e5239c03dbad25]: "To set the window size larger, I increase the send and
receive buffer using setsockopt() before calling listen() or connect(). That may be a slight overkill, but it guarantees me what
I need. I also need to set the options discussed previously to enable large window scale options at all."

http://www.microsoft.com/technet/prodtechnol/windowsserver2003/technologies/networking/tcpip03.mspx#EGAA.
Unix-, , ,
[19].

SO_RCVLOWAT, SO_SNDLOWAT
/,
select(). TCP 1 .
- ,
, TCP- 2048.
SO_RCVTIMEO, SO_SNDTIMEO
, /
. timeval
. WinSock 2
timeval .
:
Windows SO_RCVTIMEO, SO_SNDTIMEO recv()
send() ,
connect().

SO_OOBINLINE
TCP, URG , Urgent Pointer.
" ",
TCP 8 (1 ) , "
out-of-band data".
.
SO_OOBINLINE, , ioctl()
SIOCATMARK - .
SIGURG.
URG=1 TCP- , - ,
, .
16- Urgent Pointer ,
" ".

1
4

. 2.16

.2.12 -.
, . N
, ""
1, 2 OOB .
Urgent Pointer OOB .
.
"" :
2.15
.....
write(sd, "abc",3);
printf(" 3 abc"\n);
/* 1 . TCP_ */
sleep(1);
send(sd, "9",1,MSG_OOB);

/* */

printf(" 1 9"\n);
......

send() MSG_OOB.
, -
; ,
recv() MSG_OOB.
OOB- ,
TCP-, ( )
, TCP-
. , TCP.
, - " "
( MSG_OOB)
TCP- SO_OOBINLINE.
SO_OOBINLINE int; "".
, ,
SIGURG - . , F_SETOWN
fcntl().
. TCP-
accept().
( SIGURG select()) ,
, , ,
. , , recv()
EWOULDBLOCK.
, , "out-of-band mark"
, " ".
Posix1.g sockatmark()
ioctl() SIOCATMARK, :
success = ioctl (sd, SIOCATMARK, &result);

() ,
, :
1

1
4
2.16 ""
int read_until_mark (int sd)
{
while (1)
{
char buf[1024];
int flag, success;
/* , flag=1*/
success = ioctl (sd, SIOCATMARK,&flag);
if (success < 0) perror ("ioctl");
if (flag) return;
/* , */
success = read (sd, buf, sizeof buf);
/* */
if (success < 0) perror ("read");
}
}


() TCP,
. " "
telnet Ctrl+C.
.
"" "
", , .
SO_KEEPALIVE , . -,
2 . -,
,
, SO_KEEPALIVE,
. "" , 1
, 5 . " "
[19]
(RFC-793 RFC-1122),
,
. , Urgent Pointer,
""
OOB.

FreeBSD 5.0-CURRENT SO_ACCEPTFILTER,
accept-. - dataready httpready.
HTTP- (, Apache)
,
HTTP-, .

TCP
IPPROTO_TCP
TCP.
TCP_KEEPALIVE
"keep alive" .
SO_KEEPALIVE.
TCP_MAXSEG
1

1
4

MSS TCP-.
TCP_NODELAY
Nagle, (
MSS) , ACK (ACK ).

UDP
IPPROTO_UDP
UDP.
UDP_CHECKSUM
, UDP.
int. 0 = OFF, non-zero = ON.

IP
IPPROTO_IP
IP.
IP_HDRINCL
SOCK_RAW, IP-
.
IP_OPTIONS
, IP-o IP-
.
IP_TOS
type-of-service IP- .
IP_TTL
time-to-live IP- .
Windows IPX/SPX NSPROTO_IPX,
Windows Me/98/95 ,
.
51.

getsockopt()

SO_DEBUG
, , .
SO_BROADCAST
, , .
SO_ACCEPTCONN
, ( ,
listen()).
SO_ERROR
so_error, <sys/socketvar.h>,
, so_error .
SO_LINGER
close(), linger-.
SO_OOBINLINE
, , .
SO_KEEPALIVE
1

1
4

,
. TCP_KEEPALIVE
.
. [19] :
SO_KEEPALIVE TCP 2
, TCP
(keepalive probe). TCP,
.
1 , .
( ). TCP
2
2. , RST, TCP,
. , ,
ECONNRESET, .
3. . TCP,
, 75 ,
. TCP , 11
15 . TCP
, , , ETIMEDOUT,
. ICMP
, , .
ICMP Host unreachable ( )
, , . ,
, EHOSTUNREACH.
SO_RCVLOWAT
, .
SO_RCVTIMEO
timeout .
SO_REUSEADDR
, , bind(),
.
SO_SNDLOWAT
, .
SO_SNDTIMEO
timeout .
SO_TYPE
. getsockopt(). ,
(SOCK_DGRAM SOCK_STREAM) ,
.

TCP
TCP_KEEPALIVE
( ) keepalive.
int. SO_KEEPALIVE.

UDP
UDP_CHECKSUM
, UDP.
,
.
1

1
4

IP_RECVDSTADDR
, , IP-
, IP- UDP
. recvmsg()
, . ,
. BSD/386, 4.4BSD AIX 3.2.2
. SVR4, SunOS 4.x Solaris 2.x .

IP
IP_HDRINCL
, IP- .
IP_OPTIONS
, IP- IP-
.
IP_TOS
type-of-service IP- .
IP_TTL
time-to-live IP- .
, Sockets
API . , 1.1 WinSock
IP.
2.16 setsockopt()
getsockopt() . , optval .
2.17 setsockopt() getsockopt()
# include
<sys/socket.h>
.
int
res,sd;
int
sockbufsize=16384;
int
sbufsize;
size_t len = sizeof(sbufsize);
sd=socket(AF_INET,SOCK_STREAM,0);
.
/* */
res = setsockopt(sd, SOL_SOCKET, SO_SNDBUF, &sockbufsize, sizeof(sockbufsize));
.
/* */
res = getsockopt (sd, SOL_SOCKET, SO_SNDBUF, &sbufsize, &len);
.

52.

, , ,
IGMP. bind() D,
( 0, TCP/IP ).
.
API . ,
setsockopt()
getsockopt(). level getsockopt() setsockopt() IPv4
- IPPROTO_IP.

1
4

. (struct im_req),
in_addr.

IP_ADD_MEMBERSHIP
IP_ADD_MEMBERSHIP
. ,
. ,
. ,
MAC-, .
:
struct ip_mreq
{
struct in_addr imr_multiaddr; /* "" */
struct in_addr imr_interface; /* , */
}

c,
. setsockopt() SO_REUSEADDR,
. TCP/IP
IGMP Host Membership Report 224.0.0.1 ( "-").

IP_DROP_MEMBERSHIP
IP_DROP_MEMBERSHIP .
TCP/IP .
IP_DROP_MEMBERSHIP ,
1.
( ) 0, MAC . IGMP-.

IP_MULTICAST_IF
IP_MULTICAST_IF ,
/ .
. ,
,
.
.

IP_MULTICAST_LOOP
IP_MULTICAST_LOOP
, , .
. ,
, , ,
.

IP_MULTICAST_TTL
TTL , .
, ,
TTL -1. 7
WinSock API, .
IPv6 IP_ IPV6_,
.
IPV6_MULTICAST_HOPS, .

1
4

17.
(Raw Socket) ,
, ,
, ICMP,
. . [19] Raw Socket "
" . , ,
.
SOCK_STREAM SOCK_DGRAM
SOCK_RAW. ,
, ICMP.
Af = AF_INET, type = SOCK_RAW, protocol = IPPROTO_ICMP
IP- ,
. "" IP- ,
IP, .
, ( IP) , . ICMP, ICMP-, .
ICMP-, ,
. ,
, .
.
, , . ,
TCP UDP ; ICMP- ,
"", .
""
PING. TCP/IP ICMP- ECHO (
, , ). ECHO, ECHO
,
. ,
( WinSock 1.1) 3.

Windows- Windows 200, Windows XP RAW .

ICMP ""
, , ICMP
.
, :


IP_HDRINCL:

IPv4-,

const int on=1;


if(setsockopt(sd,IPPROTO_IP,IP_HDRINCL,&on,sizeof(on))<0) {/**/}

IP-.

IGMP;

, , , ,
OSPF, BGP IP.

, ,
TCP UDP. ,
.
. 9.
.
1

1
4

,
. bind() connect()
, .
, ,
"" .
*nix [19].

: socket(AF_INET, SOCK_RAW, IPPROTO_RAW),
IPPROTO_RAW, 255 IP.
, IPPROTO_RAW , .

IP-
? -
TCP/IP, ,
+. Linux- . ,
Linux- SOL_RAW.
, Linux- Raw Sockets ,
IP, ICMP TCP,
(. 5.2).
. ,
( , BSD) .

18. Nagle
TCP-, ,
TCP- (HTTP, FTP, ,
News), (, telnet
rlogin, IRC ). ( ) [37],
90% , 10% . ,
, , (512
), . ,
, 90% , telnet rlogin, 10
.
TCP ,
.
() rlogin (remote login). ,
(Nagle)
, . telnet.
, rlogin- [37].
, TCP/IP, ,
, IP-
. , 1
( ). , rlogin ,
. TCP-:
1.

,
6. ,
7.
8. .
. 2.17 .

1
5

. 2.17. rlogin

( )
- ( ACK).
rlogin .
rlogin- 1 . IP-
41 : 20 IP-, 20 TCP- 1 .
, telnet ,
, .
tcpdump,
Client 1023 Server rlogin:

1
Client.1023 -> Server.login: P 0:1(1)
2
Server.login -> Client.1023: P 1:2(1)
3
Client.1023 -> Server.login: .
4
Client.1023 -> Server.login: P 1:2(1)
5
Server.login -> Client.1023: P 2:3(1)
6
Client.1023 -> Server.login: .
7
Client.1023 -> Server.login: P 2:3(1)
8
Server.login -> Client.1023: P 3:4(1)
9
Client.1023 -> Server.login: .
10
Client.1023 > Server.login: P 3:4(1)
11
Server.login -> Client.1023: P 4:5(1)
12
Client.1023 -> Server.login: .
13
Client.1023 -> Server.login: P 4:5(1)
14
Server.login -> Client.1023: P 5:7(2)
15
Client.1023 -> Server.login: .
16
Server.login -> Client.1023: P 7:37(30)
17
Client.1023 -> Server.login: .
18
Server.login -> Client.1023: P 37:44(7)
19
Client.1023 -> Server.login: .

ACK window
ack 1 win 4096
ack 1 win 4096
ack 2 win 4096
ack 2 win 4096
ack 2 win 4096
ack 3 win 4096
ack 3 win 4096
ack 3 win 4096
ack 4 win 4096
ack 4 win 4096
ack 4 win 4096
ack 5 win 4096
ack 5 win 4096
ack 5 win 4096
ack 7 win 4096
ack 5 win 4096
ack 37 win 4096
ack 5 win 4096
ack 44 win 4096

, "date\n",
, , 30 .
BSD/386, TOS IP- rlogin-
, . P Push ,
BSD , .
1

1
5

1 1 (d). 2
( .) 3 ,
. 4-6 a, 7-9 t,
10-12 - e.
13-15.
(UNIX- , ENTER),
. (CR/LF),
.
16 date, . 30
28
Sat Feb 6 07:52:17 MST 2004
CR/LF .
( , tiny , )
, ,
. RFC 896 (John Nagle,1984),
, (Nagle algorithm).
, TCP-
"" , . TCP ""
, MSS.
, . , , ,
TCP-,
. :
, .
, ,
.

, , - RTT,
.
: -
, ;
, ,
. TCP Nagle .

Nagle
, Nagle .
UNIX- X Window: (
) ,
.
,
.
,
escape- ASCII. TCP- 1 ( ) ,
(ASCII ESC), ,
. ,
, -, .
ACK, ,
200 .
.
Host Requirements RFC , TCP
Nagle,
. API TCP_NODELAY,
Nagle.

1
5

Nagle
[37].
1: Nagle - ( !)
"" . "ServerApp"
"hello\n" CLIENT APP, .
TCP CLIENT APP

TCP SERVER APP

[ ]
"h" ------>

[1 ]
------------------>

-----------> "h"
[ack , 0,2 .]

"e" ------> [ Nagle-]


"l" ------> [ ack 1- ]
"l" ------>
"o" ------>
"\n"------>
[ack 1 "h"]
<-----------[ ]
[5 ]
------------------>
"ello\n"---------->
<--------- "HELLO\n"
[ 6 ack 5 ]
<-----------------"HELLO\n" <---[ack ]
.
[ack 6 ]
------------------>
: 5. ( TCP_NODELAY, 10.)
: 2*RTT (Round Trip Time) + ACK.
2: write().
TCP CLIENT APP

TCP SERVER APP

[ ]
"hello\n" --->

[6 bytes]

------------------>
------------> "hello\n"
<------------ "HELLO\n"
[6 , ack 6 ]
<-----------------"HELLO\n" <---[ack ]
.
.
1

1
5

. [ack 6 ]
------------------>
: 3. = RTT (. . ).

19. TCP/IP
, ,
TCP/IP.
- TCP,
.
2.18.
TCP, -.
4- :
, TCP,
socket(). TCP
SO_SNDBUF SO_RCVBUF (. 2.9.1). send(),
IPC (Inter Process Communication)
TCP , , .
TCP ( ,

IPC
TCP

connect()
send()


send()


recv()

IPC
TCP


SYNACK


TCP


TCP

TCP


TCP

2.18 TCP


TCP-
accept()
send()


recv()


send()

), send()
( - ,
). TCP ,
. ,
send() .
connect() 2.18
, TCP.
, . -, connect()
, SYN
ACK SYN- TCP
.
, .
, - .

, ,
.
TCP, UDP ,
. TCP
Receive Window,
TCP TCP. TCP ,
, .
- ,
, TCP
.
UDP , , , ..
. UDP ,
, UDP
. UDP
.
, SO_RCVBUF SO_SNDBUF
, , .
- 4096 ,
8192 61 440 .
UDP 9000 , NFS;
UDP 40 000 ,
250.
TCP
TCP, , SO_RCVBUF
connect(), ,
1isten().
, accept(),
, accept()
threeway handshake,
.
TCP-
MSS -
, 4MSS, 8xMSS.

, .

1. connectionless connection oriented ?


?
2. ?
3. ?
4. .
5. " " ?
6. " "?
7. sockaddr_in.
8. in_addr?
9. ?
10. TCP-.
11. bind()?
12. accept()?
13. TCP-.
14. 3 /.
15. UDP-.
16. UDP-.
17. , ?
18. " "? ?
19. " " , ?
20. ioctl()?
21. ?
22. " "?
23. hostent.
24. " ", ?
25. ""?
26. SIOCATMARK?
27. "" ?
28. .
29. "TIME_WAIT"?
30. " Nagle" ?

1. 3 Windows Sockets

20.
WinSock Windows Sockets (API)
MS Windows TCP/IP [16], [30], [2], [12],
[27],[28]. Windows- TCP/IP (
WinSock ). ,
- UNIX, API
. Windows Windows 9x,
(DLL).
winsock.dll (16 , WinSock 1.1) wsock32.dll ( BSD-sockets)
ws2_32.dll (32 , WinSock 2.0).
UNIX Windows , Windows Sockets
, WinSock API Windows,
"", Windows .
WinSock:
WinSock 1.0 WinSock 1.1
WinSock 2.0
WinSock 2.2.0

TCP/IP
, 1992
TCP/IP
, 1993
WinSock 1.1 AF_INET
TCP/IP
,
1994 .
,
1996 .
3.1 WinSock

WinSock

Windows 95

1.1 (2.2)

Windows 98

2.2

Windows Me

2.2

Windows NT 4.0 2.2


Windows 2000 2.2
Windows XP

2.2

Windows CE

1.1

MSDN, WinSock2-2.2.0 WinSock2.


, WinSock 1.1,
Windows.
WinSock 2.0 4, , 3-
WinSock, 1.1.
WinSock 2.0 ,
WinSock 2.2.

Windows CE, WinSock 1.1,
/.

WinSock :


Windows
Windows,
.


TCP/IP, .
( , , )
TCP/IP, ,
WinSock. . 3.1 , WinSock
TCP/IP- Windows. ,
WinSock, 3.2

. 3.1 WinSock Windows ( )

3.2 WinSock

Winsock.dll

16- Winsock 1.1

Wsock32.dll

32- Winsock 1.1

Ws2_32.dll

DLL Winsock 2.0

Mswsock.dll

Microsoft. API Mswsock.dll

Ws2help.dll

- ,
WinSock

Wshtcpip.dll

TCP

Wshnetbs.dll

NetBT

Wshirda.dll

IrDA

Wshatm.dll

ATM

Wshisn.dll

Netware

Wshisotp.dll

OSI-

Sfmwshat.dll

Macintosh

Nwprovau.dll

IPX

Rnr20.dll

Winrnr.dll

LDAP

Msafd.dll

WinSock

Afd.sys

Winsock- TDI (Transport driver interface)

.
WinSock , SOCKET, .
UNIX ( )
. , Windows UNIX, ,
. , .
WinSock .
WinSock SOCKET (unsigned).
INVALID_SOCKET.
(SOCKET)(~0) (-1) .
,
INVALID_SOCKET-1. , , , 0xFFFF. . UNIX Windows,
, ,
( ), WinSock.
, WinSock Windows.
, -.

21. -,
WinSock
.
.
. 3.4 , WinSock.
3.4. ,

accept()

.
, .
.

closesocket() . close()
Connect()

recv()

Recvfrom()

select()

-
.

send()

sendto()

( .)

UNIX Windows read()


write(). WinSock, recv()
send(). close() closesocket(), ioctl()
ioctlsocket(). . 3.3.
3.3. , WinSock,

- WinSock

read()

recv()

write()

send()

close()

closesocket()

ioctl()

ioctlsocket()

close() Windows , ..
. , closesocket()
.
ioctlsocket(). - ioctl()
fcntl() . :
int ioctlsocket(SOCKET sd,long cmd, u_long FAR *argp);

:
sd
cmd
argp

[in]
[in] , sd
[in/out] cmd
SOCKET_ERROR .

ioctlsocket() :
FIONBIO
argp, ,
sd. argp , .
argp . BSD.

WSAAsyncSelect() WSAEventSelect() .
WSAAsyncSelect() WSAEventSelect() ,
ioctlsocket() WSAEINVAL.
, WSAAsyncSelect(), WSAAsyncSelect()
lEvent, , WSAEventSelect(), WSAEventSelect()
lNetworkEvents, .

FIONREAD
, , ,
sd. argp ,
ioctlsocket() . sd (SOCK_STREAM), FIONREAD
, recv();
, ,
TCP/IP. sd (SOCK_DGRAM), FIONREAD
(), .

SIOCATMARK
, OOB- . (.
" "). ,
inline-
(SO_OOBINLINE). OOB-, TRUE.
FALSE, recv(), ,
, .
SIOCATMARK, , . ,
, . ( recv()
OOB .) argp
, ioctlsocket() (Boolean).
ioctlsocket() Windows 2000
, " " - promiscuous
mode, - ,
.
IP Ethernet-, .
, MAC-
. setsockopt() SIO_RCVALL
(SOCK_RAW)

127.0.0.1 - "", , ,
, IP.
, , 127.0.0.1 .

SIO_RCVALL Mstcpip.h.
SIO_RCVALL
.
sockaddr_in sa;
ULONG PromiscuousMode=1;
sd=socket(AF_INET, SOCK_RAW, IPPROTO_IP);
if (sd==INVALID_SOCKET) return 1;
memset(&sa,0,sizeof(sockaddr_in));
sa.sin_family=AF_INET;
sa.sin_addr.s_addr=inet_addr(server_ip);
sa.sin_port=htons(0);
if ( bind(sd,(LPSOCKADDR)&sa,sizeof(sa)) )
{
printf("bind error\n");
return 1;
}
if ( ioctlsocket(sd,SIO_RCVALL,&PromiscuousMode) )
{
printf("ioctlsocket error\n");
return 1;
}
.


.
. , , , readv(), writev(), recvmsg() sendmsg().
, . 3.5, - .
, .
, , ,
.
3.5 , WinSock API.

bind()

() .

getpeername() , . (WinSock API


,
-.)
getsockname() () .
getsockopt()

() .

htonl()

32- .

htons ()

16- .

inet_addr()

IP- 32- (
).

inet_ntoa()

IP- - .

ioctlsocket()

, -.

listen()

ntohl()

32- .

ntohs()

16- .

setsockopt()

() .

shutdown()

( ).

socket()

3.6. WinSock API

gethostbyaddr()

() IP-, .

gethostbyname()

() IP-, .

gethostname()

getprotobyname()

(, TCP).

getprotobynumber()

getsenbyname()

(, time) ,
.

getservbyport()

,
.

. 3.53.6 ,
hostent.
WinSock . ,
, ,
, , ,
. , ,
WinSock.
WinSock
( Windows) ,
gethostname(). Windows-
. Windows
. . 3.7
. WinSock API.
3.7. WinSock I

gethostbyaddr()

WSAAsyncGetHostByAddr()

gethostbyname()

WSAAsyncGetHostByName()

gethostname()

He

getprotobyname()

WSAAsyncGetProtoByName()

getprotobynumber()

WSAAsyncGetProtoByNumber()

getservbyname()

WSAAsyncGetServByName()

getservbyport()

WSAAsyncGetServByPort()

, Windows-
WSA (Async ). WSA - Windows
Sockets API - WinSock 1.1,
WinSock 2.0

22. -, Windows
WinSock
,
, - Windows.
Windows . . 3.8
Windows-, WinSock API 1.1,
, . 3.7.

3.8. - Windows (
)

WSAAsyncSelect()

select().

WSACancelAsyncRequest()

WSAAsyncGetXByY().

WSACancelBlockingCall()

API.

WSACleanup()

WinSock , DLL.

WSAGetLastError()

WSAIsBlocking()

, winsock.dll .

WSASetBlockingHook()

. (. . .)

WSASetLastError()

WSAGetLastError().

WSAStartup()

winsock.dll.

WSAUnhookBlockingHook()

. ,
Windows, 3.6.1, ,
Windows-.

23.

winsock.dll (16-bit ) wsock32.dll (32-bit ),
Windows Sockets 1.1 MS Windows MS
Windows CE.

WindSock 2.0 ws2_32.dll

WSAStartup(),
:
int WSAStartup (WORD wVersionRequested, LPWSADATA lpWSAData);

wVersionRequested Windows Sockets,


.
(minor version), (major
version).

WSAStartup() lpWSAData
WSADATA,
Windows Sockets.
, .

WSADATA :
typedef struct WSAData
{
WORD
wVersion;
WORD
wHighVersion;
char
szDescription[WSADESCRIPTION_LEN+1];
char
szSystemStatus[WSASYS_STATUS_LEN+1];
unsigned short
iMaxSockets;
unsigned short
iMaxUdpDg;
char FAR *
lpVendorInfo;
} WSADATA;
typedef WSADATA FAR *LPWSADATA;
szDescription szSystemStatus


WSAStartup() , , Windows
Sockets .

wVersion wHighVersion , , Windows


Sockets, , ,
Windows Sockets.
, ,
() . iMaxSockets
, . WinSock
;

. iMaxSockets winsock.dll
.
, Windows Sockets
.
iMaxUdpDg ,
UDP. ,
iMaxUdpDg . Berkeley 8192
UDP- ( ).
Windows , , ,
. iMaxUdpDg
Windows Sockets 512. , iMaxUdpDg,
, MTU
. (API Windows Sockets MTU,
512 .) , iMaxSockets iMaxUdpDg WinSock 2.0
1.1 , , lpVendorInfo
, API Windows Sockets.
WSAStartup() . ,
:
3.9.

WSASYSNOTREADY

WSAVERNOTSUPPORTED

WinSock

WSAEINVAL

DLL, WinSock, ,
wVersionRequested

Windows Sockets
, Windows Sockets 1.1,
WSAStartup() ,
WSAStartup() Windows Sockets DLL ,
, ,
.
3.10
Windows Sockets.
3.10. winsock.dll
,

DLL

wVersionR
equested

wVersion

wHighVersion

1.1
1.0 1.1
1.0
1.1
1.1
1.0
1.0 1.1

1.1
1.0
1.0 1.1
1.0 1.1
1.0
1.1
1.0 1.1

1.1
1.1
1.0
1.1
1.1
1.0
1.1

1.1
1.0
1.0
1.1
1.0
--1.1

1.1
1.0
1.1
1.1
1.0
--1.1

1.1
1.0
1.0
1.1

WSAVERNOTSUPPORTED
1.1

1.1 2.0
2.0

1.1
1.1

2.0
2.0

1.1
1.1

1.1
1.1

1.1

3.1 , , Windows
Sockets 1.1, WSAStartup():
3.1
WORD wVersionRequested;
WSADATA wsaData;
int err;
wVersionRequested = MAKEWORD( 1, 1 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 ) {
/* , winsock.dll, , */
return;
}
/* , winsock.dll 1.1.*/
/* 1.1 wVersion, , */
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
/* , WinSock.dll, , */
WSACleanup( );
return;
}
/* winsock.dll a. . */

MAKEWORD(), WORD
:
WORD MAKEWORD(BYTE bLow, BYTE bHigh);

:
3.2
rc = WSAStartup (MAKEWORD(1, 1), &WSAData);
if(rc != 0)
{
MessageBox(NULL, "WSAStartup Error", "Error", MB_OK);
return FALSE;
}

3.3 , WSAStartup()
winsock.dll, 1.1:
3.3 WSAStartup()
/* , >= 1.1. */
/* , . */
if ( LOBYTE( wVersionRequested ) < 1 || ( LOBYTE( wVersionRequested ) == 1 &&
HIBYTE( wVersionRequested ) < 1 )
{
return WSAVERNOTSUPPORTED;
}
/* 1.1, wVersion wHighVersion 1.1. */
lpWsaData->wVersion = MAKEWORD(1,1);
lpWsaData->wHighVersion = MAKEWORD(1,1);

Microsoft Windows 95 Microsoft Windows NT 3.51


WinSock 1.1,
MAKEWORD(1, 1) WSAStartup() .
, , ,
Windows Sockets.
WSACleanup(), , :

int WSACleanup (void);

WSACleanup() WinSock-DLL
WinSock. , WSACleanup()
(, Windows 95 N).
SOCKET_ERROR .
WSAGetLastError(),
Windows Sockets
3.7.2. ,
. WSACleanup(),
WSAGetLastError() , 3.11:
3.11.

WSANOTINITIALISED

Windows Sockets WSAStartup()

WSAENETDOWN

WSAEINPROGRESS

WSACleanup()
Windows Sockets

24. Windows
.
"" " ",
, .
, , ,
.
, ,
Windows . ,
Windows
, . ,
Windows- WinSock API
. , - ioctl() fcntl()
ioctlsocket() WinSock ( WSAIoctl () 2.0)
. , ,
!
53.

Windows-

Windows- ,
.
. Windows-,
.
Windows .
WinMain()
Windows-, ,
WinMain(). (++)
main(). (), ,
, ( ).
,
. Windows ,
, .
Windows
Windows- ,
(header) . HANDLE, HWND, BYTE, WORD,
DWORD, UNIT, LONG, BOOL, LPSTR LPCSTR. HANDLE 32- ,
. ,

. HWND 32- . BYTE 8 , WORD 16- ,


DWORD , UNIT 32- . LONG
long. BOOL ,
, . LPSTR (LP long pointer "" )
, LPCSTR (const) .
C-, "int", "char" .

Windows , .
( ..) Windows
. MSG:
MSG :
typedef struct tagMSG
{
HWND hwnd;
UINT message;
WPARAM wParam;
LPARAM lParam;
DWORD time;
POINT pt;
} MSG;

// () ;
// ;
// ;
// ;
// ;
// .

, , Windows
, (handle) ,
() (16- 32-). 16-
wParam , ,
32- lParam , -
. ,
, .
Windows- - .

. ,
. Windows .
WinMain() .
:
MSG msg;
/*, */
while (GetMessage(&msg, 0, 0, 0))
{
TranslateMessage (&msg) ;/*
-*/
DispatchMessage (&msg); /* */
}

. ,
while . ,
GetMessage() FALSE. ,
WM_QUIT, ,
. , API
PostQuitMessage(), .
PostQuitMessage(100) 100.
GetMessage() MSG,
. WM_QUIT,
GetMessage() TRUE, .
GetMessage() - , .
NULL, , ,
. - NULL,
.
,
.
0, .

MSG,
API:
TranslateMessage()
DispatchMessage().
TranslateMessage() ,
WM_KEYDOWN, WM_KEYUP, WM_SYSKEYDOWN WM_SYSKEYUP
WM_CHAR, WM_DEADCHAR, WM_SYSCHAR WM_SYSDEADCHAR.
, .
DispatchMessage() ,
Windows-, .
, ,
DefWindowProc().
, , . .


Windows-
, ,
. .
Windows, .
.
.
. Windows-, , Windows
callback functions. ,
,
,
.
Windows, ,
. , ,
Windows. ,
, Windows , .
3.4
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CREATE:
break;
case WM_DESTROY:
PostQuitMessage(0); // WM_DESTROY
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);//
// ,
//.
}
return 0;
}

("") ,
.

.3.2

GetMessage() , , -
. , , ,
GetMessage() PeekMessage(),
.
BOOL PeekMessage(
LPMSG lpMsg,
HWND hWnd,
UINT wMsgFilterMin,
UINT wMsgFilterMax,
INT wRemoveMsg

// MSG,
// .
// ,
// .
// . 100,
//
// 100, , .
// . 200,
//
// 200, ,
// . PM_NOYIELD
// PM_NOREMOVE
// PM_REMOVE - .

);


( ) , lpMsg.
GetMessage(), PeekMessage() ,
.
PeekMessage() , ,
, Win32 API IsChild(),
, wMsgFilterMin wMsgFilterMax.
hWnd NULL, wMsgFilterMin wMsgFilterMax ,
PeekMessage() . (PeekMessage()
, , .)
hWnd


. :

PM_NOREMOVE
.
PM_NOYIELD


PM_REMOVE


WM_USER. Windows
WM_USER,
:
#define WM_USER
#define WM_NETEVENT

0x0400
(WM_USER+1)

/* WM_USER */
/*
WM_NETEVENT */


. " ",
RegisterWindowMessage().
54.

WinSock API

API Window Sockets


Berkeley Sockets API, winsock.dll
(16- , ), wsock32.dll ws2_32.dll ( 8).
(API UNIX Windows )
Windows -,
UNIX- Windows. ,
API Window Sockets ,
.
API Window Sockets .
, select()
(. 2.5.7).
.
slect(), timeout .
select() , ,
Windows .
:
3.5
struct timeval timeout = {0, 0};
while (!select(..., &timeout)) {
if (PeekMessage(...))
/* */
{
TranslateMessage(...);
DispatchMessage(...);
}
}

, ,
. ,
WIN32 API FindWindow(), user.dll (user32.dll),
( ).
hWnd NULL, PeekMessage()
, .
, ,
CPU,
select() - .
blocking hooks, , ,
, ,
, . (hook)
Windows, ,
, .
, .

Windows,
WinSock API blocking hook
, .
Windows- ,
:
- , ,
,
.
UNIX, Windows- , FIONBIO
ioctlsocket() WSAAsyncSelect() ( 3.6.3.1)
. c,
WSAAsyncSelect() / WSAAsyncGetXByY() select() getXbyY(),
.
WinSock .
, ,
.
API WinSock, WinSock
,
:
3.6

.
for(;;)
{
/* */
while(BlockingHook()); /* BlockingHook() */
/* WSACancelBlockingCall() */
if(operation_cancelled()) break; /* , */
if(operation_complete()) break; /* */
}

.
BOOL BlockingHook(void) /* */
{
MSG
msg;
BOOL
ret;
/* , */
ret = (BOOL)PeekMessage(&msg,NULL,0,0,PM_REMOVE);/* */
if (ret)
/* , ( ) */
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
/* TRUE */
return ret;

}
Windows-c
; ,
.

WinSock : WSASetBlockingHook() WSAUnhookBIockingHook(). (. )
.
(blocking hook)
, .

WSASetBlockingHook()
WinSock 1.1 WSASetBlockingHook().
,
. :
FARPROC WSAAPI WSASetBlockingHook (IN FARPROC lpBlockFunc);

lpBlockFunc
.

- ,

GUI-,
.

( GUI- ) .
:
WSASetBlockingHook() , WinSock 1.1 ( ,
, (thread) WSAStartup() 1.0
1.1) WinSock 2 (. 4) WinSock
1.1 . WinSock 2 .

, WSASetBlockingHook():
WSANOTINITIALISED
WSAENETDOWN

WSAEINPROGRESS

WSAEFAULT

WSAStartup().
.
WinSock 1.1,

(callback function).
lpBlockFunc
.

:
() - , . - ,
Windows, , (callback functions),
. "WINAPI = CALLBACK =
__stdcall"

: () - , . -
, Windows, ,
(callback functions).
WinSock :
WSAIsBlocking() WSACancelBlockingCall(). ,
.

WSAIsBlocking() WSACancelBlockingCall()
WSAIsBlocking() ( ) TRUE,
. :
BOOL PASCAL FAR WSAIsBlocking (void);

API Windows Sockets,


WSACancelBlockingCall(),
. :
int WSAAPI WSACancelBlockingCall (void);


. :
1. ,
. WSAIsBlocking() .
2. , WinSock "
" ( WSASetBlockingHook()).


WSAEINTR.
connect() WinSock ,
, (
) . ,
SO_LINGER 0.
accept() select() c,
. ;
, ,
.
, , accept() select(),
.
WSACancelBlockingCall() -
TCP- , WinSock
, closesocket(), WSAECONNABORTED.
:
, ,
WSACancelBlockingCall(), , ,
.
, WSACancelBlockingCall() . , WSACancelBlockingCall() ; , ,
, WSAEINTR .

Windows
(, ),
, Windows,
, ,
, - ,
.
,
, ,
, .
, Windows-,
API, ,
, .
:

,
,
,

.
, , ,
- ,
.

,
.

, .

55.

WinSock API

/
/ Windows (. 4.3),
Windows.
, WinSock API,
,
, .
WSAEWOULDBLOCK, ,
. recv() WSAEWOULDBLOCK,
,
, .
WSAEWOULDBLOCK
WinSock API:
WSAEWOULDBLOCK

WSAAccept() accept()
losesocket()
WSAConnect() connect()

,
.
,
setsockopt() SO_LINGER,
( ).
. ,
.
. .

WSARecv(), recv(),
WSARecvFrom() recvfrom()
WSASend(), send(), WSASendTo() .
sendto()
.

WSAEWOULDBLOCK,
. ,
, . recv()
100 recv()
MSG_PEEK.
,
.
, Windows
. , Windows .
, Windows
(, ), .
WinSock , :


(. ).


WSAAsyncSelect() WSAEventSelect() (. 4.3). WinSock

WSAAsyncGetXByY()
(WSAAsyncGetProtoByName(),
WSAAsyncGetServByPort() . .). ""
, .

55.1.1.1.

WSAAsyncSelect()

WSAAsyncSelect() Windows-
:
int WSAAsyncSelect (SOCKET sd, HWND hWnd, unsigned int wMsg, long lEvent);

, , UNIX-.
timeout.
:
sd
hWnd

wMsg
lEvent

, .
, ,
.
, , .
, ,
.

WSAAsyncSelect() 0, - SOCKET_ERROR.
:

WSAStartup()
WSANOTINITIALISED
WSAAsyncSelect().
WSAENETDOWN
.
,
WSAEINVAL
,
.
Windows 1.1,
WSAEINPROGRESS
(callback) .
WSAENOTSOCK
- .
:
: FD_CONNECT

WSAEAFNOSUPPORT
WSAECONNREFUSED
WSAENETUNREACH
WSAEFAULT
WSAEINVAL
WSAEISCONN
WSAEMFILE
WSAENOBUFS
WSAENOTCONN
WSAETIMEDOUT


.
.
namelen .
.
.
.
. .
.

.

: FD_CLOSE

WSAENETDOWN
.
WSAECONNRESET
.
WSAECONNABORTED - .
: FD_ACCEPT, FD_ADDRESS_LIST_CHANGE, FD_GROUP_QOS, FD_OOB, FD_QOS,
FD_READ, FD_WRITE

WSAENETDOWN .
: FD_ROUTING_INTERFACE_CHANGE

WSAENETUNREACH .
WSAENETDOWN
.

, , Windows
, , wMsg lEvent
:
rc = WSAAsyncSelect(s, hWnd, 0, 0);

WSAAsyncSelect() select():

select() .
WSAAsyncSelect() ,
, Uinx- FD_SET
.. .

select()
, .
Windows WSAAsyncSelect() .
, WSAAsyncSelect()
, ,

(
)
.

(Worren
Yung,
http://www.tangentsoft.net/wskfaq/)
. , ,
. Windows.

WSAAsyncSelect()
, ioctlsocket() .
WSAAsyncSelect() , .
, (
WSADuplicateSocket()),
WSAAsyncSelect() (
) .
,
,
.
WinSock 1.1 :

FD_READ
FD_WRITE
FD_OOB
FD_ACCEPT
FD_CONNECT





( )
.
FD_CLOSE
()
WinSock 2.0 :

QOS.

FD_GROUP_QOS
QOS (
).

FD_ROUTING_INTERFACE_CHANGE
.

FD_ADDRESS_LIST_CHANGE
.

.
FD_QOS

FD_READ:

WSAAsyncSelect(),
, .
2. , FD_READ .
3. recv() recvfrom() ( MSG_PEEK),
.
1.


setsockopt() SO_OOBINLINE ,
, .

FD_WRITE:
1. WSAAsyncSelect(),
send() sendto().
2. connect() accept() .
3. send() sendto(),
WSAEWOULDBLOCK, send()
sendto().
4. bind() . FD_WRITE
( ) . ,
bind().
FD_OOB: , setsockopt() SO_OOBINLINE
( ).
1. WSAAsyncSelect(),
( MSG_OOB) OOB-.
2. OOB-, FD_OOB .
3. recv() recvfrom(), / MSG_OOB , OOB .
FD_ACCEPT:
1. WSAAsyncSelect(),
.
2. , FD_ACCEPT .
3. accept(),
FD_CONNECT:
1. WSAAsyncSelect(),
.
2. connect(), , connect()
, .
3. WSAJoinLeaf(), .
4. connect(), WSAConnect(), WSAJoinLeaf()
.
WSAEWOULDBLOCK, .
, ,
FD_CONNECT .
.
FD_CLOSE:
( SOCK_STREAM).
1. WSAAsyncSelect(),
.
2. , ,
. , ,
,
, FD_CLOSE ,
.
3.
shutdown() "End of Data"
(, TCP FIN), .

4. ( TCP RST), lParam


WSAECONNRESET.

FD_CLOSE closesocket().

FD_QOS,
FD_GROUP_QOS,
FD_ROUTING_INTERFACE_CHANGE FD_ADDRESS_LIST_CHANGE -

, Windows
. , Windows :

(16- 32-).

16- , ,
32- . 16
.
wParam ,
. lParam (
FD_XXX), - , .
lParam WinSock WSAGETSELECTEVENT
WSAGETSELECTERROR . WinSock
WSAGetSelectEvent() WSAGetSelectError().
. ,
.
FD_CONNECT ,
. "
", connect(), -
accept() ( , ,
). FD_CONNECT ,
(, ).
lParam,
, .
FD_ACCEPT

. ,
.
, sd
, :
rc = WSAAsyncSelect(sd, hWnd, wMsg, FD_READ|FD_WRITE);


WSAAsyncSelect() FD_READ,
TCP- ( , ,
, ), FD_READ. ,
FD_READ TCP ,
. , SO_RCVLOWAT
TCP, FD_READ.

-, .
, WSAAsyncSelect() ,
. , WSAAsyncSelect(), ,
"connection" FD_CONNECT. ,
,

, . WSAAsyncSelect()
, ioctlsocket() FIONBIO.

WinSock
, WSAAsyncSelect().
, ,
, .

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

WSAAsyncSelect() FD_READ|FD_CLOSE ,
. FD_CLOSE,
, Microsoft , FD_CLOSE ,
, , ""
FD_CLOSE. FD_READ, FD_CLOSE.


. , accept() (
2.7.1.3), WSAAsyncSelect(), ,
:
3.7 ( )
#define W_ACCEPT
(WM_USER + 1)/* */
// sd
// W_ACCEPT
int rc;
rc = WSAAsyncSelect (sd , hWnd, W_ACCEPT , FD_ACCEPT );
if(rc > 0)
{
closesocket (sd);
MessageBox(NULL, "WSAAsyncSelect Error", "Error", MB_OK);
return;
}

sd.
FD_ACCEPT. , " "

hWnd W_ACCEPT,
.

FD_ACCEPT accept(),
"" .

3.7 WSAAsyncSelect()
:
3.8 WSAAsyncSelect()

#define WSA_NetEvent (WM_USER +1)


TCHAR szError[100];
sockaddr_in sin;
SOCKET sd;
// TCP-

//

sd = socket(AF_INET, SOCK_STREAM, 0);


if (sd == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return false;
}
//
// WSA_NetEvent : FD_READ, FD_WRITE, FD_CONNECT, FD_CLOSE
if (WSAAsyncSelect(sd, hWnd, WSA_NetEvent, FD_READ | FD_WRITE | FD_CONNECT | FD_CLOSE) ==
SOCKET_ERROR)
{
wsprintf (szError, TEXT("WSAAsyncSelect failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return false;
}
// . .
if (connect(sd, (sockaddr*)&sin_, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
int nError = WSAGetLastError();
if (nError == WSAEWOULDBLOCK)
{
MessageBox (NULL, TEXT("Asynchronous connection attempt started"),
TEXT("client"), MB_OK);
}
else {
if (sd != INVALID_SOCKET)
{
closesocket(sd);//
//
sd = INVALID_SOCKET;
wsprintf (szError, TEXT("Async connect failed. Error: %d"),
WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return false;
}
}
else {
MessageBox (NULL, TEXT("Asynch connect completed immediately!"), TEXT("client"), MB_OK);
// "" FD_CONNECT ,
// .
// , hwnd
// WSAAsyncSelect().
PostMessage(WSA_NetEvent, sd, MAKELPARAM(FD_CONNECT, 0));
}
return true;
}


WIN32 API wsprintf().
Windows sprintf(). windows.h
:
int FAR CDECL wsprintf(LPSTR lpszOut, LPCSTR lpszFmt, ...);
,
, . - , ,
. :

c

d, i

ld, li

u

lu

lx, lX

s

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

,
, "
". Win32 API ,
. , (handle) ,
FindWindow(). , .
,
,
. SetConsoleTitle(). Microsoft
(Knowledge Base KB124103) :

GetConsoleTitle(), .

SetConsoleTitle(), .

Sleep(40), .

FindWindow(NULL, uniquetitle), HWND.


HWND NULL .

SetConsoleTitle() , 1,
.

HWND . , ,
HWND , GetWindowText() HWND
, GetConsoleTitle(). , ,
HWND .
3.9 GetConsoleHwnd(),
(HWND). ,
, , NULL. ,
.
3.9
HWND GetConsoleHwnd(void)
{
#define MY_BUFSIZE 1024 // .
HWND hwndFound;
// , .
char pszNewWindowTitle[MY_BUFSIZE]; // .
char pszOldWindowTitle[MY_BUFSIZE]; // .
// .
GetConsoleTitle(pszOldWindowTitle, MY_BUFSIZE);
// "" NewWindowTitle.
wsprintf(pszNewWindowTitle,"%d/%d", GetTickCount(), GetCurrentProcessId());
// .
SetConsoleTitle(pszNewWindowTitle);
// .
Sleep(40);
// NewWindowTitle.
hwndFound=FindWindow(NULL, pszNewWindowTitle);
// .
SetConsoleTitle(pszOldWindowTitle);
return(hwndFound);
}

,
,
3.10:
3.10 :
HWND MakeWorkerWindow(void)
{
WNDCLASS wndclass;
CHAR *ProviderClass = "AsyncSelect";
HWND Window;
wndclass.style = CS_HREDRAW | CS_VREDRAW;
wndclass.lpfnWndProc = (WNDPROC)WindowProc;
wndclass.cbClsExtra = 0;
wndclass.cbWndExtra = 0;
wndclass.hInstance = NULL;
wndclass.hIcon = LoadIcon(NULL, IDI_APPLICATION);
wndclass.hCursor = LoadCursor(NULL, IDC_ARROW);
wndclass.hbrBackground = (HBRUSH) GetStockObject(WHITE_BRUSH);
wndclass.lpszMenuName = NULL;
wndclass.lpszClassName = ProviderClass;
if (RegisterClass(&wndclass) == 0)
{
printf("RegisterClass() failed with error %d\n", GetLastError());
return NULL;
}
// Create a window.
if ((Window = CreateWindow(
ProviderClass,
"",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
NULL,
NULL)) == NULL)
{
printf("CreateWindow() failed with error %d\n", GetLastError());
return NULL;
}
return Window;
}

"" 3.8 ,
, MessageLoop,
. , ,
, .
WSAIoctl()
ioctlsocket().
, .
, ,
wMsg2 FD_WRITE:
Rc = WSAAsyncSelect(sd, hWnd, wMsg1, FD_READ);
Rc = WSAAsyncSelect(sd, hWnd, wMsg2, FD_WRITE);


WSAGetLastError()
,
lParam

WS2_32.DLL
.
,
, ,
.

FD_READ
FD_WRITE
FD_OOB

recv(), recvfrom(), WSARecv() WSARecvFrom().


send(), sendto(), WSASend() WSASendTo().
recv(), recvfrom(), WSARecv() WSARecvFrom().
accept() WSAAccept().
FD_ACCEPT
WSATRY_AGAIN, ,
CF_DEFER.
FD_CONNECT
.
FD_CLOSE
.
FD_QOS
WSAIoctl() SIO_GET_QOS.
. WSAIoctl()
FD_GROUP_QOS
SIO_GET_GROUP_QOS (
).
WSAIoctl()
FD_ROUTING_INTERFACE_CHANGE
SIO_ROUTING_INTERFACE_CHANGE.
WSAIoctl()
FD_ADDRESS_LIST_CHANGE
SIO_ADDRESS_LIST_CHANGE.

55.1.1.2.

WSAAsyncGetXByY

.
"" WinSock 1.1.
, .
"database"- WSAAsyncGetXByY().
, .
.
"asynchronous task handle", ,
. , .
, .
blocking hook,
, .
-,
. , .
,
WSAAsyncGetHostByName() WSAAsyncGetHostByAddr().
WSAAsyncGetHostByName(),
,
.
WSAAsyncGetHostByName() :
struct hostent FAR * gethostbyname (const char FAR * name);
HANDLE WSAAsyncGetHostByName(
HWND
hWnd,// ,
//
unsigned int wMsg,
// ,
//

const char FAR


* name,// ,
char FAR * buf,// ,
// hostent. , ,
//
// , .
// MAXGETHOSTSTRUCT ,
// winsock.h.
int
buflen //
);


HANDLE ,
WSACancelAsyncRequest()
wParam .
, ,
WSAGetLastError().
WSAEWOULDBLOCK, ,
.
Winsock .
, ,
, -
() .
, ,
.
, ,
. ,

.
,
(, ). , ,
-.

(hidden) .
.
.
Windows' USER heap ( -"") -
.

25.
, Windows WinSock 1.1
, - Windows , ,
API Windows .
, Windows
, API
,
. , API Windows
Berkeley perror() herror(), ,
.
Windows Berkeley- errno h_errno,
"" "".
Windows Sockets : - ( thread-based)
-.
- (task-based):

1.

task-based , WSAGetLastError()
WinSock.
- :

WSAAsyncSelect() FD-
( -
WSAGETSELECTERROR (lParam)).

getsockopt() SO_ERROR (
0).
WSAStartup() ,
, , . ,
WSAGetLastError(), , WSAStartup()
, WSANOTINITIALISED.
winsock.h h_errno Berkeley ( WSAGetLastError()).
errno WINSOCK.H, errno - (, ).
()
Berkeley. WinSock BSD, WSABASEERR. WinSock API
BSD , "WSA". , , BSD
" ", errno.h Berkeley :
#define EWOULDBLOCK 35,

winsock.h :
#define WSAEWOULDBLOCK (WSABASEERR+35).

( ) WinSock
Microsoft C. ,
Windows NT .
( ) Windows.
, Windows, WinSock ,
WinSock.DLL, .
Windows WINSOCK.H.
"WSA" WSABASEERR (10000).
WSABASEERR . ,
Windows API . :
WinSock.
56.

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

WSAEADDRINUSE

(10048)

(/IP-/).

IP-/,
,
, ,
.

WSAECONNABORTED

(10053)

WSAECONNREFUSED

(10061)

WSAECONNRESET
WSAEDESTADDRREQ
WSAEHOSTUNREACH
WSAEMFILE
WSAENETDOWN

(10054)
(10039)
(10065)
(10024)
(10050)

WSAENETRESET
WSAENOBUFS
WSAENETUNREACH
WSAETIMEDOUT

(10052)
(10055)
(10051)
(10060)

WSAHOST_NOT_FOUND
WSASYSNOTREADY
WSANOTINITIALISED
WSANO_DATA

(11001)
(10091)
(10093)
(11004)

WSANO_RECOVERY
WSATRY_AGAIN

(11003)
(11002)

WSAVERNOTSUPPORTED

(10092)

57.

( TCP)



,



(
)



TCP
( )


WSAStartup()
,
( DNS)

A- (
DNS). .
winsock.dll

WSAGetLastError()

errno Windows Sockets .


, getXbyY(),
h_errno. ,
WSAGetLastError(), 3.7.5.
Windows Sockets Win32 API GetLastError().

, "-".
BSD, :
#define errno WSAGetLastError()

errno
. , , . ,
errno " ",
. , errno
. ( Windows Sockets WSASetLastError().)
BSD-:
r = recv(...);
if (r == -1 && errno == EWOULDBLOCK)
{...}

:
r = recv(...);
if (r == -1
{...}

&& WSAGetLastError() == EWOULDBLOCK)

Berkeley, ,
, "WSA" . ,
:
r = recv(...);
if (r == -1
{...}

&& WSAGetLastError() == WSAEWOULDBLOCK);

1 :
r = recv(...);

if (r == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)


{...}

58.

-
API WSAGetLastError() , "Berkeley-"
- "errno" -
. WSAGetLastError()
"per thread" -.
WSAGetLastError() ,
Microsoft C. ,
Windows Sockets, ,
Microsoft C. ,
, Microsoft C, Windows,
"WSA", .
,
, .
Windows Sockets.
WinSock API ,
Windows.

WSASetLastError()
:

, WSAGetLastError().
void PASCAL FAR WSASetLastError ( int iError );

:
,
WSAGetLastError() . , Windows
Sockets, , , .

IError
,
WSAGetLastError().
.

WSANOTINITIALISED

API WSAStartup().

WSAGetLastError()
:

, .
int WSAGetLastError (void);

:
, . API Windows
, , .

.
API Windows-, .

26. TCP- Windows



UNIX -,
. WinSock winsock.h. (#include <winsock.h>),
, WinSock. Windows-
- windows.h. , winsock.h ,
windows.h

winsock.h, windows.h, windows.h


.
:
Windows-
: <winsock2.h> WS2_32.LIB <winsock.h> WSOCK32.LIB.
, WinSock (winsock.dll wsock32.dll) .


, 3-11, 3-12,
SOCKADDR_IN. , 16-
8 , 8 _sin_zero - Unix-like
Unix-.
Windows , -, ,
TCP/UDP Windows.

. "" [14] [23].
59.

WinTCP

3.911

TCP-

#include <winsock.h>
#define PORTNUM
5000
#define HOSTNAME "localhost"

//
// .
//

main()
{
int index = 0,
iReturn;
// recv()
char szClientA[100];
// ascii
TCHAR szClientW[100];
// Unicode
TCHAR szError[100];
//
SOCKET ServerSock = INVALID_SOCKET;
//
SOCKADDR_IN destination_sin;
//
PHOSTENT phostent = NULL;
// hostent
WSADATA WSAData;
// Windows Sockets.
if (WSAStartup (MAKEWORD(1,1), &WSAData) != 0)
{
wsprintf (szError, TEXT("WSAStartup failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return FALSE;
}
// TCP-, .
if ((ServerSock = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return FALSE;
}
// .
destination_sin.sin_family = AF_INET;
// , .
if ((phostent = gethostbyname (HOSTNAME)) == NULL)
{
wsprintf (szError, TEXT("Unab1e to get the host name. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);

closesocket (ServerSock);
return FALSE;
}
// IP-
memcpy ((char FAR *)&(destination_sin.sin_addr),phostent->h_addr,phostent->h_length);
//
destination_sin.sin_port = htons (PORTNUM);
// .
if (connect (ServerSock,(PSOCKADDR) &destination_sin,sizeof (destination_sin)) == SOCKET_ERROR)
{
wsprintf (szError,TEXT("Connecting to the server failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (ServerSock);
return FALSE;
}
//
if (send (ServerSock, "To Server. ", strlen ("o Server. ")+1,0)== SOCKET_ERROR)
{
wsprintf (szError,TEXT("Sending data to the server failed. Error:%d"),WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
}
//
shutdown(ServerSock,0x01);
// .
iReturn = recv (ServerSock, szClientA, sizeof (szClientA), 0);
// , . , .
if (iReturn == SOCKET_ERROR)
{
wsprintf (szError, TEXT("No data is received, recv failed. ") ,TEXT(" Error: %d"),
WSAGetLastError());
MessageBox (NULL, szError, TEXT("Client"), MB_OK);
}
else if (iReturn == 0)
{
MessageBox (NULL, TEXT("Finished receiving data"), TEXT("client"), MB_OK);
}
else
{
// ASCII Unicode.
for (index = 0; index <= sizeof (szClientA); index++) szClientW[index] = szClientA[index];
// ,
MessageBox (NULL, szClientW, TEXT("Received From Server"), MB_OK);
}
// ServerSock.
shutdown (ServerSock, 0x02);
closesocket (ServerSock);
// .
WSACleanup ();
// .
return true;
}

60.

WinTCP

3.102 TCP
#include <winsock.h>
#define PORTNUM
5000
#define MAX_PENDING_CONNECTS 5
int main(void)
{

//

int index = 0,
iReturn;
// , recv()
char szServerA[100] ;
// ASCII
TCHAR szServerW[100];
// Unicode
TCHAR szError[100];
//
SOCKET Listen_Socket = INVALID_SOCKET;
//
SOCKET ClientSock = INVALID_SOCKET;
//
SOCKADDR_IN local_sin,
//
accept_sin;
//
int accept_sin_len;
// accept_sin
WSADATA WSAData;
// WinSock
// WinSock
if (WSAStartup (MAKEWORD(1,1), &WSAData) != 0)
{
wsprintf (szError, TEXT("WSAStartup failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return FALSE;
}
// C TCP-, Listen_socket.
if ((Listen_socket = socket (AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Allocating socket failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return false;
}
// a.
local_sin.sin_family = AF_INET;
local_sin.sin_port = htons (PORTNUM);
local_sin.sin_addr.s_addr = htonl (INADDR_ANY);
// a Listen_socket.
if (bind (Listen_socket,(struct sockaddr *) &local_sin,sizeof (local_sin)) == SOCKET_ERROR)
{
wsprintf (szError, TEXT("Binding socket failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (Listen_socket); // .
return FALSE;
}
//
if (listen (Listen_socket, MAX_PENDING_CONNECTS) == SOCKET_ERROR)
{
wsprintf (szError,TEXT("Listening to the client failed. Error: %d"), WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
closesocket (Listen_socket);
// .
return FALSE;
}
accept_sin_len = sizeof (accept_sin);
//
ClientSock = accept (Listen_socket,(struct sockaddr *) &accept_sin,(int *) &accept_sin_len);
closesocket (Listen_socket);
//
if (ClientSock == INVALID_SOCKET)
{
wsprintf (szError, TEXT("Accepting connection with client failed.") TEXT(" Error: %d"),
WSAGetLastError());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
return FALSE;
}
for (;;)
// .
{
iReturn = recv (ClientSock, szServerA, sizeof (szServerA), 0);
if (iReturn == SOCKET_ERROR) // , , , .
{

wsprintf (szError, TEXT("No data is received, recv failed. ") TEXT(" Error: %d"),
WSAGetLastError());
MessageBox (NULL, szError, TEXT("Server"), MB_OK);
break;
}
else if (iReturn == 0)
{
MessageBox (NULL, TEXT("Finished receiving data"), TEXT("Server"), MB_OK);
break;
} else
{
// ascii Unicode.
for (index = 0; index <= sizeof (szServerA); index++) szServerW[index] = szServerA[index];
// , .
MessageBox (NULL, szServerW, TEXT("Received From client"), MB_OK);
}
// .
if (send (ClientSock, "To Client. ", strlen ("To Client. ") + 1, 0) == SOCKET_ERROR)
{
wsprintf (szError,TEXT("Sending data to the client failed. Error: %d"), WSAGetLastError ());
MessageBox (NULL, szError, TEXT("Error"), MB_OK);
// ClientSock.
shutdown (ClientSock, 0x02);
closesocket (ClientSock);
// ClientSock.
}
WSACleanup();
// Windows-
return 0;
}
}

:
wsock32.lib, MFC
precompiled headers ( MS Visual C++).


1.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.

WinSock?
WinSock ?
UNIX Windows?
?
WSAStartup().
?
WSADATA?
WSAAsyncSelect() select()?
Windows-?
A,W,Ex ?
?
WinSock?


1
IPv4

/* Copyright (c) 1989, 1993


The Regents of the University of California. All rights
reserved.
* This code is derived from software contributed to Berkeley by Mike Muuss.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
*
notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*
notice, this list of conditions and the following disclaimer in the
*
documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
*
must display the following acknowledgement:
*
This product includes software developed by the University of
*
California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
*
may be used to endorse or promote products derived from this software
*
without specific prior written permission.
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
/* in_cksum -Checksum routine for Internet Protocol family headers (C Version) */
unsigned short in_cksum(unsigned short *addr, int len)
{
register int sum = 0;
u_short answer = 0;
register u_short *w = addr;
register int nleft = len;
/* Our algorithm is using a 32 bit accumulator (sum), we add sequential 16 bit words
* to it, and at the end, fold back all the carry bits from the top 16 bits into the
* lower 16 bits. */
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
/* mop up an odd byte, if necessary */
if (nleft == 1)
{
*(u_char *)(&answer) = *(u_char *)w ;
sum += answer;
}
/* add back carry outs from top 16 bits to low 16 bits */

sum = (sum >> 16) + (sum & 0xffff);


sum += (sum >> 16);
answer = ~sum;
return(answer);

/* add hi 16 to low 16 */
/* add carry */
/* truncate to 16 bits */


, TCP UDP.

2
IPV6
IPv6 3-11 .
, "Format Prefix".
IPv6,
, .


NSAP
IPX


















0000 0000
0000 000
0000 00
0000010
0000011
0000 1
0001
001
010
011
100

1/256
1/256
1/128
1/128
1/128
1/32
1/16
1/8
1/8
1/8
1/8

101
110
1110
1111 0
1111 10
1111 110
1111 11100
1111 1110 10
1111 1110 11
1111 1111

1/8
1/8
1/16
1/32
1/64
1/128
1/512
1/1024
1/1024
1/256

3
PING
,
Ping. :

(,
).
ICMP (nIcmpId nIcmpSeq)
ECHO- ECHO-.
, ECHO- , .
. Berkeley,
ICMP , IP
, ICMP .
, IP_TTL, TTL
ICMP ECHO, ICMP-
, .
- Windows.

/* ICMP types */
#define ICMP_ECHOREPLY 0
/* ICMP : */
#define ICMP_ECHOREQ 8
/* ICMP : */
/* ICMP RFC 792 */
typedef struct icmp_hdr
{
u_char icmp_type;
/* */
u_char icmp_code;
/* */
u_short icmp_cksum;
/* */
u_short icmp_id;
/* */
u_short icmp_seq;
/* */
char icmp_data[1];
/* */
} ICMP_HDR, *PICMPHDR, FAR *LPICMPHDR;
#define ICMP_HDR_LEN sizeof(ICMP_HDR)
/* IP 4 RFC 791 */
#define IPVERSION 4
typedef struct ip_hdr {
u_char ip_hl;
/* */
u_char ip_v;
/* */
u_char ip_tos;
/* */
short ip_len;
/* */
u_short ip_id;
/* */
short ip_off;
/* */
u_char ip_ttl;
/* TTL */
u_char ip_p;
/* */
u_short ip_cksum;
/* . */
struct in_addr ip_src;
/* */
struct in_addr ip_dst;
/* */
} IP_HDR, *PIP_HDR, *LPIP_HDR;
#define IP_HDR_LEN sizeof(IP_HDR)

#define PNGBUFSIZE 8192+ICMP_HDR_LEN+IP_HDR_LEN


/* */
extern void WSAErrMsg(LPSTR);
/* private */
static ICMP_HDR FAR lpIcmpHdr; /* I/O */
static IP_HDR FAR *lpIpHdr;
static char achIOBuf[PNGBUFSIZE];
static SOCKADDR_IN stFromAddr;
static DWORD lCurrentTime, lRoundTripTime;
/*
Function icmp_open()
: "" ICMP . */
SOCKET icmp_open(void) {
SOCKET s;
s = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (s == SOCKET_ERROR) {
WSAErrMsg("socket(type=SOCK_RAW, protocol=IPROTO_ICMP) ");
return (INVALID_SOCKET);
}
return (s);
} /* icmp_open() */
/* Function: icmp_sendto()
: ICMP-, ICMP
, ICMP - . */
int icmp_sendto (SOCKET s,
HWND hwnd,
LPSOCKADDR_IN lpstToAddr,
int nIcmpId,
int nIcmpSeq,
int nEchoDataLen) {
int nAddrLen = sizeof(SOCKADDR_IN);
int nRet;
u_short i;
char c;
/*--------------------- ICMP- -----------------------*/
lpIcmpHdr = (ICMP_HDR FAR *)achIOBuf;
lpIcmpHdr->icmp_type = ICMP_ECHOREQ;
lpIcmpHdr->icmp_code = 0;
lpIcmpHdr->icmp_cksum = 0;
lpIcmpHdr->icmp_id
= nIcmpId++;
lpIcmpHdr->icmp_seq
= nIcmpSeq++;
/*-------------------- ----------------------- ,
- */
lCurrentTime = GetCurrentTime();
_fmemcpy (&(achIOBuf[ICMP_HDR_LEN]),&lCurrentTime,sizeof(long));
/* ( icmp-) */
c=" ";
/* : , */
for (i=ICMP_HDR_LEN+sizeof(long);
((i < (nEchoDataLen+ICMP_HDR_LEN)) && (i < PNGBUFSIZE));i++) {
achIOBuf[i] = c;
c++;
if (c > "~") /* ASCII 126, 32 */
c= " ";
}
/*---------------------- ICMP --------------------- ICMP ICMP- , 0 */
lpIcmpHdr->icmp_cksum =
cksum((u_short FAR *)lpIcmpHdr, nEchoDataLen+ICMP_HDR_LEN);
/*--------------------- ICMP -------------------*/
nRet = sendto (s,
/* */

(LPSTR)lpIcmpHdr,
/* */
nEchoDataLen+ICMP_HDR_LEN+sizeof(long),
/* */
0,
/* */
(LPSOCKADDR)lpstToAddr,
/* */
sizeof(SOCKADDR_IN));
/* */
if (nRet == SOCKET_ERROR) {
WSAErrMsg("sendto()");
}
return (nRet);
} /* icmp_sendto() */
/* Function: icmp_recvfrom()
: icmp -,
ICMP . */
u_long icmp_recvfrom(SOCKET s, LPINT lpnIcmpId, LPINT lpnIcmpSeq, LPSOCKADDR_IN lpstFromAddr)
{
u_long lSendTime;
int nAddrLen = sizeof(struct sockaddr_in);
int nRet, i;
/*-------------------- ICMP - ------------------*/
stFromAddr.sin_family = AF_INET;
stFromAddr.sin_addr.s_addr = INADDR_ANY;
stFromAddr.sin_port = 0;
nRet = recvfrom (s,
/* */
(LPSTR)achIOBuf,
/* */
PNGBUFSIZE+ICMP_HDR_LEN+sizeof(long)+IP_HDR_LEN,
/* */
0,
/* */
(LPSOCKADDR)lpstFromAddr,
/* */
&nAddrLen);
/* */
if (nRet == SOCKET_ERROR) {
WSAErrMsg("recvfrom()");
}
/*------------------------- -------------------------- . : ,
Berkeley Sockets. , IP-,
. ,
, IP- ( 0x45 ). */
/* */
if (achIOBuf[0] == 0x45) { /* IP- ? */
i = IP_HDR_LEN + ICMP_HDR_LEN;
lpIcmpHdr = (LPICMPHDR) &(achIOBuf[IP_HDR_LEN]);
} else {
i = ICMP_HDR_LEN;
lpIcmpHdr = (LPICMPHDR) achIOBuf;
}
/* ICMP ID */
*lpnIcmpId = lpIcmpHdr->icmp_id;
*lpnIcmpSeq = lpIcmpHdr->icmp_seq;
/* ICMP- */
_fmemcpy (&lSendTime, (&achIOBuf[i]), sizeof(u_long));
return (lSendTime);
} /* end icmp_recvfrom() */
/* Function: cksum()

(one's complement sum of 16-bit words). IP, ICMP, UDP, IGMP. */
u_short cksum (u_short FAR*lpBuf, int nLen) {
register long lSum = 0L; /* */
/* : , ()
0 */
while (nLen > 0) {
lSum += (lpBuf++);
/* */

nLen -= 2;
/* 2 */
}
/* 32-bit 16-bit */
lSum = (lSum & 0xffff) + (lSum>>16);
lSum += (lSum >> 16);
/* .*/
return (~lSum);
} /* cksum() */

4
Log- 3- Internet-
Packet #1, Direction: Out, Time:20:55:56,780

MAC- DNS

Ethernet II

Destination MAC: FF:FF:FF:FF:FF:FF
,,
Source MAC: 44:45:53:54:00:00
MAC
Ethertype: 0x0806 (2054)
2054 (ARP)
ARP
Hardware: 0x0001 (1) Ethernet

Protocol: 0x0800 (2048) IP
IP
Hardware address length: 0x06 (6)
6
Protocol address length: 0x04 (4)
4
Operation: 0x0001 (1) ARP Request
ARP-
Sender MAC address: 44:45:53:54:00:00
MAC
Sender IP address: 195.216.161.32
IP-
Target MAC address: 00:00:00:00:00:00
MAC-
Target IP address: 195.216.160.130
IP-
Raw Data:
0x0000
FF FF FF FF FF FF 44 45-53 54 00 00 08 06 00 01
DEST......
0x0010
08 00 06 04 00 01 44 45-53 54 00 00 C3 D8 A1 20
......DEST..
0x0020
00 00 00 00 00 00 C3 D8-A0 82
......

Packet #2, Direction: Out, Time:20:55:56,780


Ethernet II
Destination MAC: 20:53:52:43:00:00
Source MAC: 44:45:53:54:00:00
Ethertype: 0x0800 (2048) IP
IP
IP version: 0x04 (4)
Header length: 0x05 (5) 20 bytes
Type of service: 0x00 (0)
Precedence: 000 Routine
Delay: 0 Normal delay
Throughput: 0 Normal throughput
Reliability: 0 Normal reliability
Total length: 0x003A (58)
ID: 0xF900 (63744)
Flags
Don't fragment bit: 0 May fragment
More fragments bit: 0 Last fragment
Fragment offset: 0x0000 (0)
Time to live: 0x80 (128)
Protocol: 0x11 (17) UDP
Checksum: 0x785E (30814) correct
Source IP: 195.216.161.32
Destination IP: 195.216.160.130
IP Options: None
UDP
Source port: 1055
Destination port: 53
Length: 0x0026 (38)

DNS

Mac-
MAC
2048 (IP)
IP-
IP- 4
20
TOS 0




58
63744

DF 0
MF 0
0
IP TTL 128
UDP

IP
IP DNS

UDP
1055
DNS-53
UDP-

DNS

Checksum: 0x5648 (22088) correct


DNS-

ID: 0x0009 (9)


Response packet: 0
Operation code: 0x00 (0) Standard query
Flags
Authoritative Answer: 0
Truncation: 0
Recursion Desired: 1
Recursion Available: 0
Result code: 0x00 (0) Success
Question records: 0x0001 (1)
Answer records: 0x0000 (0)
Authority records: 0x0000 (0)
Additional records: 0x0000 (0)
Question section
Record: 0x1 (1)
Name: www.aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
Raw Data:
0x0000
0x0010
0x0020
0x0030
0x0040

20
00
A0
00
02

53
3A
82
00
72

52
F9
04
00
75

43
00
1F
00
00

00
00
00
00
00

00
00
35
00
01

44
80
00
03
00

45-53
11-78
26-56
77-77
01-

54
5E
48
77

00
C3
00
05

00
D8
09
61

08
A1
01
70

00
20
00
6F





1
www.aport.ru


45
C3
00
72

Packet #3, Direction: In, Time:20:55:56,950


Ethernet II
Destination MAC: 44:45:53:54:00:00
Source MAC: 20:53:52:43:00:00
Ethertype: 0x0800 (2048) IP
IP
IP version: 0x04 (4)
Header length: 0x05 (5) 20 bytes
Type of service: 0x00 (0)
Precedence: 000 Routine
Delay: 0 Normal delay
Throughput: 0 Normal throughput
Reliability: 0 Normal reliability
Total length: 0x00C6 (198)
ID: 0x38A2 (14498)
Flags
Don't fragment bit: 0 May fragment
More fragments bit: 0 Last fragment
Fragment offset: 0x0000 (0)
Time to live: 0x3E (62)
Protocol: 0x11 (17) UDP
Checksum: 0x7A31 (31281) correct
Source IP: 195.216.160.130
Destination IP: 195.216.161.32
IP Options: None
UDP
Source port: 53
Destination port: 1055
Length: 0x00B2 (178)
Checksum: 0x7C3F (31807) correct
DNS
ID: 0x0009 (9)
Response packet: 1
Operation code: 0x00 (0) Standard query
Flags
Authoritative Answer: 0
Truncation: 0
Recursion Desired: 1

00
D8
01
74

SRC..DEST....E.
.:....x^
...5.&VH......
.......www.aport
.ru.....

DNS

Recursion Available: 1
Result code: 0x00 (0) Success
Question records: 0x0001 (1)
Answer records: 0x0002 (2)
Authority records: 0x0003 (3)
Additional records: 0x0003 (3)
Question section
Record: 0x1 (1)
Name: www.aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
Answer section
Record: 0x1 (1)

Name: www.aport.ru
Type: 0x0005 (5) CNAME
Class: 0x0001 (1) IN
TTL: 1534 25 Minutes 34 sec
CNAME: aport.ru
Record: 0x2 (2)
Name: aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 1534 25 Minutes 34 sec
IP address: 194.67.26.89
Authority section
Record: 0x1 (1)
Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns1.gldn.net
Record: 0x2 (2)
Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns2.gldn.net

Record: 0x3 (3)


Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns3.gldn.net
Additional section
Record: 0x1 (1)
Name: ns1.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.2.108
Record: 0x2 (2)
Name: ns2.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.2.109
Record: 0x3 (3)
Name: ns3.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.7.1

TTL DNS- cache


32 !

IP- www.aport.ru

. RFC 1034

Raw Data:
0x0000
44
0x0010
00
0x0020
A1
0x0030
00

45
C6
20
02

53
38
00
00

54
A2
35
03

00
00
04
00

00
00
1F
03

20
3E
00
03

53-52
11-7A
B2-7C
77-77

43
31
3F
77

00
C3
00
05

00
D8
09
61

08
A0
81
70

00
82
80
6F

45
C3
00
72

00
D8
01
74

DEST.. SRC....E.
.8...>.z1
.5...|?....
.......www.aport

5
( IANA)

1. ()

1
2
3
5
7
9
11
13
15
17
18
19
20
21
22
23
24
25
27
29
31
33
35
37
38
39
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

TCP-MUX - TCP Port Service Multiplexer


COMPRESSNET - Management Utility
COMPRESSNET - Compression Process
RJE - Remote Job Entry
ECHO - Echo
DISCARD - Discard
SYSSTAT - System Status
DAYTIME - Daytime
NETSTAT - Network Status
QOTD - Quote of the Day
MSP - Message Send Protocol
CHARGEN - Character Generator
FTP-DATA - File Transfer Protocol [Default Data]
FTP - File Transfer Protocol [Control]
SSH - SSH (Secure Shell) Remote Login Protocol
TELNET - Telnet
PMS - Private Mail System
SMTP - Simple Mail Transfer Protocol
NSW-FE - NSW User System FE
MSG-ICP - Messege ICP
MSG-AUTH - Messege Authentication
DSP - Display Support Protocol
PPS - Private Printer Server
TIME - Time
RAP - Route Access Protocol
RLP - Resource Location Protocol
GRAPHICS - Graphics
NAMESERVER - Host Name Server
WHOIS - Who Is
MPM-FLAGS - MPM FLAGS Protocol
MPM - Message Processing Module [recv]
MPM-SND - MPM [default send]
NI-FTP - NI FTP (File Transfer Protocol)
AUDITD - Digital Audit Daemon
BBN-LOGIN - Login Host Protocol (TACACS)
RE-MAIL-CK - Remote Mail Checking Protocol
LA-MAINT - IMP Logical Address Maintenance
XNS-TIME - XNS Time Protocol
DOMAIN - Domain Name Server
XNS-CH - XNS Clearinghouse
ISI-GL - ISI Graphics Language
XNS-AUTH - XNS Authentication
MTP - Private terminal access

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

XNS-MAIL - XNS Mail


PFS - Private File System
Unassigned
NI-MAIL - NI MAIL
ACAS - ACA Services
WHOIS++ - whois++
COVIA - Communications Integrator (CI)
TACACS-DS - TACACS-Database Service
SQL*NET - Oracle SQL*NET
BOOTPS - Bootstrap Protocol Server
BOOTPC - Bootstrap Protocol Client
TFTP - Trivial File Transfer Protocol
GOPHER - Gopher
NETRJS-1 - Remote Job Service
NETRJS-2 - Remote Job Service
NETRJS-3 - Remote Job Service
NETRJS-4 - Remote Job Service
PDOS - Private dial out service
DEOS - Distributed External Object Store
RJE - Private RJE (Remote Job Entry) service
VETTCP - vettcp
FINGER - Finger
WWW-HTTP - World Wide Web HTTP (Hyper Text Transfer Protocol)
HOSTS2-NS - HOSTS2 Name Server
XFER - XFER Utility
MIT-ML-DEV - MIT ML Device
CTF - Common Trace Facility
MIT-ML-DEV - MIT ML Device
MFCOBOL - Micro Focus Cobol
LINK - Private terminal link
KERBEROS - Kerberos
SU-MIT-TG - SU/MIT Telnet Gateway
DNSIX - DNSIX Securit Attribute Token Map
MIT-DOV - MIT Dover Spooler
NPP - Network Printing Protocol
DCP - Device Control Protocol
OBJCALL - Tivoli Object Dispatcher
SUPDUP - SUPDUP
DIXIE - DIXIE Protocol Specification
SWIFT-RVF - Swift Remote Virtural File Protocol
TACNEWS - TAC News
METAGRAM - Metagram Relay
NEWACCT - [unauthorized use]
HOSTNAMES - NIC Host Name Server
ISO-TSAP - ISO-TSAP Class 0
X400 - x400
X400-SND - x400-snd
CSNET-NS - Mailbox Name Nameserver
3COM-TSMUX - 3COM-TSMUX
RTELNET - Remote Telnet Service
SNAGAS - SNA Gateway Access Server
POP - Post Office Protocol - Version 2
POP3 - Post Office Protocol - Version 3
SUNRPC - SUN Remote Procedure Call
MCIDAS - McIDAS Data Transmission Protocol
IDENT - Authentication Service
AUDIONEWS - Audio News Multicast
SFTP - Simple File Transfer Protocol
ANSANOTIFY - ANSA REX Notify
UUCP-PATH - UUCP Path Service

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

SQLSERV - SQL Services


NNTP - Network News Transfer Protocol
CFDPTKT - CFDPTKT
ERPC - Encore Expedited Remote Pro.Call
SMAKYNET - SMAKYNET
NTP - Network Time Protocol
ANSATRADER - ANSA REX Trader
LOCUS-MAP - Locus PC-Interface Net Map Ser
UNITARY - Unisys Unitary Login
LOCUS-CON - Locus PC-Interface Conn Server
GSS-XLICEN - GSS X License Verification
PWDGEN - Password Generator Protocol
CISCO-FNA - cisco FNATIVE
CISCO-TNA - cisco TNATIVE
CISCO-SYS - cisco SYSMAINT
STATSRV - Statistics Service
INGRES-NET - INGRES-NET Service
RPC-LOCATOR - RPC (Remote Procedure Call) Location Service
PROFILE - PROFILE Naming System
NETBIOS-NS - NETBIOS Name Service
NETBIOS-DGM - NETBIOS Datagram Service
NETBIOS-SSN - NETBIOS Session Service
EMFIS-DATA - EMFIS Data Service
EMFIS-CNTL - EMFIS Control Service
BL-IDM - Britton-Lee IDM
IMAP - Interim Mail Access Protocol v2
NEWS - NewS
UAAC - UAAC Protocol
ISO-TP0 - ISO-IP0
ISO-IP - ISO-IP
CRONUS - CRONUS-SUPPORT
AED-512 - AED 512 Emulation Service
SQL-NET - SQL-NET
HEMS - HEMS
BFTP - Background File Transfer Program
SGMP - SGMP
NETSC-PROD - NETSC
NETSC-DEV - NETSC
SQLSRV - SQL Service
KNET-CMP - KNET/VM Command/Message Protocol
PCMAIL-SRV - PCMail Server
NSS-ROUTING - NSS-Routing
SGMP-TRAPS - SGMP-TRAPS
SNMP - SNMP (Simple Network Management Protocol)
SNMPTRAP - SNMPTRAP (Simple Network Management Protocol)
CMIP-MAN - CMIP/TCP Manager
CMIP-AGENT - CMIP/TCP Agent
XNS-COURIER - Xerox
S-NET - Sirius Systems
NAMP - NAMP
RSVD - RSVD
SEND - SEND
PRINT-SRV - Network PostScript
MULTIPLEX - Network Innovations Multiplex
CL/1 - Network Innovations CL/1
XYPLEX-MUX - Xyplex
MAILQ - MAILQ
VMNET - VMNET
GENRAD-MUX - GENRAD-MUX
XDMCP - X Display Manager Control Protocol

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
242
243
244
245
246
247
248
256
257
258
259
260
261
262

NEXTSTEP - NextStep Window Server


BGP - Border Gateway Protocol
RIS - Intergraph
UNIFY - Unify
AUDIT - Unisys Audit SITP
OCBINDER - OCBinder
OCSERVER - OCServer
REMOTE-KIS - Remote-KIS
KIS - KIS Protocol
ACI - Application Communication Interface
MUMPS - Plus Five's MUMPS
QFT - Queued File Transport
GACP - Gateway Access Control Protocol
PROSPERO - Prospero Directory Service
OSU-NMS - OSU Network Monitoring System
SRMP - Spider Remote Monitoring Protocol
IRC - Internet Relay Chat Protocol
DN6-NLM-AUD - DNSIX Network Level Module Audit
DN6-SMM-RED - DNSIX Session Mgt Module Audit Redir
DLS - Directory Location Service
DLS-MON - Directory Location Service Monitor
SMUX - SMUX
SRC - IBM System Resource Controller
AT-RTMP - AppleTalk Routing Maintenance
AT-NBP - AppleTalk Name Binding
AT-3 - AppleTalk Unused
AT-ECHO - AppleTalk Echo
AT-5 - AppleTalk Unused
AT-ZIS - AppleTalk Zone Information
AT-7 - AppleTalk Unused
AT-8 - AppleTalk Unused
QMTP - The Quick Mail Transfer Protocol
Z39.50 - ANSI Z39.50
914C/G - Texas Instruments 914C/G Terminal
ANET - ATEXSSTR
IPX - IPX
VMPWSCS - VM PWSCS
SOFTPC - Insignia Solutions
CAILIC - Computer Associates Int'l License Server
DBASE - dBASE Unix
MPP - Netix Message Posting Protocol
UARPS - Unisys ARPs
IMAP3 - Interactive Mail Access Protocol v3
FLN-SPX - Berkeley rlogind with SPX auth
RSH-SPX - Berkeley rshd with SPX auth
CDC - Certificate Distribution Center
DIRECT
SUR-MEAS - Survey Measurement
DAYNA
LINK - LINK
DSP3270 - Display Systems Protocol
SUBNTBCST_TFTP
BHFHS
RAP
SET - Secure Electronic Transaction
YAK-CHAT - Yak Winsock Personal Chat
ESRO-GEN - Efficient Short Remote Operations
OPENPORT
NSIIOPS - IIOP Name Service Over TLS/SSL
ARCISDMS

263
264
280
281
282
308
309
310
311
312
313
314
315
316
317
321
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
387
388

HDAP
BGMP
HTTP-MGMT
PERSONAL-LINK
CABLEPORT-AX - Cable Port A/X
NOVASTORBAKCUP - Novastor Backup
ENTRUSTTIME
BHMDS
ASIP-WEBADMIN - Appleshare IP Webadmin
VSLMP
MAGENTA-LOGIC
OPALIS-ROBOT
DPSI
DECAUTH
ZANNET
PIP
PDAP - Prospero Data Access Protocol
PAWSERV - Perf Analysis Workbench
ZSERV - Zebra server
FATSERV - Fatmen Server
CSI-SGWP - Cabletron Management Protocol
MFTP
MATIP-TYPE-A - MATIP Type A
MATIP-TYPE-B - MATIP Type B or bhoetty
DTAG-STE-SB - DTAG, or bhoedap4
NDSAUTH
BH611
DATEX-ASN
CLOANTO-NET-1 - Cloanto Net 1
BHEVENT
SHRINKWRAP
TENEBRIS_NTS - Tenebris Network Trace Service
SCOI2ODIALOG
SEMANTIX
SRSSEND - SRS Send
RSVP_TUNNEL
AURORA-CMGR
DTK - Deception Tool Kit
ODMR
MORTGAGEWARE
QBIKGDP
RPC2PORTMAP
CODAAUTH2
CLEARCASE - Clearcase
ULISTSERV - Unix Listserv
LEGENT-1 - Legent Corporation
LEGENT-2 - Legent Corporation
HASSLE - Hassle
NIP - Amiga Envoy Network Inquiry Proto
TNETOS - NEC Corporation
DSETOS - NEC Corporation
IS99C - TIA/EIA/IS-99 modem client
IS99S - TIA/EIA/IS-99 modem server
HP-COLLECTOR - HP Performance Data Collector
HP-MANAGED-NODE - HP Performance Data Managed Node
HP-ALARM-MGR - HP Performance Data Alarm Manager
ARNS - A Remote Network Server System
IBM-APP - IBM Application 386 ASA - ASA Message Router Object Def.
AURP - Appletalk Update-Based Routing Pro.
UNIDATA-LDM - Unidata LDM Version 4

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

LDAP - Lightweight Directory Access Protocol


UIS - UIS
SYNOTICS-RELAY - SynOptics SNMP Relay Port
SYNOTICS-BROKER - SynOptics Port Broker Port
DIS - Data Interpretation System
EMBL-NDT - EMBL Nucleic Data Transfer
NETCP - NETscout Control Protocol
NETWARE-IP - Novell Netware over IP
MPTN - Multi Protocol Trans. Net.
KRYPTOLAN - Kryptolan
ISO-TSAP-C2 - ISO Transport Class 2 Non-Control over TCP
WORK-SOL - Workstation Solutions
UPS - Uninterruptible Power Supply
GENIE - Genie Protocol
DECAP - decap
NCED - nced
NCLD - ncld
IMSP - Interactive Mail Support Protocol
TIMBUKTU - Timbuktu
PRM-SM - Prospero Resource Manager Sys. Man.
PRM-NM - Prospero Resource Manager Node Man.
DECLADEBUG - DECLadebug Remote Debug Protocol
RMT - Remote MT Protocol
SYNOPTICS-TRAP - Trap Convention Port
SMSP - SMSP
INFOSEEK - InfoSeek
BNET - BNet
SILVERPLATTER - Silverplatter
ONMUX - Onmux
HYPER-G - Hyper-G
ARIEL1 - Ariel
SMPTE - SMPTE
ARIEL2 - Ariel
ARIEL3 - Ariel
OPC-JOB-START - IBM Operations Planning and Control Start
OPC-JOB-TRACK - IBM Operations Planning and Control Track
ICAD-EL - ICAD
SMARTSDP - smartsdp
SVRLOC - Server Location
OCS_CMU - OCS_CMU
OCS_AMU - OCS_AMU
UTMPSD - UTMPSD
UTMPCD - UTMPCD
IASD - IASD
NNSP - NNSP
MOBILEIP-AGENT - MobileIP-Agent
MOBILIP-MN - MobilIP-MN
DNA-CML - DNA-CML
COMSCM - comscm
DSFGW - dsfgw
DASP - dasp
SGCP - sgcp
DECVMS-SYSMGT - decvms-sysmgt
CVC_HOSTD - cvc_hostd
HTTPS - HTTPS (Hyper Text Transfer Protocol Secure) - SSL (SecureSocket Layer)
SNPP - Simple Network Paging Protocol
MICROSOFT-DS - Microsoft-DS
DDM-RDB - DDM-RDB
DDM-DFM - DDM-RFM
DDM-BYTE - DDM-BYTE

449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508

AS-SERVERMAP - AS Server Mapper


TSERVER - TServer
SFS-SMP-NET - Cray Network Semaphore server
SFS-CONFIG - Cray SFS config server
CREATIVESERVER - CreativeServer
CONTENTSERVER - ContentServer
CREATIVEPARTNR - CreativePartnr
MACON-TCP - macon-tcp
SCOHELP - scohelp
APPLEQTC - Apple Quick Time
AMPR-RCMD - ampr-rcmd
SKRONK - skronk
DATASURFSRV - DataRampSrv
DATASURFSRVSEC - DataRampSrvSec
ALPES - alpes
KPASSWD - kpasswd
SSMTP - ssmtp
DIGITAL-VRC - digital-vrc
MYLEX-MAPD - mylex-mapd
PHOTURIS - proturis
RCP - Radio Control Protocol
SCX-PROXY - scx-proxy
MONDEX - Mondex
LJK-LOGIN - ljk-login
HYBRID-POP - hybrid-pop
TN-TL-W1 - tn-tl-w1
TCPNETHASPSRV - tcpnethaspsrv
TN-TL-FD1 - tn-tl-fd1
SS7NS - ss7ns
SPSC - spsc
IAFSERVER - iafserver
IAFDBASE - iafdbase
PH - Ph service
BGS-NSI - bgs-nsi
ULPNET - ulpnet
INTEGRA-SME - Integra Software Management Environment
POWERBURST - Air Soft Power Burst
AVIAN - avian
SAFT - saft
GSS-HTTP - gss-http
NEST-PROTOCOL - nest-protocol
MICOM-PFS - micom-pfs
GO-LOGIN - go-login
TICF-1 - Transport Independent Convergence for FNA
TICF-2 - Transport Independent Convergence for FNA
POV-RAY - POV-Ray
INTECOURIER
PIM-RP-DISC
DANTZ
SIAM
ISO-ILL - ISO ILL Protocol
ISAKMP
STMF
ASA-APPL-PROTO
INTRINSA
CITADEL
MAILBOX-LM
OHIMSRV
CRS
XVTTP

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568

SNARE
FCP - FirstClass Protocol
PASSGO EXEC - Remote Process Execution
LOGIN - Remote Login via Telnet;
SHELL - Automatic Remote Process Execution
PRINTER - Printer Spooler
VIDEOTEX
TALK
NTALK
UTIME - Unix Time
EFS - Extended File Server
RIPNG
ULP
IBM-DB2
NCP
TIMED - Time Server
TEMPO - newdate
STX - Stock IXChange
CUSTIX - Customer IXChange
IRC-SERV
COURIER - rpc
CONFERENCE - chat
NETNEWS - readnews
NETWALL - Emergency Broadcasts
MM-ADMIN - MegaMedia Admin
IIOP
OPALIS-RDV
NMSP - Networked Media Streaming Protocol
GDOMAP
APERTUS-LDP - Apertus Technologies Load Determination
UUCP - UUCPD (Unix to Unix Copy)
UUCP-RLOGIN - uucp (Unix to Unix Copy) - rlogin (Remote Login)
COMMERCE
KLOGIN
KSHELL - krcmd
APPLEQTCSRVR - Apple qtcsrvr
DHCP-CLIENT - DHCP (Dynamic Host Configuration Protocol) Client
DHCP-SERVER - DHCP (Dynamic Host Configuration Protocol) Server
AFPOVERTCP - AFP over TCP
IDFP
NEW-RWHO - new-who
CYBERCASH - CyberCash
DEVICESHARE - deviceshare
PIRP - pirp
RTSP - Real Time Stream Control Protocol
DSF
REMOTEFS - rfs (Remote File System) server
OPENVMS-SYSIPC - openvms-sysipc
SDNSKMP - SDNSKMP
TEEDTAP - TEEDTAP
RMONITOR - rmonitord
MONITOR
CHSHELL - chcmd
SNEWS - snews
9PFS - plan 9 file service
WHOAMI - whoami
STREETTALK - streettalk
BANYAN-RPC - banyan-rpc
MS-SHUTTLE - Microsoft Shuttle

569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
606
607
608
609
610
611
628
633
634
635
636
640
650
666
674
704
709
729
730
731
737
740
741
742
744
747
748
749

MS-ROME - Microsoft Rome


METER - demon
METER - udemon
SONAR - sonar
BANYAN-VIP - banyan-vip
FTP-AGENT - FTP Software Agent System
VEMMI - VEMMI
IPCD
VNAS
IPDD
DECBSRV
SNTP-HEARTBEAT BDP - Bundle Discovery Protocol
SCC-SECURITY
PHILIPS-VC - PHilips Video-Conferencing
KEYSERVER
IMAP4-SSL - IMAP4+SSL
PASSWORD-CHG
SUBMISSION
CAL
EYELINK
TNS-CML
HTTP-ALT - FileMaker, Inc. - HTTP Alternate
EUDORA-SET HTTP-RPC-EPMAP - HTTP RPC Ep Map
TPIP CAB-PROTOCOL SMSD PTCNAMESERVICE - PTC Name Service
SCO-WEBSRVRMG3 - SCO Web Server Manager 3
ACP - Aeolon Core Protocol
IPCSERVER - Sun IPC server
URM - Cray Unified Resource Manager
NQS - nqs
SIFT-UFT - Sender-Initiated/Unsolicited File Transfer
NPMP-TRAP - npmp-trap
NPMP-LOCAL - npmp-local
NPMP-GUI - npmp-gui
QMQP - Qmail Quick Mail Queueing
SERVSTAT - Service Status update (Sterling Software)
GINAD - ginad
MOUNT - NFS Mount Service
LDAPSSL - LDAP Over SSL
PCNFS - PC-NFS DOS Authentication
BWNFS - BW-NFS DOS Authentication
DOOM - doom Id Software
PORT
ELCSD - errlog copy/server daemon
ENTRUSTMANAGER - EntrustManager
NETVIEWDM1 - IBM NetView DM/6000 Server/Client
NETVIEWDM2 - IBM NetView DM/6000 send/tcp
NETVIEWDM3 - IBM NetView DM/6000 receive/tcp
SOMETIMES-RPC2 - Rusersd on my OpenBSD Box
NETCP - NETscout Control Protocol
NETGW - netGW
NETRCS - Network based Rev. Cont. Sys.
FLEXLM - Flexible License Manager
FUJITSU-DEV - Fujitsu Device Control
RIS-CM - Russell Info Sci Calendar Manager
KERBEROS-ADM - kerberos administration

750
751
752
753
754
758
759
760
761
762
763
764
765
767
769
770
771
772
773
774
775
776
780
781
782
783
786
799
800
801
808
871
888
901
911
989
990
992
993
995
996
997
998
999
1000
1001
1008
1010
1011
1012
1015
1023

KERBEROS-SEC
KERBEROS_MASTER
QRH
RRH
KBR5_PROP
NLOGIN
CON
NS
RXE
QUOTAD
CYCLESERV
OMSERV
WEBSTER
PHONEBOOK - phone
VID
CADLOCK
RTIP
CYCLESERV2
SUBMIT
RPASSWD
ENTOMB
WPAGES
WPGS
HP-COLLECTOR - HP Performance Data Collector
HP-MANAGED-NODE - HP Performance Data Managed Node
HP-ALARM-MGR - HP Performance Data Alarm Manager
CONCERT - Concert
CONTROLIT
MDBS_DAEMON
DEVICE
PORT
SUPFILESRV -SUP Server
CDDATABASE - CDDataBase
PORT
Dark Shadow
FTPS-DATA - FTP Over TLS/SSL
FTP Control TLS/SSL
TELNETS - telnet protocol over TLS/SSL
IMAPS - Imap4 protocol over TLS/SSL
POP3S - Pop3 (Post Office Protocol) over TLS/SSL
VSINET - vsinet
MAITRD
BUSBOY
PUPROUTER
CADLOCK
Silence
UFSD - UFSD
Doly-Trojan
Doly-Trojan
Doly-Trojan
Doly-Trojan
RESERVED Reserved

2.

1024
OLD_FINGER - old_finger
1025
LISTEN - listen
1026
NTERM - nterm
1027
NT
1028
NT

1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1058
1059
1067
1068
1080
1083
1084
1090
1103
1109
1110
1112
1127
1155
1167
1170
1178
1212
1222
1234
1241
1243
1245
1248
1269
1330
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358

NT
IAD1 - BBN IAD
IAD2 - BBN IAD
IAD3 - BBN IAD
NT
NT
NT
NT
NT
NT
NT
NT
NT
Bla
NT
NT
Rasmin
NT
NT
NT
NT
NIM - nim
NIMREG - nimreg
INSTL_BOOTS - Installation Bootstrap Proto. Serv.
INSTL_BOOTC - Installation Bootstrap Proto. Cli.
SOCKS - Socks
ANSOFT-LM-1 - Anasoft License Manager
ANSOFT-LM-2 - Anasoft License Manager
Xtreme
XAUDIO - Xaserver
KPOP - kpop
NFSD-STATUS - Cluster Status Info
MSQL - Mini-SQL Server
SUPFILEDBG - SUP Debugging
NFA - Network File Access
PHONE - Conference Calling
Psyber Stream Server, Streaming Audio trojan, Voice
SKKSERV - SKK (Kanji Input)
LUPA - lupa
NERV - SNI R&D network
Ultors Trojan
MSG - Remote Message Server
BackDoor-G, SubSeven, SubSeven Apocalypse
Voodoo Doll
HERMES - Multi Media Conferencing
Mavericks Matrix
PORT
ALTA-ANA-LM - Alta Analytics License Manager
BBN-MMC - Multi Media Conferencing
BBN-MMX - Multi Media Conferencing
SBOOK - Registration Network Protocol
EDITBENCH - Registration Network Protocol
EQUATIONBUILDER - Digital Tool Works (MIT)
LOTUSNOTE - Lotus Note
RELIEF - Relief Consulting
RIGHTBRAIN - RightBrain Software
INTUITIVE EDGE - Intuitive Edge
CUILLAMARTIN - CuillaMartin Company
PEGBOARD - Electronic PegBoard
CONNLCLI - CONNLCLI

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418

FTSRV - FTSRV
MIMER - MIMER
LINX - LinX
TIMEFLIES - TimeFlies
NDM-REQUESTER - Network DataMover Requester
NDM-SERVER - Network DataMover Server
ADAPT-SNA - Network Software Associates
NETWARE-CSP - Novell NetWare Comm Service Platform
DCS - DCS
SCREENCAST - ScreenCast
GV-US - GlobalView to Unix Shell
US-GV - Unix Shell to GlobalView
FC-CLI - Fujitsu Config Protocol
FC-SER - Fujitsu Config Protocol
CHROMAGRAFX - Chromagrafx
MOLLY - EPI Software Systems
BYTEX - Bytex
IBM-PPS - IBM Person to Person Software
CICHLID - Cichlid License Manager
ELAN - Elan License Manager
DBREPORTER - Integrity Solutions
TELESIS-LICMAN - Telesis Network License Manager
APPLE-LICMAN - Apple Network License Manager
UDT_OS GWHA - GW Hannaway Network License Manager
OS-LICMAN - Objective Solutions License Manager
ATEX_ELMD - Atex Publishing License Manager
CHECKSUM - CheckSum License Manager
CADSI-LM - Computer Aided Design Software Inc LM
OBJECTIVE-DBC - Objective Solutions DataBase Cache
ICLPV-DM - Document Manager
ICLPV-SC - Storage Controller
ICLPV-SAS - Storage Access Server
ICLPV-PM - Print Manager
ICLPV-NLS - Network Log Server
ICLPV-NLC - Network Log Client
ICLPV-WSM - PC Workstation Manager software
DVL-ACTIVEMAIL - DVL Active Mail
AUDIO-ACTIVMAIL - Audio Active Mail
VIDEO-ACTIVMAIL - Video Active Mail
CADKEY-LICMAN - Cadkey License Manager
CADKEY-TABLET - Cadkey Tablet Daemon
GOLDLEAF-LICMAN - Goldleaf License Manager
PRM-SM-NP - Prospero Resource Manager
PRM-NM-NP - Prospero Resource Manager
IGI-LM - Infinite Graphics License Manager
IBM-RES - IBM Remote Execution Starter
NETLABS-LM - NetLabs License Manager
DBSA-LM - DBSA License Manager
SOPHIA-LM - Sophia License Manager
HERE-LM - Here License Manager
HIQ - HiQ License Manager
AF - AudioFile
INNOSYS - InnoSys
INNOSYS-ACL - Innosys-ACL
IBM-MQSERIES - IBM MQSeries
DBSTAR - DBStar
NOVELL-LU6.2 - Novell LU6.2
TIMBUKTU-SRV1 - Timbuktu Service 1 Port
TIMBUKTU-SRV2 - Timbuktu Service 2 Port

1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478

TIMBUKTU-SRV3 - Timbuktu Service 3 Port


TIMBUKTU-SRV4 - Timbuktu Service 4 Port
GANDALF-LM - Gandalf License Manager
AUTODESK-LM - Autodesk License Manager
ESSBASE - Essbase Arbor Software
HYBRID - Hybrid Encryption Protocol
ZION-LM - Zion Software License Manager
SAIS - Satellite-data Acquisition System 1
MLOADD - mloadd monitoring tool
INFORMATIK-LM - Informatik License Manager
NMS - Hypercom NMS
TPDU - Hypercom TPDU
RGTP - Reverse Gossip Transport
BLUEBERRY-LM - Blueberry Software License Manager
MS-SQL-S - Microsoft-SQL-Server
MS-SQL-M - Microsoft-SQL-Monitor
IBM-CICS - IBM CICS
SAISM - Satellite-data Acquisition System 2
TABULA - Tabula
EICON-SERVER - Eicon Security Agent/Server
EICON-X25 - Eicon X25/SNA Gateway
EICON-SLP - Eicon Service Location Protocol
CADIS-1 - Cadis License Management
CADIS-2 - Cadis License Management
IES-LM - Integrated Engineering Software
MARCAM-LM - Marcam License Management
PROXIMA-LM - Proxima License Manager
ORA-LM - Optical Research Associates License Manager
APRI-LM - Applied Parallel Research LM
OC-LM - OpenConnect License Manager
PEPORT - PEport
DWF - Tandem Distributed Workbench Facility
INFOMAN - IBM Information Management
GTEGSC-LM - GTE Government Systems License Man
GENIE-LM - Genie License Manager
INTERHDL_ELMD - interHDL License Manager
ESL-LM - ESL License Manager
DCA - DCA
VALISYS-LM - Valisys License Manager
NRCABQ-LM - Nichols Research Corp.
PROSHARE1 - Proshare Notebook Application
PROSHARE2 - Proshare Notebook Application
IBM_WRLESS_LAN - IBM Wireless LAN
WORLD-LM - World License Manager
NUCLEUS - Nucleus
MSL_LMD - MSL License Manager
PIPES - Pipes Platform
OCEANSOFT-LM - Ocean Software License Manager
CSDMBASE - CSDMBASE
CSDM - CSDM
AAL-LM - Active Analysis Limited License Manager
UAIACT - Universal Analytics
CSDMBASE - csdmbase
CSDM - csdm
OPENMATH - OpenMath
TELEFINDER - Telefinder
TALIGENT-LM - Taligent License Manager
CLVM-CFG - clvm-cfg
MS-SNA-SERVER - ms-sna-server
MS-SNA-BASE - ms-sna-base

1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538

DBEREGISTER - dberegister
PACERFORUM - PacerForum
AIRS - AIRS
MITEKSYS-LM - Miteksys License Manager
AFS - AFS License Manager
CONFLUENT - Confluent License Manager
LANSOURCE - LANSource
NMS_TOPO_SERV - nms_topo_serv
LOCALINFOSRVR - LocalInfoSrvr
DOCSTOR - DocStor
DMDOCBROKER - dmdocbroker
INSITU-CONF - insitu-conf
ANYNETGATEWAY - anynetgateway
STONE-DESIGN-1 - stone-design-1
NETMAP_LM - netmap_lm
ICA - ica
CVC - cvc
LIBERTY-LM - liberty-lm
RFX-LM - rfx-lm
WATCOM-SQL - Watcom-SQL
FHC - Federico Heinz Consultora
VLSI-LM - VLSI License Manager
SAISCM - Satellite-data Acquisition System 3
SHIVADISCOVERY - Shiva
IMTC-MCS - Databeam
EVB-ELM - EVB Software Engineering License Manager
FUNKPROXY - Funk Software Inc.
UTCD - Universal Time daemon (utcd)
SYMPLEX - symplex
DIAGMOND - diagmond
ROBCAD-LM - Robcad Ltd. License Manager
MVX-LM - Midland Valley Exploration Ltd. Lic. Man.
3L-L1 - 3l-l1
WINS - Microsoft's Windows Internet Name Service
FUJITSU-DTC - Fujitsu Systems Business of America Inc
FUJITSU-DTCNS - Fujitsu Systems Business of America Inc
IFOR-PROTOCOL - ifor-protocol
VPAD - Virtual Places Audio data
VPAC - Virtual Places Audio control
VPVD - Virtual Places Video data
VPVC - Virtual Places Video control
ATM-ZIP-OFFICE - atm zip office
NCUBE-LM - nCube License Manager
RNA-LM - Ricardo North America License Manager
CICHILD-LM - cichild
INGRESLOCK - ingres
PROSPERO-NP - Prospero Directory Service non-priv
PDAP-NP - Prospero Data Access Prot non-priv
TLISRV - oracle
MCIAUTOREG - micautoreg
COAUTHOR - oracle
RAP-SERVICE - rap-service
RAP-LISTEN - rap-listen
MIROCONNECT - miroconnect
VIRTUAL-PLACES - Virtual Places Software
MICROMUSE-LM - micromuse-lm
AMPR-INFO - ampr-info
AMPR-INTER - ampr-inter
SDSC-LM - isi-lm
3DS-LM - 3ds-lm

1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598

INTELLISTOR-LM - Intellistor License Manager


RDS - rds
RDS2 - rds2
GRIDGEN-ELMD - gridgen-elmd
SIMBA-CS - simba-cs
ASPECLMD - aspeclmd
VISTIUM-SHARE - vistium-share
ABBACCURAY - abbaccuray
LAPLINK - laplink
AXON-LM - Axon License Manager
SHIVAHOSE - Shiva Hose
3M-IMAGE-LM - Image Storage license manager 3M Company
HECMTL-DB - HECMTL-DB
PCIARRAY - pciarray
SNA-CS - sna-cs
CACI-LM - CACI Products Company License Manager
LIVELAN - livelan
ASHWIN - AshWin CI Tecnologies
ARBORTEXT-LM - ArborText License Manager
XINGMPEG - xingmpeg
WEB2HOST - web2host
ASCI-VAL - asci-val
FACILITYVIEW - facilityview
PCONNECTMGR - pconnectmgr
CADABRA-LM - Cadabra License Manager
PAY-PER-VIEW - Pay-Per-View
WINDDLB - WinDD
CORELVIDEO - CORELVIDEO
JLICELMD - jlicelmd
TSSPMAP - tsspmap
ETS - ets
ORBIXD - orbixd
RDB-DBS-DISP - Oracle Remote Data Base
CHIP-LM - Chipcom License Manager
ITSCOMM-NS - itscomm-ns
MVEL-LM - mvel-lm
ORACLENAMES - oraclenames
MOLDFLOW-LM - moldflow-lm
HYPERCUBE-LM - hypercube-lm
JACOBUS-LM - Jacobus License Manager
IOC-SEA-LM - ioc-sea-lm
TN-TL-R1 - tn-tl-r1
VMF-MSG-PORT - vmf-msg-port
TAMS-LM - Toshiba America Medical Systems
SIMBAEXPRESS - simbaexpress
TN-TL-FD2 - tn-tl-fd2
INTV - intv
IBM-ABTACT - ibm-abtact
PRA_ELMD - pra_elmd
TRIQUEST-LM - triquest-lm
VQP - VQP
GEMINI-LM - gemini-lm
NCPM-PM - ncpm-pm
COMMONSPACE - commonspace
MAINSOFT-LM - mainsoft-lm
SIXTRAK - sixtrak
RADIO - radio
RADIO-SM - radio-sm
ORBPLUS-IIOP - orbplus-iiop
PICKNFS - picknfs

1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668

SIMBASERVICES - simbaservices
ISSD
AAS - aas
INSPECT - inspect
PICODBC - pickodbc
ICABROWSER - icabrowser
SLP - Salutation Manager (Salutation Protocol)
SLM-API - Salutation Manager (SLM-API)
STT - stt
SMART-LM - Smart Corp. License Manager
ISYSG-LM - isysg-lm
TAURUS-WH - taurus-wh
ILL - Inter Library Loan
NETBILL-TRANS - NetBill Transaction Server
NETBILL-KEYREP - NetBill Key Repository
NETBILL-CRED - NetBill Credential Server
NETBILL-AUTH - NetBill Authorization Server
NETBILL-PROD - NetBill Product Server
NIMROD-AGENT - Nimrod Inter-Agent Communication
SKYTELNET - skytelne
XS-OPENBACKUP - xs-openbackup
FAXPORTWINPORT - faxportwinport
SOFTDATAPHONE - softdataphone
ONTIME - ontime
JALEOSND - jaleosnd
UDP-SR-PORT - udp-sr-port
SVS-OMAGENT - svs-omagent
CNCP - CableNet Control Protocol
CNAP - CableNet Admin Protocol
CNIP - CableNet Info Protocol
CERT-INITIATOR - cert-initiator
CERT-RESPONDER - cert-responder
INVISION - InVision
ISIS-AM - isis-am
ISIS-AMBC - isis-ambc
SAISEH - Satellite-data Acquisition System 4
DATAMETRICS - datametrics
SA-MSG-PORT - sa-msg-port
RSAP - rsap
CONCURRENT-LM - concurrent-lm
INSPECT - inspect
NKD
SHIVA_CONFSRVR - shiva_confsrvr
XNMP - xnmp
ALPHATECH-LM - alphatech-lm
STARGATEALERTS - stargatealerts
DEC-MBADMIN - dec-mbadmin
DEC-MBADMIN-H - dec-mbadmin-h
FUJITSU-MMPDC - fujitsu-mmpdc
SIXNETUDR - sixnetudr
SG-LM - Silicon Grail License Manager
SKIP-MC-GIKREQ - skip-mc-gikreq
NETVIEW-AIX-1 - netview-aix-1
NETVIEW-AIX-2 - netview-aix-2
NETVIEW-AIX-3 - netview-aix-3
NETVIEW-AIX-4 - netview-aix-4
NETVIEW-AIX-5 - netview-aix-5
NETVIEW-AIX-6 - netview-aix-6
NETVIEW-AIX-7 - netview-aix-7
NETVIEW-AIX-8 - netview-aix-8

1669
1670
1671
1672
1673
1674
1675
1676
1677
1723
1807
1812
1813
1827
1981
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2030
2032

NETVIEW-AIX-9 - netview-aix-9
NETVIEW-AIX-10 - netview-aix-10
NETVIEW-AIX-11 - netview-aix-11
NETVIEW-AIX-12 - netview-aix-12
PROSHARE-MC-1 - Intel Proshare Multicast
PROSHARE-MC-2 - Intel Proshare Multicast
PDP - Pacific Data Products
NEFCOMM1 - netcomm1
GROUPWISE - groupwise
PPTP - pptp
SpySender
RADIUS - RADIUS Authentication Protocol
RADACCT - RADIUS Accounting Protocol
PCM - PCM Agent
Shockrave
LICENSEDAEMON - cisco license management
TR-RSRB-P1 - cisco RSRB Priority 1 port
TR-RSRB-P2 - cisco RSRB Priority 2 port
MSHNET - MHSnet system
STUN-P1 - cisco STUN Priority 1 port
STUN-P2 - cisco STUN Priority 2 port
IPSENDMSG - IPsendmsg
SNMP-TCP-PORT - cisco SNMP TCP port
STUN-PORT - cisco serial tunnel port
PERF-PORT - cisco perf port
TR-RSRB-PORT - cisco Remote SRB port
GDP-PORT - cisco Gateway Discovery Protocol
X25-SVC-PORT - cisco X.25 service (XOT)
TCP-ID-PORT - cisco identification port
CALLBOOK
DC
GLOBE
CFINGER - cfinger
MAILBOX
BERKNET
INVOKATOR
DECTALK
CONF
NEWS
SEARCH
RAID-CC - raid
TTYINFO RAID-AM
TROFF
CYPRESS
BOOTSERVER
CYPRESS-STAT
TERMINALDB
WHOSOCKAMI
XINUPAGESERVER
SERVEXEC
DOWN
XINUEXPANSION3
XINUEXPANSION4
ELLPACK
SCRABBLE

SHADOWSERVER
SUBMITSERVER
DEVICE2
BLACKBOARD

2033
2034
2035
2038
2040
2041
2042
2043
2044
2045
2046
2047
2048
2064
2065
2067
2080
2103
2104
2105
2106
2108
2111
2112
2115
2120
2140
2155
2201
2221
2222
2223
2232
2241
2283
2301
2307
2401
2430
2431
2432
2433
2500
2501
2564
2565
2583
2592
2600
2601
2602
2603
2604
2605
2627
2638
2700
2766
2784

GLOGGER
SCOREMGR
IMSLDOC
OBJECTMANAGER
LAM
INTERBASE
ISIS - isis
ISIS-BCAST - isis-bcast
RIMSL
CDFUNC
SDFUNC
DLS
DLS-MONITOR - dls-monitor
DISTRIB-NETASSHOLES - A group of lamers working on a closed-source client for solving the
RSA cryptographic challenge
DLSRPN - Data Link Switch Read Port Number
DLSWPN - Data Link Switch Write Port Number
Wingate Winsock Redirector Service
ZEPHYR-CLT - Zephyr Serv-HM Conncetion
Zephyr Host Manager
EKLOGIN - Kerberos (v4) Encrypted RLogin
EKSHELL - Kerberos (v4) Encrypted RShell
RKINIT - Kerberos (v4) Remote Initialization
KX - X Over Kerberos
KIP - IP Over Kerberos
Bugs
KAUTH - Remote kauth
Deep Throat, The Invasor
Illusion Mailer
ATS - Advanced Training System Program
UNREG-AB1 - Allen-Bradley unregistered port
UNREG-AB2 - Allen-Bradley unregistered port
INREG-AB3 - Allen-Bradley unregistered port
IVS-VIDEO - IVS Video default
IVSD - IVS Daemon
HVL Rat5
CIM - Compaq Insight Manager
PEHELP - pehelp
CVSPSERVER - CVS Network Server
VENUS
VENUS-SE
CODASRV
CODASRV-SE
RTSSERV - Resource Tracking system server
RTSCLIENT - Resource Tracking system client
HP-3000-TELNET - HP 3000 NS/VT block mode telnet
Striker
WinCrash
NETREK[GAME] - netrek[game]
Digital Rootbeer
ZEBRA - Zebra VTY
RIPD - RIPd VTY
RIPNGD - RIPngd VTY
OSPFD - OSPFd VTY
BGPD - BGPd VTY
WEBSTER Sybase Database
TQDATA - tqdata
LISTEN - System V Listener Port
WWW-DEV - world wide web - development

2800
2989
3000
3001
3005
3006
3024
3049
3064
3086
3128
3129
3130
3141
3150
3155
3264
3295
3306
3333
3421
3454
3455
3456
3457
3459
3700
3791
3801
3871
3900
3905
3908
3920
3921
3922
3923
3925
3975
3984
3985
3986
3996
4000
4001
4008
4045
4092
4132
4133
4321
4333
4343
4444
4500
4501
4557
4559
4567
4590

Phineas Phucker
(UDP) - RAT
UNKNOWN - Unknown Service
NESSUSD - Nessus Security Scanner
DESLOGIN - Encrypted Symmetric Telnet
DESLOGIND WinCrash
NSWS DISTRIB-NET-PROXY - Stupid closed source distrib.net proxy
SJ3 - SJ3 (Kanji Input)
RingZero Masters Paradise SQUID-IPC VMODEM - VMODEM
Deep Throat, The Invasor
HTTP Proxy
CCMAIL - cc:mail/lotus
PORT
MYSQL
DEC-NOTES - DEC Notes
BMAP - Bull Apprise portmapper
MIRA - Apple Remote Access Protocol
PRSVP - RSVP Port
VAT - VAT default data
VAT-CONTROL - VAT default control
Eclipse 2000
Portal of Doom
Eclypse
(UDP) - Eclypse
PORT
UDT_OS - Unidata UDT OS
PORT
PORT
PORT
PORT
PORT
PORT
PORT
PORT
MAPPER-NODEMGR - MAPPER network node manager
MAPPER-MAPETHD - MAPPER TCP/IP server
MAPPER-WS_ETHD - MAPPER workstation server
PORT
UNKNOWN - Unknown Service
PORT
NETCHEQUE - NetCheque accounting
LOCKD - NFS Lock Daemon
WinCrash
NUTS_DEM - NUTS Daemon
NUTS_BOOTP - NUTS Bootp Server
RWHOIS - Remote Who Is
MSQL - Mini SQL Server
UNICALL - UNICALL
NV-VIDEO - NV Video default
SAE-URN - sae-urn
URN-X-CDCHOICE - urn-x-cdchoice
FAX - fax
HYLAFAX - HylaFAX cli-svr Protocol
File Nail
ICQTrojan

4672
4899
5000
5001
5002
5003
5004
5005
5010
5011
5031
5050
5075
5145
5190
5191
5192
5193
5232
5236
5300
5301
5302
5303
5304
5305
5308
5321
5376
5400
5401
5402
5432
5500
5510
5512
5520
5530
5540
5550
5555
5556
5557
5569
5631
5632
5650
5680
5713
5714
5715
5716
5717
5742
5800
5801
5858
5900
5901
5902

RFA - remote file access server


RAdmin - Remote Administrator
UNKNOWN - Unknown Service
COMMPLEX-LINK RFE - radio free ethernet
CLARIS-FMPRO - Claris FileMaker Pro
AVT-PROFILE-1 - avt-profile-1
AVT-PROFILE-2 - avt-profile-2
TELELPATHSTART - TelepathStart
TELELPATHATTACK - TelepathAttack
NetMetro
MMCC - multimedia conference control tool
IISADMIN - IIS Administration Web Site
RMONITOR_SECURE
AOL - America-Online
AOL-1 - AmericaOnline1
AOL-2 - AmericaOnline2
AOL-3 - AmericaOnline3
SGI-DGL - SGI Distributed Graphics
PADL2SIM
HACL-HB - HA Cluster Heartbeat
HACL-GS - HA Cluster General Services
HACL-CFG - HA Cluster Configuration
HACL-PROBE - HA Cluster Probing
HACL-LOCAL
HACL-TEST
CFENGINE Firehotcker
MS FTP
Blade Runner, Back Construction
Blade Runner, Back Construction
Blade Runner, Back Construction
POSTGRES - Postgres Database Server
Hotline Server
SECUREIDPROP - ACE/Server Services
Illusion Maker
SDLOG - ACE/Server Services
SDSERV - ACE/Server Services
SDXAUTHD - ACE/Server Services
Xtcp
ServeMe
Bo
Bo
Robo-Hack
PCANYWHEREDATA
PCANYWHERESTAT
MS FTP PORT
CANNA - Canna (Jap Input)
PROSHAREAUDIO - proshare conf audio
PROSHAREVIDEO - proshare conf video
PROSHAREDATA - proshare conf data
PROSHAREREQUEST - proshare conf request
PROSHARENOTIFY - proshare conf notify
WinCrash
VNC - Virtual Network Computing
VNC - Virtual Network Computing
NETREK[GAME] - netrek[game]
VNC - Virtual Network Computing
VNC-1 - Virtual Network Computing Display
VNC-2 - Virtual Network Computing Display

5977
5978
5979
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6110
6111
6112
6141
6142
6143
6144
6145
6146
6147
6148
6149
6400
6455
6456
6558
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6771
6776
6912
6939
6969
6970
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009

NCD-PREF-TCP - NCD Preferences


NCD-DIAG-TCP - NCD Diagnostics
NCD-CONF-TCP - NCD Configuration
NCD-PREF - NCD Preferences Telnet
NCD-DIAG - NCD Diagnostics Telnet
NCD-CONF - NCD Configuration Telnet
X11 - X Window System
X11:1 - X Window Server
X11:2 - X Window Server
X11:3 - X Window Server
X11:4 - X Window Server
X11:5 - X Window Server
X11:6 - X Window Server
X11:7 - X Window Server
X11:8 - X Window Server
X11:9 - X Window Server
SOFTCM - HP SoftBench CM
SPC - HP SoftBench Sub-Process Control
DTSPCD - dtspcd
META-CORP - Meta Corporation License Manager
ASPENTEC-LM - Aspen Technology License Manager
WATERSHED-LM - Watershed License Manager
STATSCI1-LM - StatSci License Manager - 1
STATSCI2-LM - StatSci License Manager - 2
LONEWOLF-LM - Lone Wolf Systems License Manager
MONTAGE-LM - Montage License Manager
RICARDO-LM - Ricardo North America License Manager
TAL-POD - tal-pod
The Thing
SKIP-CERT-RECV - SKIP Certificate Receive
SKIP-CERT-SEND - SKIP Certificate Send
XDSXDM IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC - irc
IRC - irc
Vampyre
DeepThroat
IRC-SERV - irc-serv
DeepThroat
BackDoor-G, SubSeven
Shit Heep
Indoctrination
ACMSODA - acmsoda
GateCrasher, Priority, IRC 3
AFSSERV - file server itself
UNKNOWN - Unknown Service
UNKNOWN - Unknown Service
AFS3-VLSERVER - volume location database
AFS3-KASERVER - AFS/Kerberos authentication service
AFS3-VOLSER - volume managment server
AFS3-ERRORS - error interpretation service
AFS3-BOS - basic overseer process
AFS3-UPDATE - server-to-server updater
AFS3-RMTSYS - remote cache manager service

7010
7100
7120
7121
7200
7201
7300
7301
7306
7307
7308
7309
7326
7648
7649
7650
7651
7770
7777
7789
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8080
8081
8082
8083
8084
8085
8086
8087
8088
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8181
8383
8450
8765
8807
8888
8892
9000
9001

UPS-ONLINET - onlinet uninterruptable power supplies


FONT-SERVICE - X Font Service
IISADMIN - IIS Administration Web Site
VIRPROT-LM - Virtual Prototypes License Manager
FODMS - FODMS FLIP
DLIP - DLIP
NetMonitor
NetMonitor
NetMonitor
NetMonitor
NetMonitor
NetMonitor
ICB - Internet Citizen's Band
CUCME-1 - CucMe live video/Audio Server
CUCME-2 - CucMe live video/Audio Server
CUCME-3 - CucMe live video/Audio Server
CUCME-4 - CucMe live video/Audio Server
IRC
CBT - cbt
Back Door Setup, ICKiller
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
NPMP - npmp
Ultraseek
DEMOS NNTP
SiteScope - SiteScope Remote Server Monitoring
SEOSLOAD - eTrust ACX
UNKNOWN - Unknown Service
UNKNOWN

9010
9090
9095
9100
9200
9201
9202
9203
9400
9535
9872
9873
9874
9875
9876
9989
9998
9999
10005
10067
10080
10082
10083
10101
10167
10520
10607
11000
11223
11371
12067
12223
12345
12346
12361
12362
12631
13000
13326
16660
16969
17007
17300
18000
20000
20001
20005
20034
20203
21544
21845
21846
21847
22222
22273
22289
22305
22321
23456
23476

SERVICE
ZEUS-ADMIN - Zeus Admin Server
SERVICE
JETDIRECT - HP JetDirect Card
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
InCommand
MAN
Portal of Doom
Portal of Doom
Portal of Doom
Portal of Doom
SD - Session Director
iNi-Killer
DEMOS SMTP
DISTINCT - distinct
STEL - Secure Telnet
(UDP) - Portal of Doom
AMANDA - Amanda Backup Util
AMANDA-IDX - Amanda Indexing
AMIDXTAPE - Amanda Tape Indexing
BrainSpy
(UDP) - Portal of Doom
Acid Shivers
Coma
Senna Spy
Progenic trojan
PKSD - PGP Pub. Key Server
Gjamer
Hack99 KeyLogger
NB - NetBus
GabanBus, NetBus, X-bill
Whack-a-mole
Whack-a-mole
Whackjob
Senna Spy
CROSSFIRE[GAME] - crossfire[game]
Stacheldraht Master Serverd
Priority
ISODE-DUA
Kuang2 The Virus
BIIMENU - Beckman Instruments Inc.
Millennium
Millennium backdoor
BTX - Xcept4
Netbus 2 Pro
Logged
Girlfriend
WEBPHONE - webphoned

INFO SERVER - info server


CONNECT SERVER - connect server
Prosiak
WNN6 - Wnn6 (Jap. Input)
WNN6_CN - Wnn6 (Chi. Input)
WNN6_KR - Wnn6 (Kor. Input)
WNN6_TW - Wnn6 (Tai. Input)
Evil FTP, Ugly FTP , Whack Job
Donald Dick

23477
24326
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
26000
26001
26002
26208
26274
27119
27444
27500
27501
27502
27665
27910
27911
27912
27913
27920
27960
29891
29970
30029
30100
30101
30102
30303
30999
31335
31336
31337
31338
31457
31666
31785
31787
31788
31789
31791
31792
32000
33333
33911
34324
40193
40412
40421
40422
40423
40426
43188

Donald Dick
Netscape Server
ICL-TWOBASE1 - icl-twobase1
ICL-TWOBASE2 - icl-twobase2
ICL-TWOBASE3 - icl-twobase3
ICL-TWOBASE4 - icl-twobase4
ICL-TWOBASE5 - icl-twobase5
ICL-TWOBASE6 - icl-twobase6
ICL-TWOBASE7 - icl-twobase7
ICL-TWOBASE8 - icl-twobase8
ICL-TWOBASE9 - icl-twobase9
ICL-TWOBASE10 - icl-twobase10
QUAKEXX
QUAKEXX
QUAKEXX
WNN6_DS - Wnn6 (Dserver)
(UDP) - Delta Source
QUAKEXX
TRINOO_BCAST - Trinoo Attack Tool
QUAKEXX
QUAKEXX
QUAKEXX
TRINOO_MASTER - Trinoo Attack Tool
QUAKEXX
QUAKEXX
QUAKEXX
QUAKEXX
QUAKEXX
QUAKE3SERVER - Quake 3 Arena Server
(UDP) - The Unexplained
PORT
AOL Trojan
NetSphere
Netsphere
NetSphere
Sockets de Troie
Kuang2
TRINOO_REGISTER - Trinoo Attack Tool
Whack
BO - BackOrifice
NetSpy DK
TETRINET (Tetris GAME)
BO Whack
HackrarTack
HackrarTack
HackrarTack
HackrarTack (udp)
HackrarTack (udp)
HackrarTack
Generic - Shared service port
Prosiak
Spirit 2001a
BigGluck, TN
NetWare
The Spy
Agent 40421, Masters Paradise
Masters Paradise
Masters Paradise
Masters Paradise
REACHOUT

44333
WinRoute
47262
(UDP) - Delta Source
47557
DBBROWSE - Databeam Corporation
3.

50505
Sockets de Troie
50766
Fore, Schwindler
53001
Remote Window Shutdown
54320
BO 2K
54321
SchoolBus
60000
Deep Throat
61466
TeleCommando
65000
Devil
65301
PCANYWHERE

() .2,3
Internet.

6
TCP- connect()

#include <stdio.h>

#include <errno.h>

#include <netdb.h>

#include <fcntl.h>

#define port 3490 // server`s port number

#define MAXDATASIZE 100 // buffer size

int main( int argc, char *argv[])

// structures used by select(...)

10

fd_set rfds;

11

struct timeval tv;

12

int sockfd;

13

int numbytes;

14

char buf[MAXDATASIZE];

15

struct hostent *he;

16

struct sockaddr_in their_addr;

17

int flags;

18

// check for command line`s argument

19

if (argc!=2)

20

21

fprintf (stderr, "usage: client hostname\n");

22

exit(1);

23

24

// get IP address by name (for example, localhost -> 127.0.0.1)

25

if ((he=gethostbyname (argv [1]))==NULL)

26

27

herror ("gethostbyname");

28

exit(1);

29

30

// create a socket

31

if ((sockfd=socket (AF_INET, SOCK_STREAM, 0))==-1)

32

33

perror("socket");

34

exit(1);

35

36

// remove blocking from the socket

37

flags = fcntl(sockfd, F_GETFL, 0);

38

fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

39

// fill their_addr structure (destination address)

40

their_addr.sin_family=AF_INET;

41

their_addr.sin_port=htons(port);

42

their_addr.sin_addr= *((struct in_addr *)he->h_addr);

43

bzero(&(their_addr.sin_zero), 8);

44

// prepare structures used by select(...)

45

tv.tv_sec=10;

46

tv.tv_usec=0;

47

FD_ZERO(&rfds);

48

FD_SET(sockfd,&rfds);

49

// try to connect to the server (connect(...) is NON blocking!!!)

50

printf("Connecting...\n");

51

if(connect(sockfd,(struct sockaddr*)&their_addr,sizeof(their_addr))!=0)

52

if(errno!=EINPROGRESS) // check for connection error (EINPROGRESS is NOT an


53 error!)
54

55

perror("connect");

56

exit(1);

57

58

59

else

60

61

printf("connected at once\n");

62

63

// wait for server`s response (block the program)

64

if(select(sockfd+1, &rfds, NULL, NULL, &tv) == -1)

65

66

perror("select");

67

exit(-1);

68

69

// if sockfd descriptor is in rfds set

70

// then server answered for our request

71

// otherwise time out occured

72

if(FD_ISSET(sockfd, &rfds))

73

74

socklen_t err_len;

75

int error;

76

err_len=sizeof(error);

77

// check for the server`s response

78

if(getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&error,&err_len)==-1)

79

80

perror("getsockopt");

81

exit(1);

82

83

if(error != 0)

84

85

printf("SO_ERROR = %d\n", error);

86

printf("Connection failed\n");

87

exit(-1);

88

89

90

else

91

92

printf("Connection timed out\n");

93

exit(-1);

94

95

// return blocking state to the socket

96

fcntl(sockfd, F_SETFL, flags);

97

// wait for incoming message

98

if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0))==-1)

99

100

perror ("recv");

101

exit(1);

102

103

// show incomming message

104

buf [numbytes]='\0'; // zero terminated string

105

printf ("Received: %s \n", buf);

106

// close the socket

107

close (sockfd);

108

return 0;

109 }

:
. connect()
.
select().
fcntl() ( 37-38).
O_NONBLOCK, .
connect() ( 51) EINPROGRESS.
, connect() .
select() ( 64). rfds,
, . select() rfds
, . rfds
72 FD_ISSET.
78 . getsockopt()
. , .
96 , .. .
recv() ( 98) ,
.
:

. select()
timeout.

. TCP
TCP RST. timeout.

. TCP
TCP ACK. timeout.

#ifndef IP_MULTICAST_IF
/* include/netinet/in.h BSD 4.4. */
#define IP_MULTICAST_IF 9
/* / IP multicast */

#define
#define
#define
#define
#define
#define
#define

IP_MULTICAST_TTL 10
IP_MULTICAST_LOOP 11
IP_ADD_MEMBERSHIP 12
IP_DROP_MEMBERSHIP 13
IP_DEFAULT_MULTICAST_TTL 1
IP_DEFAULT_MULTICAST_LOOP 1
IP_MAX_MEMBERSHIPS 20

/*
/*
/*
/*

/ IP multicast TTL */
/ IP multicast */
() IP- */
IP- */

/* / multicast- */
typedef struct ip_mreq {
struct in_addr imr_multiaddr;
/* */
struct in_addr imr_interface;
/* */
}IP_MREQ;
#endif
...
#define DESTINATION_MCAST "234.5.6.7"
#define DESTINATION_PORT 4567
#define BUFSIZE 1024
...
int nRet, nSize, nOptVal;
SOCKET hSock;
char achInBuf[BUFSIZE];
struct sockaddr_in stSourceAddr, stDestAddr;
u_short nSourcePort;
struct ip_mreq stIpMreq;
...
/* (UDP) */
hSock = socket(PF_INET, SOCK_DGRAM, 0);
if (hSock == INVALID_SOCKET)
{ }
...
/* multicast-. */
...
/* */
stSourceAddr.sin_family = AF_INET;
stSourceAddr.sin_port = htons(nSourcePort);
stSourceAddr.sin_addr.s_addr = INADDR_ANY;
/* bind() ,
*/
nRet=bind(hSock,(struct sockaddr FAR *)&stSourceAddr,sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
//
}
...
/* (loopback) multicast-, , . .
(. 2.9.3).*/
nOptVal = FALSE;
nRet=setsockopt(hSock,IPPROTO_IP,IP_MULTICAST_LOOP,(char FAR *)nOptVal, sizeof(int));
if (nRet == SOCKET_ERROR) {
/* , .
WinSock , . ,
loopback-, , .*/
bLoopFailed = TRUE;
}
...
/* IP TTL 1 64, multicast-
*/
nOptVal = 64;
nRet = setsockopt (hSock, IPPROTO_IP, IP_MULTICAST_TTL,(char FAR *)nOptVal, sizeof(int));
if (nRet == SOCKET_ERROR) {

}
...
/* */
stDestAddr.sin_family = AF_INET;
stDestAddr.sin_addr.s_addr = inet_addr (DESTINATION_MCAST);
stDestAddr.sin_port = htons (DESTINATION_PORT);
...
nRet = sendto (hSock, (char FAR *)achOutBuf,lstrlen(achOutBuf), 0,
(struct sockaddr FAR *) &stDestAddr,
sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
//
}
...
/*----------------------- ------------------------ FD_READ ( , ,
) */
nRet = WSAAsyncSelect (hSock, hwnd, WM_READ_DATA, FD_READ);
if (nRet == SOCKET_ERROR)
{
//
}
...
/* , */
stIpMreq.imr_multiaddr.s_addr = DESTINATION_MCAST; /* */
stIpMreq.imr_interface.s_addr = INADDR_ANY; /* default */
nRet = setsockopt (hSock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char FAR *)&stIpMreq, sizeof (struct ip_mreq));
if (nRet == SOCKET_ERROR) {
}
...
/* multicast- */
case WM_READ_DATA:
if (WSAGETSELECTERROR (lParam))
{
//
}
switch (WSAGETSELECTEVENT (lParam)) {
case FD_READ:
/* */
nSize = sizeof(struct sockaddr);
nRet = recvfrom (hSock, (char FAR *)achInBuf, BUFSIZE, 0, (struct sockaddr *) &stSockAddr,
&nSize);
if (nRet == SOCKET_ERROR)
{
//
} break;
}

8
UDP- (raw)

// Compile:
// cl -o Iphdrinc Iphdrinc.c ws2_32.lib
// Command Line Parameters/Arguments:
// iphdrinc [-fp:int] [-fi:str] [-tp:int] [-ti:str] [-n:int] [-m:str]
// -fp:int From -
// -fi:IP From - IP-
// -tp:int To
-
// -ti:IP To
- IP-
// -n:int
// -m:str
#pragma pack(1)
#define WIN32_LEAN_AND_MEAN //
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_MESSAGE 4068
#define MAX_PACKET 4096
//
#define DEFAULT_PORT 5150
#define DEFAULT_IP "10.0.0.1"
#define DEFAULT_COUNT 5
#define DEFAULT_MESSAGE "This is a test"
// IP-. .
typedef struct ip_hdr
{
unsigned char ip_verlen;
// IP
unsigned char ip_tos;
// TOS
unsigned short ip_totallength;
//
unsigned short ip_id;
//
unsigned short ip_offset;
//
unsigned char ip_ttl;
// TTL
unsigned char ip_protocol;
//
unsigned short ip_checksum;
//
unsigned int ip_srcaddr;
//
unsigned int ip_destaddr;
//
} IP_HDR, *PIP_HDR, FAR* LPIP_HDR;
// UDP-
typedef struct udp_hdr
{
unsigned short src_portno;
//
unsigned short dst_portno;
//
unsigned short udp_length;
// UDP-
unsigned short udp_checksum;
// UDP- ( )
} UDP_HDR, *PUDP_HDR;
//
unsigned long dwToIP,
// IP
dwFromIP;
// IP (spoof)
unsigned short iToPort,
//
iFromPort;
// (spoof)
DWORD dwCount;
//
char strMessage[MAX_MESSAGE];
//
//
void usage(char *progname)
{
printf("usage: %s [-fp:int] [-fi:str] [-tp:int] [-ti:str]\
[-n:int] [-m:str]\n", progname);
printf(" -fp:int From (sender) port number\n");
printf(" -fi:IP From (sender) IP address\n");
printf(" -fp:int To (recipient) port number\n");
printf(" -fi:IP To (recipient) IP address\n");
printf(" -n:int Number of times to read message\n");
printf(" -m:str Size of buffer to read\n\n");
ExitProcess(1); // WinAPI, .
}
//
void ValidateArgs(int argc, char **argv)
{
int i;
iToPort = DEFAULT_PORT;
iFromPort = DEFAULT_PORT;

dwToIP = inet_addr(DEFAULT_IP);
dwFromIP = inet_addr(DEFAULT_IP);
dwCount = DEFAULT_COUNT;
strcpy(strMessage, DEFAULT_MESSAGE);
for(i = 1; i < argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 'f': // From address
switch (tolower(argv[i][2]))
{
case 'p':if (strlen(argv[i]) > 4) iFromPort = atoi(&argv[i][4]);
break;
case 'i': if (strlen(argv[i]) > 4) dwFromIP = inet_addr(&argv[i][4]);
break;
default: usage(argv[0]);
break;
}
break;
case 't': //
switch (tolower(argv[i][2]))
{
case 'p': if (strlen(argv[i]) > 4) iToPort = atoi(&argv[i][4]);
break;
case 'i': if (strlen(argv[i]) > 4) dwToIP = inet_addr(&argv[i][4]);
break;
default:
usage(argv[0]);
break;
}
break;
case 'n': //
if (strlen(argv[i]) > 3)dwCount = atol(&argv[i][3]);
break;
case 'm': if (strlen(argv[i]) > 3) strcpy(strMessage, &argv[i][3]);
break;
default:
usage(argv[0]);
break;
}
}
}
return;
}
//
//
USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
// main(). , WinSock 2.0,
// IP_HDRINCL.
// IP UDP .
// .
int main(int argc, char **argv)
{
WSADATA wsd;

SOCKET sd;
BOOL bOpt=TRUE;
// IP_HDRINCL
struct sockaddr_in remote;
//
IP_HDR ipHdr;
// IP-
UDP_HDR udpHdr;
// UDP-
int ret;
DWORD i;
unsigned short iTotalSize,iUdpSize,iUdpChecksumSize, iIPVersion, iIPSize, cksum = 0;
char buf[MAX_PACKET], *ptr = NULL;
IN_ADDR addr;
//
ValidateArgs(argc, argv);
addr.S_un.S_addr = dwFromIP;
printf("From IP: <%s>\n Port: %d\n", inet_ntoa(addr),iFromPort);
addr.S_un.S_addr = dwToIP;
printf("To IP: <%s>\n Port: %d\n", inet_ntoa(addr), iToPort);
printf("Message: [%s]\n", strMessage);
printf("Count: %d\n", dwCount);
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) // WinSock
{
printf("WSAStartup() failed: %d\n", GetLastError());
return -1;
}
//
sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_UDP, NULL, 0,0);
if (sd == INVALID_SOCKET)
{
printf("WSASocket() failed: %d\n", WSAGetLastError());
return -1;
}
// IP_HDRINCL sd
ret = setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&bOpt, sizeof(bOpt));
if (ret == SOCKET_ERROR)
{
printf("setsockopt(IP_HDRINCL) failed: %d\n", WSAGetLastError());
return -1;
}
// IP-
iTotalSize = sizeof(ipHdr) + sizeof(udpHdr) + strlen(strMessage);
iIPVersion = 4;
iIPSize = sizeof(ipHdr) / sizeof(unsigned long);
ipHdr.ip_verlen = (iIPVersion << 4) | iIPSize;
ipHdr.ip_tos = 0;
// TOS=0
ipHdr.ip_totallength = htons(iTotalSize); // IP-
ipHdr.ip_id = 0;
// , 0
ipHdr.ip_offset = 0;
//
ipHdr.ip_ttl = 128;
// TTL
ipHdr.ip_protocol = 0x11; // -(UDP)
ipHdr.ip_checksum = 0 ;
//
ipHdr.ip_srcaddr = dwFromIP;
//
ipHdr.ip_destaddr = dwToIP;
//
// UDP-
iUdpSize = sizeof(udpHdr) + strlen(strMessage);
udpHdr.src_portno = htons(iFromPort) ;
udpHdr.dst_portno = htons(iToPort) ;
udpHdr.udp_length = htons(iUdpSize) ;
udpHdr.udp_checksum = 0 ;
// UDP-
iUdpChecksumSize = 0;
ptr = buf;
ZeroMemory(buf, MAX_PACKET); // WinAPI, .
memcpy(ptr, &ipHdr.ip_srcaddr, sizeof(ipHdr.ip_srcaddr));
ptr += sizeof(ipHdr.ip_srcaddr);
iUdpChecksumSize += sizeof(ipHdr.ip_srcaddr);
memcpy(ptr, &ipHdr.ip_destaddr, sizeof(ipHdr.ip_destaddr));
ptr += sizeof(ipHdr.ip_destaddr);
iUdpChecksumSize += sizeof(ipHdr.ip_destaddr);
ptr++;
iUdpChecksumSize += 1;
memcpy(ptr, &ipHdr.ip_protocol, sizeof(ipHdr.ip_protocol));
ptr += sizeof(ipHdr.ip_protocol);

iUdpChecksumSize += sizeof(ipHdr.ip_protocol);
memcpy(ptr, &udpHdr.udp_length, sizeof(udpHdr.udp_length));
ptr += sizeof(udpHdr.udp_length);
iUdpChecksumSize += sizeof(udpHdr.udp_length);
memcpy(ptr, &udpHdr, sizeof(udpHdr));
ptr += sizeof(udpHdr);
iUdpChecksumSize += sizeof(udpHdr);
for(i = 0; i < strlen(strMessage); i++, ptr++)
*ptr = strMessage[i];
iUdpChecksumSize += strlen(strMessage);
cksum = checksum((USHORT *)buf, iUdpChecksumSize);
udpHdr.udp_checksum = cksum;
// IP UDP
ZeroMemory(buf, MAX_PACKET);
ptr = buf;
memcpy(ptr, &ipHdr, sizeof(ipHdr)); ptr += sizeof(ipHdr);
memcpy(ptr, &udpHdr, sizeof(udpHdr)); ptr += sizeof(udpHdr);
memcpy(ptr, strMessage, strlen(strMessage));
// sendto()
remote.sin_family = AF_INET;
remote.sin_port = htons(iToPort);
remote.sin_addr.s_addr = dwToIP;
for(i = 0; i < dwCount; i++) //
{
ret = sendto(sd, buf, iTotalSize, 0, (SOCKADDR *)&remote, sizeof(remote));
if (ret == SOCKET_ERROR)
{
printf("sendto() failed: %d\n", WSAGetLastError());
break;
}
else
printf("sent %d bytes\n", ret);
}
closesocket(sd) ;
WSACleanup() ;
return 0;
}

TRANSPORTA UN SAKARU INSTITTS


OC UNIX WINDOWS

2006

1. 4 Winsock 2.0
Windows,
Windows Sockets,
WinSock 2.0 2.2 [30][16].
, , ,
, ,
.
(API) WinSock 2.0
WinSock 1.1.
"-",
(TCP) (UDP) .
, .
API WinSock 2.0
TCP/IP IPX/SPX, ,
TCP/IP. WinSock
2.0 , Quality of Service (QoS
), .

, ,
.
WinSock 2.0 API ,
,
, . WinSock 2.0
, ATM, ISDN .
WinSock API WinSock 2.0:

- ,
, DNS, SAP, X.500 . .
/ .
(QoS Quality of Service).
.
-.
,
.
Scatter and Gather ( /).
.
/.
.
(LSP NSP)

API.
- WinSock 2.0 WOSA (Windows Open Service Architecture),
.
.
, WOSA, , -.
.
, "-" Microsoft
, .
,
, .dll, .

WinSock 2.0, WOSA,


, (SPI Service Provider
Interfaces) - (NSP Name Spase Provider). SPI
32- Microsoft Windows, Windows NT Windows 9,
Windows 2k XP.
- WinSock UNICODE.
WinSock ,
ANSI UNICODE.
- . , TCP/IP TCP- UDP-, IPX/SPX IPX, SPX SPX II.
WinSock-DLL, ws2_32.dll,
. - WinSock-DLL,
- .
. ( )
ws2_32.dllWinSock-DLL.
WinSock 2.0
,
" WinSock"
WSAPROTOCOL_INFO (. 4.2.2),
. 32-,
64- .
WSAEnumProtocols():
int WSAEnumProtocols(
LPINT lpiProtocols,
LPWSAPROTOCOL_INFO lpProtocolBuffer,
LPDWORD lpdwBufferLength
);

lpiProtocols [in] iProtocol. .


lpiProtocols=NULL, .
, .
lpProtocolBuffer [out] , WSAPROTOCOL_INFO.
lpdwBufferLength [in, out]
lpProtocolBuffer, WSAEnumProtocols().
,
WSAEnumProtocols(),
.
, SOCKET_ERROR.
TCP
#include <windows.h>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
BOOL isProto(int iProto)
{
WSADATA wsaData;
BOOL bRet = FALSE;
WSAPROTOCOL_INFO protInfo[32];
DWORD dwLen = sizeof(protInfo);
WSAStartup(MAKEWORD(2, 2), &wsaData);
int i = WSAEnumProtocols(NULL, protInfo, &dwLen);
if(SOCKET_ERROR != i)
while(i--)

if(iProto == protInfo[i].iProtocol)
{
bRet = TRUE;
break;
}
WSACleanup();
return bRet;
}
....
if(isProto(IPPROTO_TCP))
{
/* TCPIP installed */
}

WinSock 2.0
ws2tcpip.h.

27. Winsock 2.0 API


Winsock 2.0 API WSA. WSC, WSP, WPU NSP
Winsock 2.0 SPI, 4.2.1.

WSA WinSock 1.1, 16 .

4. Winsock 2.0 API, 6-


WSAAsyncGetXByY(), 3.3,
WSACancelAsyncRequest(), .
4. Winsock 2.0 API
/

WinSock 1.1

WSAAccept()

WSAAsyncSelect()

. 3.6.3.1

WSACleanup()

. 3.5

WSACloseEvent()

. 4.3

WSAConnect()

WSACreateEvent()

. 4.3

WSADuplicateSocket()

WSAPROTOCOL_INFO
.

WSAEnumNetworkEvents()

. 4.3

WSAEnumProtocols()

. 4

10

WSAEventSelect()

. 4.3

11

WSAGetLastError()

12

WSAGetOverlappedResult()

. 4.3

13

WSAGetQOSByName()

QOS

14

WSAHtonl()

u_long
.

15

WSAHtons()

u_short
.

16

WSAIoctl()

17

WSAJoinLeaf()

18

WSANtohl()

u_long
.

. 3.7.3

19

WSANtohs()

u_short
.

20

WSARecv()

21

WSARecvDisconnect()


, .

22

WSARecvFrom()

23

WSAResetEvent()

. 4.3

24

WSASend()

25

WSASendDisconnect()

26

WSASendTo()

27

WSASetEvent()

. 4.3

28

WSASetLastError()

29

WSASocket()

30

WSAStartup()

31

WSAWaitForMultipleEvents()

. 4.3

32

WSAProviderConfigChange()

. 3.7.3
. 4.3

. 3.5

WSACancelBlockingCall(),
WSAIsBlocking(),
WSASetBlockingHook()

WSAUnhookBlockingHook() API
WinSock 1.1, , ""
WSAStartup() 2.0. WSAEINPROGRESS
.
API,
.

winsock2.h.

61.

WSAAccept()


, QOS
. SOCKET , INVALID_SOCKET.
SOCKET
IN
OUT
IN OUT
IN
IN

WSAAPI WSAAccept (
SOCKET
struct sockaddr FAR *
LPINT
LPCONDITIONPROC
DWORD

sd,
addr,
addrlen,
lpfnCondition,
dwCallbackData);

:
addr - (),
; ,
;
addrlen - ,
addr;
lpfnCondition - ,
(, IP-) CF_ACCEPT ,
CF_REJECT CF_DEFER .
WSAAccept() ,
, . ,
. CF_REJECT
WSAAccept() INVALID_SOCKET

WSAECONNREFUSED.

lpfnCondition,
SO_CONDITIONAL_ACCEPT
( - BOOL).
.
DwCallbackData - , .
WinSock.
(condition procedure) :
int CALLBACK ConditionFunc(
IN
LPWSABUF
IN
LPWSABUF
IN OUT
LPQOS
IN OUT
LPQOS
IN
LPWSABUF
OUT
LPWSABUF
OUT
GROUP FAR *
IN
DWORD
);

lpCallerId,
lpCallerData,
lpSQOS,
lpGQOS,
lpCalleeId,
lpCalleeData,
g,
dwCallbackData

.
, DLL
MakeProcInstance().
WinSock 2.0, MSDN - msdn.microsoft.com.
62.

WSAConnect()

connect() .
, (
), .
SOCKET_ERROR .
int WSAAPI WSAConnect (
IN
SOCKET
IN
const struct sockaddr FAR *
IN
int
IN
LPWSABUF
OUT
LPWSABUF
IN
LPQOS
IN
LPQOS
);

sd,
name,
namelen,
lpCallerData,
lpCalleeData,
lpSQOS,
lpGQOS

sd
- .
name - .
namelen .
LpCallerData - ,
( ).
LpCalleeData - ,
( ).

ATM- (RAWWAN)
. TCP/IP Windows .

63.

LpSQOS .
LpGQOS .

WSADuplicateSocket()

lpProtocolInfo WSAPROTOCOL_INFO
.
SOCKET_ERROR .
int WSAAPI WSADuplicateSocket (
IN
SOCKET
IN
DWORD

sd,
dwProcessId,

OUT
);

LPWSAPROTOCOL_INFO

lpProtocolInfo

sd .
dwProcessId ID ,
.
lpProtocolInfo -
WSAPROTOCOL_INFO. -
.

Shared Sockets
WSADuplicateSocket() is introduced to enable socket sharing across processes. A source process calls
WSADuplicateSocket() to obtain a special WSAPROTOCOL_INFO structure for a target process ID. It
uses some interprocess communications (IPC) mechanism to pass the contents of this structure to a target
process. The target process then uses the WSAPROTOCOL_INFO structure in a call to WSPSocket(). The
socket descriptor returned by this function will be an additional socket descriptor to an underlying socket
which thus becomes shared. Note however, that sockets may be shared amongst threads in a given process
without using the WSADuplicateSocket() function, since a socket descriptor is valid in all of a process
threads.
The two (or more) descriptors that reference a shared socket may be used independently as far as I/O is
concerned. However, the WinSock interface does not implement any type of access control, so it is up to the
processes involved to coordinate their operations on a shared socket. A typical use for shared sockets is to
have one process that is responsible for creating sockets and establishing connections, hand off sockets to
other processes which are responsible for information exchange.
Since what is duplicated are the socket descriptors and not the underlying socket, all of the state associated
with a socket is held in common across all the descriptors. For example a setsockopt() operation performed
using one descriptor is subsequently visible using a getsockopt() from any or all descriptors. A process may
call closesocket() on a duplicated socket and the descriptor will become deallocated. The underlying socket,
however, will remain open until closesocket() is called with the last remaining descriptor.
Notification on shared sockets is subject to the usual constraints of WSAAsyncSelect() and
WSAEventSelect(). Issuing either of these calls using any of the shared descriptors cancels any previous
event registration for the socket, regardless of which descriptor was used to make that registration. Thus, for
example, it would not be possible to have process A receive FD_READ events and process B receive
FD_WRITE events. For situations when such tight coordination is required, it is suggested that developers
use threads instead of separate processes.

64.

WSAGetQOSByName()

QOS ,
,
. TRUE FALSE .
BOOL WSAAPI WSAGetQOSByName(
IN
SOCKET
IN OUT
LPWSABUF
OUT
LPQOS
);

sd,
lpQOSName,
lpQOS

sd .
lpQOSName QOS
.
lpQOS - QOS, .

65.

WSAHtonl()
u_long .

int WSAAPI WSAHtonl (


IN
SOCKET
IN
u_long
OUT
u_long FAR
);

sd,
hostlong,
lpnetlong

:
sd - .
hostlong
- 32- .
lpnetlong
- 32- .
WSAHtons(), WSANtohl() WSANtohs() ,
. SOCKET_ERROR .
66.

WSAIoctl()

( ) ,
. SOCKET_ERROR .
int WSAAPI WSAIoctl (
IN
SOCKET
sd,
IN
DWORD
dwIoControlCode,
IN
LPVOID
lpvInBuffer,
IN
DWORD
cbInBuffer,
OUT
LPVOID
lpvOutBuffer,
IN
DWORD
cbOutBuffer,
OUT
LPDWORD
lpcbBytesReturned,
IN
LPWSAOVERLAPPED
lpOverlapped,
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

sd - .
dwIoControlCode - .
lpvInBuffer
- .
cbInBuffer - .
lpvOutBuffer - .
cbOutBuffer - .
lpcbBytesReturned - .
lpOverlapped - WSAOVERLAPPED (NULL
).
lpCompletionRoutine - (NULL ).
ioctlsocket(),

WinSock 1.1 UNIX
dwIoControlCode 32- .
I1

O-1

V-1

T2

/ 11

16

I - 1, .
O - 1, .
V - 1, .
T = 0 UNIX IOCTL.
T = 1 IOCTL Windows Sockets 2.
T = 2 IOCTL .

T = 3 IOCTL .
,
"".
/ - T = 3 - ; T = 2
; T = 1
Windows Sockets 2 IOCTL; T = 0 , UNIX.
- 16- IOCTL .

WSAIoctl() ,
TCP (Pascal):
function GetSocketBufferDataSize(m_hSocket: Integer):Integer;
var
dwSize : dword;
dwBytesReturned : dword;
begin
// -
dwSize:=0;
WSAIoctl(m_hSocket, FIONREAD, nil, 0, @dwSize, SizeOf(DWORD), dwBytesReturned,
nil, nil);
Result:=dwSize;
end;

WSAIoctl() (MSDN):
tcp_keepalive,
mstcpip.h, SIO_KEEPALIVE_VALS.
tcp_keepalive:
struct tcp_keepalive {
u_long onoff;
// / keep-alive
//. onoff>0
u_long keepalivetime;//
//
u_long keepaliveinterval;// ,
// .
};

.
, sd.
struct tcp_keepalive alive;
DWORD dwRet, dwSize;
alive.onoff = 1;
alive.keepalivetime = 10000;
alive.keepaliveinterval = 1000;
dwRet = WSAIoctl(sock, SIO_KEEPALIVE_VALS, &alive, sizeof(alive), NULL, 0,
reinterpret_cast<DWORD*>(&dwSize), NULL, NULL);
if (dwRet == SOCKET_ERROR)
{
std::cout << "WSAIoctl fail with code " << WSAGetLastError() << "\n";
}
67.

WSAJoinLeaf()

,
. SOCKET
INVALID_SOCKET .
SOCKET WSAAPI WSAJoinLeaf (
IN
SOCKET
sd,
IN
const struct sockaddr FAR *
name,
IN
int
namelen,
IN
LPWSABUF
lpCallerData,
OUT
LPWSABUF
lpCalleeData,
IN
LPQOS
lpSQOS,

IN
IN
);

LPQOS
DWORD

lpGQOS,
dwFlags

68.

sd
- .
name - .
namelen - .
lpCallerData, lpCalleeData, lpSQOS, lpGQOS
WSAConnect() .
dwFlags , ,
.

WSARecv()

, .
, , ,
, alertable.
SOCKET_ERROR. WSA_IO_PENDING
.
, .
int WSAAPI WSARecv (
IN
SOCKET
sd,
IN OUT
LPWSABUF
lpBuffers,
IN
DWORD
dwBufferCount,
OUT
LPDWORD
lpNumberOfBytesRecvd,
IN OUT
LPDWORD
lpFlags,
IN
LPWSAOVERLAPPED
lpOverlapped,
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

sd .
lpBuffers WSABUF. WSABUF
.
dwBufferCount WSABUF lpBuffers.
lpNumberOfBytesRecvd ,
.
lpFlags .
lpOverlapped WSAOVERLAPPED (
).
lpCompletionRoutine - (
).
WSABUF :
typedef struct _WSABUF
{
u_long
len;
char FAR * buf;
} WSABUF, FAR * LPWSABUF;

//
//

UNIX- MSG_PEEK MSG_OOB MSG_PARTIAL,


, .
, , -
.
WSARecv() ,
, lpNumberOfBytesRecvd.
69.

WSARecvDisconnect()

,
. , SOCKET_ERROR.

int WSAAPI WSARecvDisconnect (


IN
SOCKET
OUT
LPWSABUF
);

sd,
lpInboundDisconnectData

70.

sd .
lpInboundDisconnectData .

WSARecvFrom()

.
SOCKET_ERROR .
int WSAAPI WSARecvFrom (
IN
SOCKET
sd,
IN OUT
LPWSABUF
lpBuffers,
IN
DWORD
dwBufferCount,
OUT
LPDWORD
lpNumberOfBytesRecvd,
IN OUT
LPDWORD
lpFlags,
OUT
struct sockaddr FAR *
lpFrom,
IN OUT LPINT
lpFromlen,
IN
LPWSAOVERLAPPED
lpOverlapped,
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

71.

sd - .
lpBuffers WSABUF.
dwBufferCount WSABUF lpBuffers.
lpNumberOfBytesRecvd - , ,
.
lpFlags .
lpFrom ,
.
lpFromlen (, lpFrom).
lpOverlapped WSAOVERLAPPED (
).
lpCompletionRoutinelpOverlapped (
).

WSASend()

.
SOCKET_ERROR .
int WSAAPI WSASend (
IN
SOCKET
sd,
IN
LPWSABUF
lpBuffers,
IN
DWORD
dwBufferCount,
OUT
LPDWORD
lpNumberOfBytesSent,
IN
DWORD
dwFlags,
IN
LPWSAOVERLAPPED
lpOverlapped,
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

sd .
lpBuffers WSABUF. WSABUF
.
dwBufferCount WSABUF lpBuffers.
lpNumberOfBytesSent ,
.
lpFlags .

72.

lpOverlapped WSAOVERLAPPED (
).
lpCompletionRoutine - (
).

WSASendDisconnect()

( shutdown() c
how=1) . ,
SOCKET_ERROR.
int WSAAPI WSASendDisconnect (
IN
SOCKET
OUT
LPWSABUF
);

sd,
lpOutboundDisconnectData

73.

sd .
lpOutboundDisconnectData .

WSASendTo()

, I/O c
. SOCKET_ERROR .
int WSAAPI WSASendTo (
IN
SOCKET
sd,
IN OUT
LPWSABUF
lpBuffers,
IN
DWORD
dwBufferCount,
OUT
LPDWORD
lpNumberOfBytesSent,
IN OUT
LPDWORD
lpFlags,
OUT
struct sockaddr FAR *
lpTo,
IN OUT
LPINT
lpTolen,
IN
LPWSAOVERLAPPED
lpOverlapped,
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

74.

sd - .
lpBuffers WSABUF.
dwBufferCount WSABUF lpBuffers.
lpNumberOfBytesSent - , ,
.
lpFlags .
lpTo .
lpToLen lpTo.
lpOverlapped WSAOVERLAPPED (
).
lpCompletionRoutinelpOverlapped (
).

WSAProviderConfigChange()

.
SOCKET_ERROR .
int WSAAPI WSAProviderConfigChange(
IN OUT
LPHANDLE
IN
LPWSAOVERLAPPED
IN
LPWSAOVERLAPPED_COMPLETION_ROUTINE
);

lpNotificationHandle,
lpOverlapped,
lpCompletionRoutine

:
lpNotificationHandle .

lpOverlapped - WSAOVERLAPPED.
lpCompletionRoutine - ,
.
,
, , Win32,
.
lpNotificationHandle NULL
,
lpNotificationHandle,
. ( )
I/O .
Win32 CloseHandle().

28. API Winsock 2.0


75.

WinSock Service Provider

WinSock 2 Service Provider Interface (SPI) WinSock


API .4.1. SPI "" "" .
,
.
SPI : - ()
. , - :
(layered) (base).
WinSock , , , ""
,
WinSock API. ,
Microsoft TCP/IP.
,
, .
NSP
WinSock API gethostbyname() WSALookupServiceBegin().
,
.

. 4.1 SPI

WOSA
,
.
WinSock SPI ws2spi.h SPI-
ws2_32.lib.
SPI 4 , 4.1.
4.1 SPI-
API

WSC

WSP

API

WPU

NSP

API


Win9x SPI-

76.

SPI


- LSP (Layered Service Provider). LSP- WinSock-
, , , .
LSP ,
, , ,
.., , TCP.
LSP WinSock ,
(chain). LSP Microsoft-.
, , LSP, WinSock,
LSP, .
HTTP-. ,
send(), LSP,
. LSP
, "" ,
, TCP. 4.2
LSP .

. 4.2 LSP


LSP ,
LSP, sporder.exe Microsoft LSP Explorer Lavasoft.

LSP WinSock Windows-DLL,


WSPStartup(). ,
WSPStartup() -, 30 SPI, LSP,
, . WSPPROC_TABLE
30 . LSP ,
, ws2spi.h
, LSP
. 4.2 SPI-,
DLL.
4.2 LSP
/ API

SPI-

WSAAccept() (accept() WSPAccept())

WSPAccept()

WSAAddressToString()

WSPAddressToString()

WSAAsyncSelect()

WSPAsyncSelect()

bind()

WSPBind()

WSACancelBlockingCall()

WSPCancelBlockingCall()

WSACleanup()

WSPCleanup()

closesocket()

WSPCloseSocket()

WSAConnect() (connect() WSPConnect())

WSPConnect()

WSADuplicateSocket()

WSPDuplicateSocket()

10

WSAEnumNetworkEvents()

WSPEnumNetworkEvents()

11

WSAEventSelect()

WSPEventSelect()

12

WSAGetOverlappedResult()

WSPGetOverlappedResult()

13

getpeername()

WSPGetPeerName()

14

getsockname()

WSPGetSockName()

15

getsockopt()

WSPGetSockOpt()

16

WSAGetQOSByName()

WSPGetQOSByName()

17

WSAIoctl()

WSPIoctl()

18

WSAJoinLeaf()

WSPJoinLeaf()

19

listen()

WSPListen()

20

WSARecv() (recv() WSPRecv())

WSPRecv()

21

WSARecvDisconnect()

WSPRecvDisconnect()

22

WSARecvFrom()(recvfrom()
WSPRecvFrom())

23

select()

WSPSelect()

24

WSASend() (send() WSPSend())

WSPSend()

25

WSASendDisconnect()

WSPSendDisconnect()

26

WSASendTo() (sendto() WSPSendTo())

WSPSendTo()

27

setsockopt()

WSPSetSockOpt()

WSPRecvFrom()

/ API

SPI-

28

shutdown()

WSPShutdown()

29

WSASocket() (socket() WSPSocket())

WSPSocket()

30

WSAStringToAddress()
WSPStringToAddress()
-
, .wsp .nsp.
, WinSock-, ws2_32.dll
SPI LSP.
WinSock SPI-. :
htonl(), htons(), ntohl(), and ntohs(), WSA-, ws2_32.dll
, inet_addr() inet_ntoa().
WSAGetXbyY(), WSACancelAsyncRequest() gethostname()
ws2_32.dll.
WinSock-, WSAEnumProtocols(),
WSAIsBlocking(),
WSASetBlockingHook()

WSAUnhookBlockingHook() ws2_32.dll. ,
WinSock 2.0
.
WSAGetLastError() WSASetLastError()
ws2_32.dll.

WSACreateEvent(),
WSACloseEvent(),
WSASetEvent(),
WSAResetEvent()

WSAWaitForMultipleEvents() "" Windows.

WSAPROTOCOL_INFOW
SPI,
, .
:
typedef struct _WSAPROTOCOL_INFO
{
DWORD dwServiceFlags1;
DWORD dwServiceFlags2;
DWORD dwServiceFlags3;
DWORD dwServiceFlags4;
DWORD dwProviderFlags;
GUID ProviderId;
DWORD dwCatalogEntryId;
WSAPROTOCOLCHAIN ProtocolChain;
int iVersion;
int iAddressFamily;
int iMaxSockAddr;
int iMinSockAddr;
int iSocketType;
int iProtocol;
int iProtocolMaxOffset;
int iNetworkByteOrder;
int iSecurityScheme;
DWORD dwMessageSize;
DWORD dwProviderReserved;
WCHAR szProtocol[WSAPROTOCOL_LEN+1];
} WSAPROTOCOL_INFOW;

:
dwServiceFlags1
, , .
. :
XP1_CONNECTIONLESS
(connectionless.) ,
.

XP1_GUARANTEED_DELIVERY
.
XP1_GUARANTEED_ORDER
.
XP1_MESSAGE_ORIENTED
.
XP1_PSEUDO_STREAM
, .
XP1_GRACEFUL_CLOSE
"" (graceful close - 1.7.12).
, (abortive) .
XP1_EXPEDITED_DATA
"" .
XP1_CONNECT_DATA
(connect data.)
XP1_DISCONNECT_DATA
(disconnect data.)
XP1_INTERRUPT
.
XP1_SUPPORT_BROADCAST
.
XP1_SUPPORT_MULTIPOINT
.
.
XP1_MULTIPOINT_CONTROL_PLANE
, ( = 1) (
= 0).
XP1_MULTIPOINT_DATA_PLANE
, ( = 1) ( =
0).
XP1_QOS_SUPPORTED
.
XP1_UNI_SEND
.
XP1_UNI_RECV
.
XP1_IFS_HANDLES
, ,
Installable File System (IFS).
XP1_PARTIAL_MESSAGE
MSG_PARTIAL WSASend() and WSASendTo().
dwServiceFlags2
.
dwServiceFlags3
.
dwServiceFlags4
.
dwProviderFlags
, .
:
PFL_MULTIPLE_PROTO_ENTRIES
,
, . - SPX,

(message-oriented) - .
PFL_RECOMMENDED_PROTO_ENTRY

,
.
PFL_HIDDEN
ws2_32.dll,
, WSAEnumProtocols().
WinSock 2 .
PFL_MATCHES_PROTOCOL_ZERO
, "0" socket() WSASocket()
.
ProviderId
GUID, . ,
.
GUID
.
dwCatalogEntryId
, WS2_32.DLL
WSAPROTOCOL_INFO.
ProtocolChain
WSAPROTOCOLCHAIN, .
0, WSAPROTOCOL_INFO LSP,
Windows Sockets 2 SPI. 1,
, dwCatalogEntryId
WSAPROTOCOL_INFO. . 1,
LSP . ID
ProtocolChain.ChainEntries, LSP (
ProtocolChain.ChainEntries) .
iVersion
.
iAddressFamily
, " " socket()
WSASocket().
iMaxSockAddr
.
iMinSockAddr
.
iSocketType
(SOCK_STREAM, SOCK_DGRAM ..).
iProtocol
(IPPROTO_TCP ..).
iProtocolMaxOffset
, iProtocol,
protocol socket() WSASocket().
. , iProtocolMaxOffset 0.
iNetworkByteOrder
(BIGENDIAN LITTLEENDIAN) - 0
1 .
iSecurityScheme
( ).
SECURITY_PROTOCOL_NONE
.
dwMessageSize
, .
:
0 stream-oriented .
0x1 (send) MTU
.

getsockopt() ( 2.9.2)
SO_MAX_MSG_SIZE.
0xFFFFFFFF - message-oriented,
.
dwProviderReserved
-.
szProtocol
"" , "SPX2".
WSAPROTOCOL_LEN 255.

LSP
, LSP.
LSP ,
Windows-DLL. ,
LSP, : WSPStartup(),
/,
4.3. ,
LSP , , , popup' .., , MS Windows.
LSP WSPStartup().
:
int WSPAPI WSPStartup(
WORD wVersionRequested,
// , ,[in]
LPWSPDATA lpWSPData,
// WSADATA,[out]
LPWSAPROTOCOL_INFOW lpProtocolInfo,
//
// WSAPROTOCOL_INFOW,[in]
WSPUPCALLTABLE UpCallTable,
//
// ws2_32.dll,[in]
LPWSPPROC_TABLE lpProcTable
// SPI-,[out]
);

WSAStartup().

[in] [out]

WSAPROTOCOL_INFOW
. LSP
. "-" WSPStartup()
. UpCallTable,
ws2_32.dll, WinSock-,
lpProcTable LSP, ,
.
UpCallTable " - upcall"
WPU.
WSPStartup() :
1. , .
2. lpWSPData lpProcTable.
3. (
).
,
WSPStartup() WSPCleanup().
0,
.
WSPDATA. LSP ,
lpWSPData , WSPStartup().
WSPPROC_TABLE ,
LSP, .
LSP ,
, .

lpProtocolInfo, (
[27]).
LSP WinSock,
4.3:
4.3 WinSock, LSP
ID

1021

LSP2

TCP/IP

1020 1010 1001

1022

LSP2

UDP/IP

1020 1011 1002

1020

LSP2

1010

LSP1

TCP/IP

1009 1001

1011

LSP1

UDP/IP

1009 1002

1009

LSP1

1001

MSAFD TCP/IP TCP/IP

1002

MSAFD UDP/IP UDP/IP


" (dummy)" LSP ,
WSAPROTOCOL_INFOW, LSP, ,
ID.

DLL
WSCGetProviderPath(). :
int WSCGetProviderPath(
LPGUID lpProviderId,
LPWSTR lpszProviderDllPath,
LPINT lpProviderDllPathLen,
LPINT lpErrno
);

, DLL, LoadLibrary() GetProcAddress()


WSPStartup()- ,
. Windows 9x Me UNICODE
ANSI LoadLibraryA().
LSP (handle).
,
, LSP. ( ,
), LSP WSPStartup(),
LSP- WSPSocket() LSP
, . LSP,
(, TCP), LSP
.
WSPSocket() . ,
WSPPROC_TABLE LSP
WSPStartup() LSP.
WSPSocket(), ,
. ,
:
sd = socket(AF_INET, SOCK_STREAM, 0);

0
.
, LSP TCP/IP Windows
msafd.dll , WSPSocket()
LSP . , msafd.dll,
DLL, ( WSPStartup() WsControl()), WSPSocket()-

" ",
.

- , , LSP
WSAPROTOCOL_INFOW .

,
, , WPUCreateSocketHandle()
, ,
.
LSP, LSP
. LSP,
, XP1_IFS_HANDLES
WSAPROTOCOL_INFO-,
ReadFile() and WriteFile() . ,
IFS ( Installable File System ).
:
SOCKET WPUCreateSocketHandle(
DWORD dwCatalogEntryId,
DWORD_PTR dwContext,
LPINT lpErrno
);

// ID WinSock
// ,
//

,
_SOCK_INFO .
WSPSocket() [27].

LSP
LSP,
WinSock. WinSock 2.0.
,
.
,
,
sd=socket(AF_INET, SOCK_STREAM,0);

( )
ws2_32.dll. WinSock 2.0
, . 0
,
IPPROTO_TCP. LSP,
, TCP,
, LSP?
WinSock, LSP
.
LSP
WSAPROTOCOL_INFOW, LSP
( ), .
WSAPROTOCOLCHAIN:
typedef struct _WSAPROTOCOLCHAIN {
int ChainLen;
DWORD ChainEntries[MAX_PROTOCOL_CHAIN];
} WSAPROTOCOLCHAIN, FAR * LPWSAPROTOCOLCHAIN;

ChainLen ( ) :
ChainLen 0 () ()
ChainLen 1 ()
ChainLen 2
0 2 .

, ChainEntries WinSock-
. dwCatalogEntryId
WSAPROTOCOL_INFOW.
, LSP MsTCP-,
ChainLen 2. ChainEntries ,
ID , ID MsTCP-. ,
, , WSAPROTOCOL_INFOW,
LSP, dwCatalogEntryId
. LSP
WSCInstallProvider(). " ",
ChainLen 0. LSP.
WSAPROTOCOL_INFOW "",
DLL. , WSAEnumProtocols()
, " " hainLen=0. WSCEnumProtocols(),
LSP, "".
MAX_PROTOCOL_CHAIN 7.
LSP WSCInstallProvider():
int WSPAPI WSCInstallProvider(
IN LPGUID lpProviderId,
IN const WCHAR FAR *lpszProviderDllPath,
IN const LPWSAPROTOCOL_INFOW lpProtocolInfoList,
IN DWORD dwNumberOfEntries,
OUT LPINT lpErrno
);

, . -,
UNICODE-. LSP GUID (Globally
Unique IDentifier), "" UUIDGEN.EXE
UuidCreate(). lpszProviderDllPath
UNICODE-.
WinSock.
lpProtocolInfoList WSAPROTOCOL_INFOW
. .
dwNumberOfEntries .
WSAPROTOCOL_INFOW ,
"" , 2- :
szProtocol , .
XP1_IFS_HANDLES dwServiceFlags1, -
. ,
ReadFile() WriteFile().
WinSock ,
,
WSCWriteProviderOrder() , .
, .
ws2_32.dll
DLL ,

dwProviderFlags

WSAPROTOCOL_INFOW

PFL_MATCHES_PROTOCOL_ZERO, ,
, .. LSP ( MSAFD TCP - ).
LSP .
LSP , "",
, WSCDeinstallProvider(),
GUID LSP "", ,
.
.

SPI

, WinSock SPI,
.
API.
WinSock DLL ,
.
WinSock WSAIoctl(), - .

. WSAIoctl(),
SIO_GET_EXTENSION_FUNCTION_POINTER.
WSAIoctl() ,
.
.
, , WSPShutdown() ( how
SD_SEND SD_BOTH), WSPSendDisconnect(). WSPCloseSocket()
.
-
FD_CLOSE.
, ,
WSPSendDisconnect() WSPRecvDisconnect().
WSPCloseSocket().
WinSock SPI WSPShutdown(), WSPSendDisconnect()
, WSPCloseSocket()
.
SO_LINGER SO_DONTLINGER
:

,
.

() (graceful shutdown);
.
,
.


. .
, .

WSPCloseSocket()

-
/, (4.2) . ,
, ,
.
NSP,
, , .
[27] MSDN.

29. / Winsock 2.0


Winsock 2.0
/ :
1. /,
2. / select()
,
3. / Windows-
WSAAsyncSelect(),
4. / WSAEventSelect(),
5. / ( / - overlapped I/O),

6. (completion port).
. - /
select() - , ,
, ioctlsocket().
, , UNIX-,
. , , Windows
.
Windows-
, .
-
WSAEVENT WSACreateEvent():
WSAEVENT WSACreateEvent(void);

(Event-handle),
WSAEventSelect():
int WSAEventSelect(
SOCKET
WSAEVENT
long
);

sd,
hEventObject,
lNetworkEvents

hEventObject . ,
.
WSAResetEvent() . WSAEVENT HANDLE
API.
, , lNetworkEvents,
, WSAAsyncSelect()
FD_READ, FD_ACCEPT (3.6.3.1), :
//
NewEvent = WSACreateEvent();
// NewEvent FD_ACCEPT
// FD_CLOSE
WSAEventSelect( ListenSocket, NewEvent, FD_ACCEPT | FD_CLOSE);

WSAEventSelect() 0,
, - SOCKET_ERROR.
-, ,
. "" -",
" " "". ,
Windows, .
WSACreateEvent() - ""
. , ""
. "" , ()
/
WSAResetEvent():
BOOL WSAResetEvent(WSAEVENT hEvent);

-,
WSACloseEvent() , :
BOOL WSACloseEvent(WSAEVENT hEvent);

WSAAsyncSelect(), WSAEventSelect()
.
ioctlsocket()/WSAIoctl().

WSAWaitForMultipleEvents(). WaitForSingleObject() API
.

, ( )

" "
"". WSAWaitForMultipleEvents() :
DWORD WSAWaitForMultipleEvents(
DWORD
cEvents,
const WSAEVENT FAR
* lphEvents,
BOOL
fWaitAll,
DWORD
dwTimeout,
BOOL
fAlertable
);
cEvents
, lphEvents .

( WSAEVENT)

:
, cEvents=0

"" .
,
(thread) WSA_MAXIMUM_WAIT_EVENTS, 64.
64 , .
fWaitAll , , "". "TRUE",
"" . ,
"" , ,
" WSA_WAIT_EVENT_0"
. FALSE
. dwTimeout
. 0,
. ,
WSA_WAIT_TIMEOUT. dwsTimeout
WSA_INFINITE, (
select() 2.5.7). fAlertable ""
WSAEventSelect() ,
/ , FALSE.
4.1 :
4.1
WSAEVENT
EventArray[WSA_MAXIMUM_WAIT_EVENTS];
int
Total=0, res, i;
// EventArray -
...
while (1)
{
res=WSAWaitForMultipleEvents(Total,EventArray,FALSE,WSA_INFINITE,FALSE);
if ((res != WSA_WAIT_FAILED) && (res != WSA_WAIT_TIMEOUT))
{
//
i = res - WSA_WAIT_EVENT_0;
// EventArray[i]
...
// ("")
WSAResetEvent(EventArray[i]);
}
}

. , ( )
, ,
" " ,
WSAWaitForMultipleEvents() ,
dwTimeOut 0.
:
W
S

A
_
W
Af
IW
Ta
_i
Et
VA
El
Nl
T
_
0

t
o

(
W
SAT
_R
WU
AE
I,
T
_
E
V
E
N
T
_
0

c
E
v
e
n
t
s
-
1
)

f
W
a
i
t

A
l
l

F
A
L
S
E
,

W
S
A
_
W
A
I
T
_
E
V
E
N
T

_
0

l
p
h
E
v
e
n
t
s

l
p
h
E
v
e
n
t
s

.
W
S
A
_
W
A
I
T
_
I
O
_
C
O
M
P
L
E
T
I

O
N

W
S
A
W
a
i
t
F
o
r
M
u
l
t
i
p
l
e
E
v
e
n
t
s
(
)

f
A
l
e
r
t
a
b
l
e
T
R
U
E
.
W
S
A
_
W
A
I
T
_
T
I
M

E
O,
U
T

f
W
a
i
t
A
l
l

.
, WSA_WAIT_FAILED.

WSAWaitForMultipleEvents()
, sd
WSAEnumNetworkEvents():
int WSAEnumNetworkEvents(
SOCKET sd,
//[in]
WSAEVENT hEventObject,
//[in]
LPWSANETWORKEVENTS lpNetworkEvents //[out]
);
hEventObject ,

, lpNetworkEvents
:
typedef struct _WSANETWORKEVENTS
{
long lNetworkEvents;
//
int iErrorCode[FD_MAX_EVENTS];
//
} WSANETWORKEVENTS, FAR * LPWSANETWORKEVENTS;

FD_XXX ,
or . lNetworkEvents
, , . ,
(lNetworkEvents and FD_XXX) , , FD_XXX
.
,
:
WSAEnumNetworkEvents(SocketsArray[index1], EventArray[index2], &info)
if (info.lNetworkEvents & FD_READ)
//info
//
{
//
}

_BIT
, FD_READ_BIT:
if (NetworkEvents.iErrorCode[FD_READ_BIT] != 0)
{
printf("FD_READ failed with error %d\n",
NetworkEvents.iErrorCode[FD_READ_BIT]);
break;
}

/ WSAEventSelect()
,
Windows, .
, .
/ (
) Overlapped I/O.
,
c WSASocket():
SOCKET WSASocket(
int af,
int type,

int protocol,
LPWSAPROTOCOL_INFO lpProtocolInfo,
GROUP g,
DWORD dwFlags);

,
.
WSAPROTOCOL_INFO. lpProtocolInfo NULL, , , ws2_32.dll af, type protocol.
, 0, ,
WSAPROTOCOL_INFO.
lpProtocolInfo ,

FROM_PROTOCOL_INFO (" "),


. " ",
WinSock 2.0, Windows .
, .

WSA_FLAG_OVERLAPPED.
I/O
. WinSock 1.1,
Windows NT. overlapped I/O WinSock 1.1
ReadFile WriteFile,
.
, ""
/,
. , , ,
.
Windows, Windows CE.
WinSock 1.1
ReadFile() WriteFile(), read() write() *nix, WinSock 2.0 I/O ,
WSASend() WSARecv(). WinSock 1.1
ReadFile() WriteFile() ,
WSASend() WSARecv().
,
WSA_FLAG_OVERLAPPED.
:
WSASend()
WSASendTo()
3. WSARecv()
4. WSARecvFrom()
5. WSAIoctl()
6. WSARecvMsg()
7. AcceptEx()
8. ConnectEx()
9. TransmitFile()
10. TransmitPackets()
11. DisconnectEx()
12. WSANSPIoctl()
WSAOVERLAPPED .
,
, , ,
!
1.
2.

, SOCKET_ERROR,
WSAGetLastError() - WSA_IO_PENDING.
WSASend():
int WSASend(
SOCKET
sd,
LPWSABUF
lpBuffers,
DWORD
dwBufferCount,
LPDWORD
lpNumberOfBytesSent,
DWORD
dwFlags,
LPWSAOVERLAPPED
lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

WSABUF,
dwBufferCount. (scatter/gather)
2.5.5. lpNumberOfBytesSent - DWORD,
.
dwFlags send().

,
lpOverlapped
(

WSAOVERLAPPED)

lpCompletionRoutine ( )
.
12
"" WSAOVERLAPPED,
/.
, WSAOVERLAPPED,

.

WSAOVERLAPPED OVERLAPPED Win32 API.
typedef struct WSAOVERLAPPED
{
DWORD
Internal;
DWORD
InternalHigh;
DWORD
Offset;
DWORD
OffsetHigh;
WSAEVENT hEvent;
} WSAOVERLAPPED, FAR * LPWSAOVERLAPPED;
Internal, InternalHigh, Offset OffsetHigh


. hEvent
WSAEVENT
- lpCompletionRoutine NULL. lpCompletionRoutine
NULL, .
/
event-,
" ",
WSAOVERLAPPED_COMPLETION_ROUTINE
6- .
,
.
,
, -
WSAGetOverlappedResult().
c - WinSock
, WSAOVERLAPPED "",
/ .
WSAWaitForMultipleEvents(). ,
,
WSAGetOverlappedResult():

BOOL WSAGetOverlappedResult(
SOCKET
sd,
LPWSAOVERLAPPED
lpOverlapped,
LPDWORD
lpcbTransfer,
BOOL
fWait,
LPDWORD
lpdwFlags
);
lpOverlapped WSAOVERLAPPED,
. lpcbTransfer ,
. fWait

, , .
fWait=TRUE . fWait=FALSE
FALSE
WSA_IO_INCOMPLETE. ""
, . lpdwFlags
, ,
WSARecv() WSARecvFrom().
WSAGetOverlappedResult() TRUE.
FALSE, :
I/O- .
I/O- , .
I/O- -
WSAGetOverlappedResult().
/ -
, WSPSocket() WSA_FLAG_OVERLAPPED.
/
- " - ompletion routines". callback-,
. ,
, ,
.
, ,
WSAOVERLAPPED ,
, WSASend() .
:
void CALLBACK CompletionRoutine(
DWORD dwError,
DWORD cbTransferred,
LPWSAOVERLAPPED lpOverlapped,
DWORD dwFlags
);

dwError - lpOverlapped.
cbTransferred .
lpOverlapped WSAOVERLAPPED,
I/O-.
dwFlags , .
,
, hEvent.
, ,
alertable state.
WSAWaitForMultipleEvents() "" , ,
Windows SleepEx() ,
WSAWaitForMultipleEvents(), . SleepEx() :
DWORD SleepEx(
DWORD dwMilliseconds,
BOOL bAlertable
);

SleepEx() . bAlertable=FALSE
callback-, dwMilliseconds.
TRUE, , SleepEx()
I/O - WAIT_IO_COMPLETION.
dwMilliseconds=INFINITE,


Win9x, ,
WinNT, Win2K WinXP. -

. 0,
, (
setsockopt() SO_SNDBUF/SO_RCVBUF) -
-

/
9.

/, , " "
completion port. ,
() ,
/ .
, (
,
www.microsoft.com),
I/O- ,
. Windows NT, Windows 2000,
Windows XP Windows Server 2003 . ,
, MSDN, 16-
.

, " ".
CreateIoCompletionPort(),
() (. 4.5.1.1)
I/O ,
.
- I/O,
, I/O-
. CreateIoCompletionPort(),
:
HANDLE CreateIoCompletionPort(
HANDLE FileHandle,
HANDLE ExistingCompletionPort,
DWORD CompletionKey,
DWORD NumberOfConcurrentThreads
);

, ,
:
1.
2.
,
- NumberOfConcurrentThreads; .
NumberOfConcurrentThreads , ,
. ,
,
. 0
, . I/O:
CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL, 0, 0);

, ,
, .


, ,
. -
, ,
. ,
, ?
, ,
, .
CreateIoCompletionPort()
; .
, CreateIoCompletionPort()
.
NumberOfConcurrentThreads CreateIoCompletionPort()
n .
n , n
. (,
, ,
CreateIoCompletionPort().)
, ,
CreateIoCompletionPort()?
, .
( proxy- -
WaitForSingleObject()) "" Sleep() -
. ..
-
NumberOfConcurrentThreads, - -
.
NumberOfConcurrentThread .
, /
, .
CreateIoCompletionPort()
FileHandle, ExistingCompletionPort CompletionKey
.
FileHandle , .
ExistingCompletionPort ,
. CompletionKey "per-handle data",
.
, , .
"per-handle data" " ". ,
, "" . , ,
, .
,
, /.
, , LIFO. ,
, ,
, .
-, /
. ECHO-,
. :
1. . 0 -
.
2. , .
3. I/O- ,
2. ,

, , -
, ,
. CreateThread(),
, .
4. , 5150.
5. accept().
6. , " per-handle data"
.
7. , accept(), ,
CreateIoCompletionPort().
"per-handle data"
CreateIoCompletionPort() .
8. I/O . ,
WSARecv() WSASend() ,
/ .
(.. ). ( ),
.
5-8, .
., :
4.2 IOCompletionPort

DWORD WINAPI ServerThread (LPVOID CompletionPortID);//


HANDLE CompletionPort;
//
WSADATA wsd;
// WSADATA
SYSTEM_INFO SystemInfo;
//
SOCKADDR_IN InternetAddr;
//
SOCKET Listen_socket;
int i;
typedef struct _PER_HANDLE_DATA
{
SOCKET
Accept_socket;
//
SOCKADDR_STORAGE ClientAddr; //
// ,
} PER_HANDLE_DATA, * LPPER_HANDLE_DATA;
// WinSock
StartWinsock(MAKEWORD(2,2), &wsd);
// 1:
// -
CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0);
// 2:
// ,
GetSystemInfo(&SystemInfo);
// 3:
// , ,
// .
// .
for(i = 0; i < SystemInfo.dwNumberOfProcessors; i++)
{
HANDLE ThreadHandle;
// , .
// : ServerWorkerThread() .
ThreadHandle = CreateThread(NULL, 0,ServerWorkerThread, CompletionPort,0,
&ThreadId);
//
CloseHandle(ThreadHandle);
}
// 4:
// ( WSA_FLAG_OVERLAPPED)
Listen_socket = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,
WSA_FLAG_OVERLAPPED);
InternetAddr.sin_family = AF_INET;
InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);

InternetAddr.sin_port = htons(5150);
bind(Listen, (PSOCKADDR) &InternetAddr,sizeof(InternetAddr));
//
listen(Listen_socket, 5);
while(TRUE)
{
PER_HANDLE_DATA *PerHandleData=NULL;
SOCKADDR_IN saRemote;
SOCKET Accept_socket;
int RemoteLen;
// 5:
//
RemoteLen = sizeof(saRemote);
Accept_socket = WSAAccept(Listen_socket, (SOCKADDR *)&saRemote,&RemoteLen);
// 6:
// " per-handle data",
PerHandleData = (LPPER_HANDLE_DATA) GlobalAlloc(GPTR,
sizeof(PER_HANDLE_DATA));
printf("Socket number %d connected\n", Accept_socket);
PerHandleData->Socket = Accept_socket;
memcpy(&PerHandleData->ClientAddr, &saRemote, RemoteLen);
// 7:
//
CreateIoCompletionPort((HANDLE)Accept_socket,CompletionPort,(DWORD)
PerHandleData,0);
// 8:
// / .
// WSASend() WSARecv()
// I/O.
// WSARecv() / WSASend()
// , SOCKET_ERROR
// WSA_IO_PENDING, (

// ).
}
DWORD WINAPI ServerWorkerThread(LPVOID lpParam)
{
.....
return 0;
}

/,
, ,
.
. GetQueuedCompletionStatus(),
.
, I/O.
BOOL GetQueuedCompletionStatus(
HANDLE CompletionPort,
// the I/O completion port of interest
LPDWORD lpNumberOfBytesTransferred,// to receive number of bytes
// transferred during I/O
LPDWORD lpCompletionKey,
// to receive file's completion key
LPOVERLAPPED *lpOverlapped, // to receive pointer to OVERLAPPED structure
DWORD dwMilliseconds
// optional timeout value
);

:
CompletionPort
lpNumberOfBytesTransferred - -
WSASend/WSARecv
lpCompletionKey - ,

lpOverlapped OVERLAPPED-

dwMilliseconds - (INFINITE - )
,
FALSE *lpOverlapped NULL. dwMilliseconds =0
, .
. *lpOverlapped
NULL , 0.
, GetLastError() WAIT_TIMEOUT.
, , , GetQueuedCompletionStatus()
ERROR_SUCCESS, *lpOverlapped -NULL lpNumberOfBytes 0.
lpOverlapped OVERLAPPED, ,
Per-I/O,
( ECHO-, , ,
- / ). Per-I/O ,
, OVERLAPPED,
, OVERLAPPED.
- OVERLAPPED
. , ,
Per-I/O:
typedef struct {
OVERLAPPED Overlapped;
// :
WSABUF DataBuf;
CHAR Buffer[DATA_BUFSIZE];
DWORD BytesSend;
DWORD BytesRecv;
DWORD OperationType;
DWORD TotalBytes;
.....
} PER_IO_OPERATION_DATA;

OVERLAPPED
, / , - /,
- , ,
.
, WinSock- OVERLAPPED . :
PER_IO_OPERATION_DATA PerIoData;
...
WSARecv(socket, &wbuf, 1, &Bytes, &Flags, &(PerIoData.Overlapped),NULL);

GetQueuedCompletionStatus()
. per-I/O ,

CONTAINING_RECORD. :
PER_IO_DATA *PerIoData=NULL;
OVERLAPPED
*lpOverlapped=NULL;
ret = GetQueuedCompletionStatus(CompPortHandle,&Transferred,
(PULONG_PTR)&CompletionKey,&lpOverlapped,INFINITE);
PerIoData = CONTAINING_RECORD(lpOverlapped, PER_IO_DATA, Overlapped);

OVERLAPPED-
PER_IO_DATA , ,
.
, ,
PerIoData - , ..
- I/O
. , ,
,
.
ECHO
ServerWorkerThread():
4.3 ServerWorkerThread():

DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)


{
HANDLE CompletionPort = (HANDLE) CompletionPortID;
DWORD BytesTransferred;
LPOVERLAPPED Overlapped;
LPPER_HANDLE_DATA PerHandleData;
LPPER_IO_DATA PerIoData;
DWORD SendBytes, RecvBytes;
DWORD Flags;
while(TRUE)
{
// / ,
//
if (GetQueuedCompletionStatus (CompletionPort, &BytesTransferred,
(LPDWORD)&PerHandleData, (LPOVERLAPPED *) &PerIoData, INFINITE) == 0)
{
// .
printf ("GetQueuedCompletionStatus failed with error %d\n", GetLastError ());
return 0;
}
// BytesTransferred=0,
// , ,
//
if (BytesTransferred == 0 &&(PerIoData->OperationType == RECV_POSTED
PerIoData->OperationType == SEND_POSTED))
{
closesocket(PerHandleData->Socket);
GlobalFree(PerHandleData);
GlobalFree(PerIoData);
continue;//
}
// . ,
// OperationTypefield PerIoData
if (PerIoData->OperationType == RECV_POSTED)
{
// WSARecv(),
// , PerIoData->Buffer
}
//
WSASend()
// WSARecv(). WSARecv()
//
Flags = 0;
//
ZeroMemory(&(PerIoData->Overlapped),sizeof(OVERLAPPED));
PerIoData->DataBuf.len = DATA_BUFSIZE;
PerIoData->DataBuf.buf = PerIoData->Buffer;
PerIoData->OperationType = RECV_POSTED;
// WSARecv()
WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
&(PerIoData->Overlapped), NULL);
}//End While
}//End ServerWorkerThread()

.
, GetQueuedCompletionStatus() FALSE.
Windows, GetLastError().
WinSock- , WSAGetOverlappedResult()
WSAOVERLAPPED,
WSAGetLastError() WinSock-.
- ..
. ""
OperationType PER_IO_OPERATION_DATA
, :

switch (PerIoData->OperationType)
{
case SRV_NEW_CONNECTION:
// :
...
case SRV_DATA_SEND:
//
...
case SRV_DATA_RECV:
//
...
case SRV_DISCONNECT:
//
.......
}

-
OVERLAPPED, - . ,
closesocket()
. ,
. PostQueuedCompletionStatus(),
, :
BOOL PostQueuedCompletionStatus(
HANDLE CompletionPort,
DWORD dwNumberOfBytesTransferred,
DWORD dwCompletionKey,
LPOVERLAPPED lpOverlapped
);

//
//
//
//


GetQueuedCompletionStatus()
GetQueuedCompletionStatus()
GetQueuedCompletionStatus()

CompletionPort - , ,
GetQueuedCompletionStatus() -
-
- , , Etc...
GetQueuedCompletionStatus()
, ,
. , 0
dwCompletionKey-,
.
CloseHandle()
.

30. I/O
/ WinSock
, () ,
,
,
. ,
:
1. "" "" ,
, .
2. ""
, .
,
select().
3. select(). select()
, .
select() .
4. (WSAAsyncSelect()),
,

,
.
5. - WSAEventSelect(),
select(), . ,
, select() -, WSAEventSelect()
WinSock.
6. I/O WinSock 2,
I/O- Win32
API
.
7. I/O ompletion Port
.
,
I/O,
.
, ,
,
.
, Windows 9x I/O ,
, API, ReadFile()
Windows 9x . UNIX , I/O ,
. , UNIX-like
"" aio_*(), WinSock-
.
, UNIX-like
" Posix Posix threads", API
UNIX Windows .
select()
- ,
.
, .
WSAAsyncSelect()
, ,
.
WSAEventSelect()
WSAAsyncSelect(), ""
. , 100
. , " " 64 (
) , 1024 , 16 !
1-100 -
.

I/O
.
( ),
.
. ,

(GUI), .
"" ,
.
FTP-, -,
, email-
.
.

31. WinSock 2.0


WinSock 2
.
- API ,
,
.
77.

API

WinSock 2
Extension API, ,
. AcceptEx(), ConnectEx(),
DisconnectEx(), TransmitFile(), TransmitPackets() WSARecvMsg().
GetAcceptExSockaddrs() AcceptEx().
MSWSOCK.H, - mswsock.dll. 3
mswsock.dll AcceptEx(),
GetAcceptExSockaddrs() TransmitFile(),
, mswsock.lib.
DLL WSAIoctl()
SIO_GET_EXTENSION_ FUNCTION_POINTER,
GUID[27]. WSAStringToAddress()
IPv4 Inet_Addr(), WSAAddressToString(), .
WSADuplicateSocket():
int WSADuplicateSocket(
SOCKET sd,
DWORD dwProcessId,
LPWSAPROTOCOL_INFO lpProtocolInfo);

sd , , dwProcessID , .
ProtocolInfo , .
- ,
WSASocket() .
WSADuplicateSocket() SOCKET_ERROR
.

77.1.1.1.

AcceptEx()

AcceptEx() ,
- - Web
. ,
.

. TRUE FALSE .
Windows Me/98/95.
BOOL PASCAL FAR AcceptEx (
IN SOCKET sListenSd,
IN SOCKET sAcceptSd,

//
// ,
//
IN PVOID lpOutputBuffer,
//
//
//
IN DWORD dwReceiveDataLen, // , 0,
//
//
IN DWORD dwLocalAddrLen,
// +16
IN DWORD dwRemoteAddrLen, // +16 .
// 0.
OUT LPDWORD lpdwBytesRecevd,//
IN LPOVERLAPPED lpOverlapped// WSAOVERLAPPED,
);

sAcceptSd ,
,
.
AcceptEx() .
. accept() ,
"" ,
, AcceptEx() sAcceptSd
, sListenSd ,
setsockopt() SO_UPDATE_ACCEPT_CONTEXT, :
err = setsockopt( sAcceptSocket,SOL_SOCKET,SO_UPDATE_ACCEPT_CONTEXT,
(char *)&sListenSocket,sizeof(sListenSocket) );

4.4 AcceptEx()
( MSDN):
4.4 AcceptEx()
include <stdio.h>
#include "winsock2.h"
#include "mswsock.h"
void main() {
//
WSADATA wsaData;
HANDLE hCompPort;
//
LPFN_ACCEPTEX lpfnAcceptEx = NULL;
// AcceptEx()
GUID GuidAcceptEx = WSAID_ACCEPTEX;
// GUID AcceptEx()
WSAOVERLAPPED olOverlap;
//
SOCKET ListenSd,AcceptSd;
sockaddr_in server;
char lpOutputBuf[1024];
int outBufLen = 1024;
DWORD dwBytes;
// WinSock
int iResult = WSAStartup( MAKEWORD(2,2), &wsaData );
if( iResult != NO_ERROR )
printf("Error at WSAStartup\n");
//
hCompPort = CreateIoCompletionPort( INVALID_HANDLE_VALUE, NULL, (u_long)0, 0 );
//
SListensd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
if (SListensd == INVALID_SOCKET) {
printf("Error at socket(): SListensd\n");
WSACleanup();
return;
}
//
CreateIoCompletionPort((HANDLE)SListensd, hCompPort, (u_long)0, 0);
// IPv4 20000
hostent* OurHost;
char* ip;
u_short port = 20000;
OurHost = gethostbyname("");
ip = inet_ntoa (*(struct in_addr *)*OurHost->h_addr_list);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr(ip); server.sin_port = htons(port);
if ( bind( SListensd,(SOCKADDR*) &server, sizeof(server) ) == SOCKET_ERROR )
{
printf("bind failed\n");
closesocket(SListensd);
return;

}
//
if (listen( SListensd, 150 ) == SOCKET_ERROR)
{
printf("error listening\n");
}
printf("Listening on address: %s:%d\n", ip, port);
// AcceptEx() , WSAIoctl(), .
// I/O .
WSAIoctl(SListensd,SIO_GET_EXTENSION_FUNCTION_POINTER,&GuidAcceptEx, sizeof(GuidAcceptEx),
&lpfnAcceptEx,sizeof(lpfnAcceptEx),&dwBytes,NULL,NULL);
//
AcceptSd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (AcceptSd == INVALID_SOCKET)
{
printf("Error creating accept socket.\n");
WSACleanup();
return;
}
// .
memset(&olOverlap, 0, sizeof(olOverlap));
// AcceptEx()
lpfnAcceptEx(SListensd,AcceptSd,lpOutputBuf,outBufLen-((sizeof(sockaddr_in)+ 16)*2),
sizeof(sockaddr_in)+16,sizeof(sockaddr_in)+16,&dwBytes,&olOverlap);
// AcceptSd
CreateIoCompletionPort((HANDLE)AcceptSd, hCompPort, (u_long)0, 0);
// - send(),
recv(),
// TransmitFile() ..
...
}


16
sockaddr , ,
TDI (Transport Driver Interface). TCP/IP ..
32 .

AcceptEx(),
,
MSDN. , GetAcceptExSockaddrs(),
,
AcceptEx() lpOutputBuffer.
, TDI. , SOCKADDR.
:
VOID PASCAL FAR GetAcceptExSockaddrs (
IN PVOID
lpOutputBuffer,
IN DWORD
dwReceiveDataLength,
IN DWORD
dwLocalAddressLength,
IN DWORD
dwRemoteAddressLength,
OUT struct sockaddr **LocalSockaddr,
OUT LPINT
LocalSockaddrLength,
OUT struct sockaddr **RemoteSockaddr,
OUT LPINT
RemoteSockaddrLength
);

AcceptEx()
. . , AcceptEx()
:
SOCKADDR *lpLocalSockaddr=NULL, *lpRemoteSockaddr=NULL;
int LocalSockaddrLen=0, RemoteSockaddrLen=0;
// GetAcceptExSockaddrs()
LPFN_GETACCEPTEXSOCKADDRS lpfnGetAcceptExSockaddrs=NULL;

//
lpfnGetAcceptExSockaddrs(buf,buflen - ((sizeof(SOCKADDR_IN) + 16) * 2),
sizeof(SOCKADDR_IN) + 16,sizeof(SOCKADDR_IN) + 16,&lpLocalSockaddr,
&LocalSockaddrLen,&lpRemoteSockaddr,&RemoteSockaddrLen);

WSAIoctl()
lpfnGetAcceptExSockaddrs, 4.2.
GetAcceptExSockaddrs() .

77.1.1.2.

ConnectEx(), DisconnectEx()

ConnectEx()
(connect data).
TRUE, FALSE .
(
- )
connect' . lpOverlapped
NULL. , ,
: ReadFile(), WriteFile(), send()
WSASend(), recv() WSARecv(), TransmitFile() closesocket().
BOOL (PASCAL FAR *LPFN_CONNECTEX) (
IN SOCKET sd,
IN const struct sockaddr FAR
IN int
IN PVOID
IN DWORD
OUT LPDWORD
IN LPOVERLAPPED
);
sd

*name,
namelen,
lpSendBuffer,
dwSendDataLength,
lpdwBytesSent,
lpOverlapped

bind()
, . lpOverlapped
WSAOVERLAPPED . ,
, TCP/IP . ConnectEx() DisconnectEx()
Windows XP Windows Server 2003 ,
Windows NT 4.0 Windows 2000.
DisconnectEx()
,
AcceptEx() ConnectEx(). ,
TransmitFile() TransmitPackets()
, DisconnectEx() ,
.
typedef BOOL(PASCAL FAR * LPFN_DISCONNECTEX) (
IN
IN
IN
IN
);

SOCKET sd,
LPOVERLAPPED
DWORD
DWORD

lpOverlapped,
dwFlags,
dwReserved

. dwFlags 0 TF_REUSE_SOCKET.
, TF_REUSE_SOCKET
AcceptEx().
0.

77.1.1.3.

TransmitFile(), TransmitPackets()

TransmitFile()
,
""
.
,
. TRUE FALSE .


WSASend()/ReadFile(),
- TransmitFile()
.
BOOL PASCAL FAR TransmitFile (
IN SOCKET
hSocket,
IN HANDLE
hFile,
IN DWORD
nNumberOfBytesToWrite,
IN DWORD
nNumberOfBytesPerSend,
IN LPOVERLAPPED
lpOverlapped,
IN LPTRANSMIT_FILE_BUFFERS lpTransmitBuffers,
IN DWORD
dwFlags
);

, SOCK_STREAM,
SOCK_SEQPACKET SOCK_RDM, . hFile
, NULL,

lpTransmitBuffers.

nNumberOfBytesToWrite ,
. nNumberOfBytesPerSend
, send(); , by
default, Windows NT Workstation 4k, Windows Server - 64k.
lpOverlapped , ,
.
OVERLAPPED .
lpTransmitBuffers TRANSMIT_FILE_BUFFERS,
, ( )
. 4.4 ,
dwFlags.
4.4 TransmitFile()

TF_DISCONNECT

,
.

TF_REUSE_SOCKET

AcceptEx()
.
TF_DISCONNECT.

TF_USE_DEFAULT_WORKER .
TF_USE_SYSTEM_THREAD

TF_USE_KERNEL_APC

""
(APC) .
TransmitFile() ,
.

TF_WRITE_BEHIND

, TransmitFile() ,
.
TF_DISCONNECT TF_REUSE_SOCKET.


TF_USE_KERNEL_APC . ,
, TransmitFile(), ,
APC. , Winsock
APCs , ,
, APCs , ,
alertable , .

TransmitFile() Windows.
Windows XP/2003 "" WinSock -
TransmitPackets().

TransmitPackets() TransmitFile() , ,
, ,
TCP, UDP ( UDP connect()).
:
BOOL (PASCAL FAR * LPFN_TRANSMITPACKETS) (
SOCKET
hSocket,
LPTRANSMIT_PACKETS_ELEMENT lpPacketArray,
DWORD
nElementCount,
DWORD
nSendSize,
LPOVERLAPPED
lpOverlapped,
DWORD
dwFlags
);
lpPacketArray

TRANSMIT_PACKETS_ELEMENT:
typedef struct _TRANSMIT_PACKETS_ELEMENT {
ULONG dwElFlags;
ULONG cLength; // . 0, .
union {struct
{
LARGE_INTEGER nFileOffset;
//
HANDLE
hFile;
//
};
PVOID
pBuffer;
//
};
} TRANSMIT_PACKETS_ELEMENT;

dwElFlags ,
lpPacketArray, TP_ELEMENT_MEMORY, TP_ELEMENT_FILE TP_ELEMENT_EOP
send().
. nElementCount

TRANSMIT_PACKETS_ELEMENT,
nSendSize

nNumberOfBytesPerSend TransmtFile(), lpOverlapped () .


4.4 TP.
TP_DISCONNECT TP_REUSE_SOCKET
. ,
. TRUE FALSE .

77.1.1.4.

WSARecvMsg()

WSARecv()
WSARecvFrom(), ,
. 0, - SOCKET_ERROR.
int WSARecvMsg(
SOCKET s,
LPWSAMSG lpMsg,
LPDWORD lpdwNumberOfBytesRecvd,
LPWSAOVERLAPPED lpOverlapped,
LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
);

, WSAMSG,
Posix.1g msghdr.
78.

RSVP


. IPv4, TOS
Type Of Service ( 1.2.1) .
, Frame Relay
ATM, ,
,
,
, IPv6 .

IPv6 ,
Ethernet,

.
WinSock 2 QOS, API,
IPv4.
QOS (Quality Of Service )
:



"" ""
"" ,
, UDP
QOS WinSock 2 Windows-
QOS- TCP/IPv4 UDP/IPv4 ,
Windows 98, Windows Me, Windows 2000 Windows XP. QOS
IPv6 , QOS
"IP ATM".
QOS Windows-
, ,
IPv4 .
, QOS :

QOS ( RSVP
IEEE)



, ,
RSVP (Resource ReSerVation Protocol RFC-2205, 1997), QOS .
RSVP
.
,
() . RSVP ,
. ,
RSVP .
OSI RSVP ,
IP, ,
ICMP.
RSVP .
IP-, ,
,
, 2/, 100 .
PathMessage IP- , ,
FlowSpec.

-:
250-300 .
, VoIP, ,
, ,
VoIP.

-
, . , IP-

, FlowSpec, AdmissionControl PolicyControl. AdmissionControl


,
PolicyControl QOS.
, , AdmissionControl PolicyControl
QOS.
-, .
RSVP ,
,
. RSVP
, ().
- .
RSVP QOS ,
, :
IEEE 802.1p (1998 ) - 3
MAC

IEEE 802.1Q (1998 ) - Ethernet


,
( ). ,
, ,
IEEE 802.1p.

IP- IP- TOS

OSI-2 RSVP ""


QOS- WAN

SBM - Subnet Bandwidth Manager - ,


.
Windows-.

,
IEEE 802.1p 802.1Q

, QOS,
,
. WinSock 2
.
" - generic" -
GQOS, .
WinSock- WSAEnumProtocols(),
WSAPROTOCOL_INFO. dwServiceFlags1
XP1_QOS_SUPPORTED, -.
(T Traffic
Control). TOS IPv4. GPC,
" " , PC,
.
- RSVP. GQOS
"" , .
GQOS API TC API.
79.

Helper API

WinSock 2 ,
,
, TCP/IP .


,
Windows-, :
IPCONFIG.EXE - ( WINIPCFG.EXE Windows 95, Windows 98 Windows Me).
TCP/IP.

NETSTAT.EXE - TCP,
UDP IPv4.

ROUTE.EXE - IPv4.

ARP.EXE - ARP-.

IPV6.EXE - IPv6-.

IPHLPAPI.H

IPTYPES.H

IPHLPAPI.DLL , (. 8)

IPHLPAPI.LIB.
IP Helper :
:

GetNetworkParams()

GetAdaptersInfo()
GetAdapterIndex()
GetPerAdapterInfo()
GetUniDirectionalAdapterInfo()

GetNumberOfInterfaces()
GetInterfaceInfo()
GetFriendlyIfIndex()
GetIfEntry()
GetIfTable()
SetIfEntry()

IP-:

GetIpAddrTable()
AddIPAddress()
DeleteIPAddress()
IpReleaseAddress()
IpRenewAddress()

ARP:

GetIpNetTable()
CreateIpNetEntry()
DeleteIpNetEntry()
FlushIpNetTable()
CreateProxyArpEntry()
DeleteProxyArpEntry()
SendARP()

IP ICMP :

GetIpStatistics()

GetIcmpStatistics()
SetIpStatistics()
SetIpTTL()

CreateIpForwardEntry()
DeleteIpForwardEntry()
SetIpForwardEntry()
GetIpForwardTable()
GetBestRoute()
GetBestInterface()
GetRTTAndHopCount()

NotifyAddrChange()
NotifyRouteChange()

TCP UDP:

GetTcpStatistics()
GetUdpStatistics()
GetTcpTable()
GetUdpTable()
SetTcpEntry()

, iphlpapi.dll
, , , .

GetNetworkParams():
DWORD GetNetworkParams(
PFIXED_INFO pFixedInfo, // FIXED_INFO
PULONG pOutBufLen
//
);

ERROR_SUCCESS.
, ERROR_BUFFER_ OVERFLOW
, .
, , ERROR_NOT_SUPPORTED,
GetNetworkParams() .
FormatMessage()
.
FIXED_INFO :
typedef struct
{
char
HostName[MAX_HOSTNAME_LEN + 4] ;
char
DomainName[MAX_DOMAIN_NAME_LEN + 4];
PIP_ADDR_STRING CurrentDnsServer;
IP_ADDR_STRING DnsServerList;
UINT
NodeType;
char
ScopeId[MAX_SCOPE_ID_LEN + 4];
UINT
EnableRouting;
UINT
EnableProxy;
UINT
EnableDns;
} FIXED_INFO, *PFIXED_INFO;

HostName
DomainName
CurrentDnsServer
DnsServerList

, DNS.
, .
.
IP_ADDR_STRING,
DNS-, .

NodeType

ScopeId
EnableRouting
EnableProxy
EnableDns

. BROADCAST_NODETYPE,
PEER_TO_PEER_NODETYPE, MIXED_NODETYPE
HYBRID_NODETYPE. 5.1.1.
DHCP.
, .
, ARP-.
, DNS .


, MSDN
4.5
// iphlpapi.lib
#include <stdio.h>
#include <windows.h>
#include <iphlpapi.h>
main() {
FIXED_INFO * SomeNetInfo;
ULONG
ulOutBufLen;
DWORD
dwRetVal;
IP_ADDR_STRING * pIPAddr;
SomeNetInfo = (FIXED_INFO *) GlobalAlloc( GPTR, sizeof( FIXED_INFO ) );
ulOutBufLen = sizeof( FIXED_INFO );
if( ERROR_BUFFER_OVERFLOW == GetNetworkParams( SomeNetInfo, &ulOutBufLen ) )
{
GlobalFree( SomeNetInfo );
SomeNetInfo = (FIXED_INFO *) GlobalAlloc( GPTR, ulOutBufLen );
}
if ( dwRetVal = GetNetworkParams( SomeNetInfo, &ulOutBufLen ) )
{
printf( "GetNetworkParams failed. Return Value: %08x\n", dwRetVal );
}
else {
printf( "Host Name: %s\n", SomeNetInfo -> HostName );
printf( "Domain Name: %s\n", SomeNetInfo -> DomainName );
printf( "DNS Servers:\n" );
printf( "\t%s\n", SomeNetInfo -> DnsServerList.IpAddress.String );
pIPAddr = SomeNetInfo -> DnsServerList.Next;
while ( pIPAddr )
{
printf( "\t%s\n", pIPAddr ->IpAddress.String );
pIPAddr = pIPAddr ->Next;
}
}
exit( 0 );
}

GetInterfaceInfo() , .
NO_ERROR.
ERROR_INSUFFICIENT_BUFFER, ,
dwOutBufLen . , , ,
"" ,
.
DWORD GetInterfaceInfo(
PIP_INTERFACE_INFO pIfTable,// IP_INTERFACE_INFO,
//
PULONG dwOutBufLen
//
);

IPHelper GetIpStatistics(),
, .. :
MIB_IPSTATS IPStats;

// MIB_IPSTATS, IP//
if (GetIpStatistics(&IPStats) == NO_ERROR)
{
//
}

MIB_IPSTATS ( MIB - Management Information Base)


23 , ,
IP-, dwDefaultTTL TTL, ,
dwReasmTimeout ,
Reasm reassemby -:
typedef struct _MIB_IPSTATS {
DWORD dwForwarding;
// IP-
DWORD dwDefaultTTL;
//TTL IP-,
DWORD dwInReceives;
// IP-
DWORD dwInHdrErrors;
// IP-
DWORD dwInAddrErrors; // IP-
DWORD dwForwDatagrams; // IP-
DWORD dwInUnknownProtos;// IP-
DWORD dwInDiscards;
// IP-
DWORD dwInDelivers;
// IP-
DWORD dwOutRequests;
// IP-
DWORD dwRoutingDiscards;// IP-
DWORD dwOutDiscards;
// IP-
DWORD dwOutNoRoutes;
//
DWORD dwReasmTimeout; //
DWORD dwReasmReqds;
// ,
DWORD dwReasmOks;
// ,
DWORD dwReasmFails;
// ,
DWORD dwFragOks;
// ,
DWORD dwFragFails;
// DF=1
DWORD dwFragCreates;
// -
DWORD dwNumIf;
//
DWORD dwNumAddr;
// IP-
DWORD dwNumRoutes;
// IP-
} MIB_IPSTATS,*PMIB_IPSTATS;

, ,
IP-, .
GetIcmpStatistics(), GetTcpStatistics() GetUdpStatistics()
,
.
GetTcpTable() SetTcpEntry()
TCP
, , ,
,
SetTcpEntry().
GetTcpTable() TCP:
DWORD GetTcpTable(PMIB_TCPTABLE pTcpTable,PDWORD pdwSize, BOOL bOrder);

:
pTcpTable
pdwSize
bOrder

//[out] , TCP-
// MIB_TCPTABLE
//[in, out] , . ,
// ,
//[in] . TRUE,
// :
//Local IP address
//Local port
//Remote IP address
//Remote port

NO_ERROR.

pTcpTable
ERROR_INSUFFICIENT_BUFFER .
pdwSize.
ERROR_INVALID_PARAMETER
ERROR_NOT_SUPPORTED

pdwSize NULL, GetTcpTable()


pdwSize.
.
FormatMessage()
.

4.6 (MSDN)
//
PMIB_TCPTABLE pTcpTable;
pTcpTable = (MIB_TCPTABLE*) malloc(sizeof(MIB_TCPTABLE));
DWORD dwSize = 0;
// GetTcpTable()
if (GetTcpTable(pTcpTable, &dwSize, TRUE) == ERROR_INSUFFICIENT_BUFFER) {
GlobalFree(pTcpTable);
pTcpTable = (MIB_TCPTABLE*) malloc ((UINT) dwSize);
}
// GetTcpTable()
if ((dwRetVal = GetTcpTable(pTcpTable, &dwSize, TRUE)) == NO_ERROR) {
for (int i = 0; i < (int) pTcpTable->dwNumEntries; i++) {
printf("State: %ld\n", pTcpTable->table[i].dwState);
}
}
else {
printf("\tCall to GetTcpTable failed.\n");
LPVOID lpMsgBuf;
if (FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dwRetVal,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), //
(LPTSTR) &lpMsgBuf,
0,
NULL ))
{
printf("\tError: %s", lpMsgBuf);
}
LocalFree( lpMsgBuf );
}

MIB_TCPTABLE :
typedef struct _MIB_TCPTABLE {
DWORD
dwNumEntries; //
MIB_TCPROW
table[ANY_SIZE];// MIB_TCPROW
//
} MIB_TCPTABLE,*PMIB_TCPTABLE;

- MIB_TCPROW - :
typedef struct _MIB_TCPROW {
DWORD dwState;
// , TCP-
DWORD dwLocalAddr;
// . 0 ,
// ,
//
DWORD dwLocalPort;
//
DWORD dwRemoteAddr; //
DWORD dwRemotePort; //
} MIB_TCPROW, *PMIB_TCPROW;

dwState :
MIB_TCP_STATE_CLOSED
MIB_TCP_STATE_LISTEN
MIB_TCP_STATE_SYN_SENT
MIB_TCP_STATE_SYN_RCVD
MIB_TCP_STATE_ESTAB
MIB_TCP_STATE_FIN_WAIT1
MIB_TCP_STATE_FIN_WAIT2
MIB_TCP_STATE_CLOSE_WAIT
MIB_TCP_STATE_CLOSING
MIB_TCP_STATE_LAST_ACK
MIB_TCP_STATE_TIME_WAIT
MIB_TCP_STATE_DELETE_TCB

SetTcpEntry() TCP-.
DWORD SetTcpEntry(
PMIB_TCPROW pTcpRow
);

//[in]

MIB_TCPROW

TCP-.
NO_ERROR. FormatMessage()
. iprtrmib.h.


, TCP-,
MIB_TCP_STATE_DELETE_TCB .. , .

-
Microsoft[30] [27].
80.

IrDA (Infrared Data Association


) PC 1993 .
(IrSock,) ,
Windows- Windows CE.
,
Windows 98, Windows Me, Windows 2000 Windows XP.
,
.
(
2,5. ), FIR
4 /. /
.. , time
multiplexing.
Bluetooth
10-30 ( ).
1 /.
IrLMP - Link Management Protocol
, .
,
. ,
, , Bluetooth.

IrDA,
.
, ,

, DNS. IrDA
, gethostbyname() IP-,


- AF_IRDA.
:
typedef struct _SOCKADDR_IRDA
{
u_short
irdaAddressFamily;
u_char
irdaDeviceID[4];
char
irdaServiceName[25];
} SOCKADDR_IRDA, *PSOCKADDR_IRDA, FAR *LPSOCKADDR_IRDA;

irdaAddressFamily AF_IRDA.
irdaDeviceID ,
, . IrSock
, , ,
. , irdaServiceName[25]
, () bind(),
c connect() (). Windows E
:
SOCKADDR_IRDA ddress = {AF_IRDA, 0, 0,0,0,"Service_Name"};
IrDA- "" , OBEX (Object
Exchange) , IrCOMM , IrLAN -
Ethernet ..
, IrDA
. Logical
Service Access Point Selectors (LSAP-SEL) IAS.
Logical Service Access Point Selectors 001 06F (1-111Windows CE), Windows 127. 000 ,
IAS (Information Access Services),
- IAS "" DNS.
,
Tiny Transport Protocol (TTP),
(data transmission start/stop).
. IrDA ,
.
Information Access Service (IAS) "yellow pages -
",
, . , PC1 IAS-
PC2 Speakers LSAP-SEL
003, , , , ,
003.

. IrDA-:
sd = socket (AF_IRDA, SOCK_STREAM, 0);

getsockopt():
int getsockopt(SOCKET
optlen);

sd,

int

level,

int

optname,

const

char

FAR

*optval,

int

SOL_IRLMP, optname :

IRLMP_ENUMDEVICES IRDA-;
IRLMP_IAS_QUERY IAS-;
IRLMP_SEND_PDU_LEN -
IrLPT.
IRLMP_ENUMDEVICES
WINDOWS_DEVICELIST :
typedef struct _WINDOWS_DEVICELIST
{

ULONG
numDevice;
WINDOWS_IRDA_DEVICE_INFO
Device[1];
} WINDOWS_DEVICELIST, *PWINDOWS_DEVICELIST, FAR *LPWINDOWS_DEVICELIST;

IRDA_DEVICE_INFO :
typedef struct _WINDOWS_IRDA_DEVICE_INFO
{
u_char irdaDeviceID[4];
char
irdaDeviceName[22];
u_char irdaDeviceHints1;
// Windows CE
u_char irdaDeviceHints2;
// Windows CE
u_char irdaCharSet;
} WINDOWS_IRDA_DEVICE_INFO, *PWINDOWS_IRDA_DEVICE_INFO,
FAR *LPWINDOWS_IRDA_DEVICE_INFO;
:
Windows E .

*optval.
getsockopt() IRLMP_ENUMDEVICES
,
,
getsockopt() . setsockopt(),
IR- ,
IRLMP_DISCOVERY_MODE.
, ,
- TCP- S.
IAS IRLMP_IAS_QUERY DNS-.
IAS_QUERY Windows CE
WINDOWS_IAS_QUERY Windows 98, Me, 2000 XP.
,
c Windows CE ,
WinSock 1.1.

af_irda.h,

http://www.cswl.com/whiteppr/white/arhead.html.
4.7
#include <windows.h>
#include <af_irda.h>
#include <stdio.h>
#pragma comment ( lib, "WS2_32.Lib" )
void main()
{
SOCKET sd;
SOCKADDR_IRDA address = {AF_IRDA, 0, 0,0,0,"MyServer"};
DEVICELIST devList;
char helloClient[25];
int mode = 1;
sd = socket (AF_IRDA, SOCK_STREAM, 0);
//
setsockopt (sd, SOL_IRLMP, IRLMP_DISCOVERY_MODE, (char *)&devList,(int)&mode);
// a
recv(sd, (char *)&devList, sizeof(devList), 0);
//
mode = FALSE;
setsockopt (sd, SOL_IRLMP, IRLMP_DISCOVERY_MODE, (char *) &devList, (int)&mode);
//
for(int i=0;i<=3;i++)address.irdaDeviceID[i] = (char)devList.Device[i].irdaDeviceID;
// MyServer
connect(sd, (struct sockaddr*)&address, sizeof(SOCKADDR_IRDA));

//
send(sd, "Hello Server!", strlen("Hello World!")+1, 0);
// .
recv(sd, helloClient, sizeof(helloClient), 0);
printf("%s\n", helloClient);
closesocket(sd);
}

Windows 2000
WinSock
2.0

http://www.alanjmcf.me.uk/comms/infrared/irdaWinsockCli.cpp.html.


1. , Winsock 2.0
42. -,
WinSock 2.0?
43. WinSock 2.0?
44. / Winsock 2.0?
45. / API WinSock 2.0?
46. " LSP" ?
47. (callback) I/O ?
48. WSAEventSelect()?
49. WinSock ws2_32.dll?
50. WSAProtocolInfo.
51. IEEE 802.1p.802.1Q?
52. RSVP.
53. IP-Helper API?
54. .
55. IAS?
56. getsockopt() setsockopt() IrDA?

1. 5
,

. Microsoft Windows NetBIOS,
Windows, TLI,
- UNIX- ,
BPF, ,
. (
) ,
, .

32. NetBIOS
NetBIOS Network Basic Input Output System
,
, ,
, . 1983 IBM.
, ,
, Windows 95, Windows 98, Windows NT Windows 2000.
NetBIOS
, , 1985 IBM
NetBIOS Extended User Interface (NetBEUI),
NetBIOS . NetBIOS , Chat
Notes Windows NT, Microsoft Mail NetBIOS
. NetBIOS , , SMB,
Windows. , nbsession, nbname nbdatagram,
, , -
,
, .

NetBIOS
,
, .
81.

NetBIOS

2.1 NetBIOS
TCP/IP "" NetBEUI. .
, ,
( ). ,
NetBEUI, TCP/IP, .
NetBIOS , NetBEUI
, , .
- TCP/IP IPX/SPX,
.

NetBIOS Windows- IPX/SPX, IPX/SPX
.

NetBIOS,
NetBIOS.
NetBIOS . , ,
, .
NetBIOS "", .. ,
. 16- ,
15- . 15 ,
. 16- (),
.
, NetBIOS- SATURN, Messenger
Service ( 03h) 16- / "53 41 54 55 52 4E 20 20 20 20 20 20
20 20 20 03". "*" () . 5.1-5.2
NetBIOS.
5.1 NetBIOS

00

20

1B

Domain Master Browser

03

Messenger Service

03

Messenger Service

1D

Master Browser

06

Remote Access Server (RAS) Service

1F

NetDDE (Network Dynamic Data Exchange) Service

21

RAS Client Service

BE

Network Monitor Agent

BF

Network Monitor Application


Browser . ( )
: Domain Master Browser ( ), Master
Browser ( ), Backup Browser ( ), Nonbrowser ( ).

5.2 NetBIOS

00

Domain Name ( )

1C

Domain Controller ( )

1E

Browser Service Elections ( )


25

, , nbtstat
n:

, NetBIOS- "MSHOME" "OLEG"


<03h> <00h>.
"UNIQUE " "GROUP".
, RFC-1000 1001. RFC, 4
, (" "): B-
(), P- ( - peer), M- () H- ();
. , B-
UDP-.
, , , ,
. ,
, IP-.
P- NetBIOS ( WINS
Windows NT), M- ,
, H- WINS , ,
.
NetBIOS,
- LANA Numbers LANA,
NetBIOS.
LANA "Local Area Network (LAN) Adapter",
"LANA number" - , c "
", NetBIOS. ,
, NetBIOS - TCP/IP NetBEUI.
LANA :
LANA

TCP/IP- 1

NetBEUI- 1

TCP/IP- 2

NetBEUI- 2

" "
. Windows- 0 "default route
", , LANA,
. Windows- NetBIOS

NCBENUM, LANA.
, LANA .
Windows NT, Windows 2000 Windows XP
NetBIOS , NetBEUI,
WinSock 2.
82.

NetBIOS

, "" NetBIOS
NetBEUI. "NetBIOS over TCP NetBIOS TCP",
" NetBT". ""
TCP/IP NetBIOS
NBT netbios.dll.
NetBT " " :
TCP
139 - nbsession NetBIOS
42 - WINS - Windows Internet Name System Windows
UDP
137 - nbname
138 - nbdatagram UDP-
42 - - WINS
:
WINS NetBIOS- IP-. WINS
NetBIOS (NetBIOS Name Server-NBNS) Microsoft
NetBIOS TCP/IP -.
WINS, , IP , . , WINS ,
- .

TCP- NetBIOS 139 , ,


,
NetBIOS.
NetBIOS, Transaction ID -
, , .
NetBIOS TCP ,
, , 2
65536 . UDP .
NetBIOS 137 UDP.
NetBIOS IP-
.

, .
WinNuke, ""
.
TCP " - OOB". Windows
139 p OOB-, p NetBIOS,
, p pp .

82.1.1.1.

NetBIOS-

NetBIOS
:
UCHAR Netbios(PNCB pNCB);

, , ..
nb30.h. ( 3.0 ).
netapi32.lib.
NetBIOS- NCB (network control block),
pNCB. NetBIOS-
NetBIOS- ( 11).
typedef struct _NCB
{
UCHAR
ncb_command;
UCHAR
ncb_retcode;
UCHAR
ncb_lsn;
UCHAR
ncb_num;
PUCHAR
ncb_buffer;
WORD
ncb_length;
UCHAR
ncb_callname[NCBNAMSZ];
UCHAR
ncb_name[NCBNAMSZ];
UCHAR
ncb_rto;
UCHAR
ncb_sto;
void
(*ncb_post) (struct _NCB *);
UCHAR
ncb_lana_num;
UCHAR
ncb_cmd_cplt;
UCHAR
ncb_reserve[10];
HANDLE
ncb_event;
} * PNCB, NCB;

NetBIOS, . ,
.

ncb_command - NetBIOS, .
.
ncb_retcode - .
ncb_lsn - .
NCBCALL NCBLISTEN.
ncb_num , .
ncb_buffer .
, NCBENUM,
LANA_ENUM.
ncb_length .
. NetBIOS NRC_BUFLEN.
ncb_callname[NCBNAMSZ]; .
ncb_name[NCBNAMSZ]; , .
ncb_rto - timeout . 0 .
500- .
ncb_sto - timeout . 0 .
500- .
ncb_post .
void CALLBACK PostRoutine(PNCB pncb);
pncb NCB .
ncb_lana_num LANA, .
ncb_cmd_cplt . NetBIOS
NRC_PENDING, .
ncb_reserve , 0.
ncb_event - - Windows,
.
. .
0, ncb_command ASYNCH ncb_post 0.
NRC_ILLCMD.

NCBNAMSZ=16 NB30.h , .


NetBIOS.
5.1 LANA
#include "iostream.h"
#include "stdio.h"
#include "windows.h"
#include "NB30.h"
int main()
{
LANA_ENUM lan_num;
NCB
ncb;
UCHAR uRetCode;
memset( &ncb, 0, sizeof(ncb) );
// NCB
ncb.ncb_command = NCBENUM;
// LANA
ncb.ncb_buffer = (unsigned char *) &lan_num; // lan_num
ncb.ncb_length = sizeof(lan_num);
uRetCode = Netbios((NCB*) &ncb );
// Netbios()
if (uRetCode != 0)
{
cout << "error NCBENUM " << endl;
exit(1);
}
for (int i=0;i<lan_num.length; i++) // LANA
{
printf( "The LANA Number is: %03u",lan_num.lana[i]);
cout << endl;
}
return 0;
}

( Windows 98)
TCP/IP LANA- 001 002.

NetBEUI
LANA 001 002 TCP/IP 006, 007 NetBEUI.

5.2
#include "iostream.h"
#include "stdio.h"
#include "windows.h"
#include "NB30.h"
#define LANANUM
001

//
//
#define LOCALNAME
"LOCAL NET"
#define MAX_SESSION 20
#define MAX_NAMES
30
void main()
{
NCB ncb;
UCHAR uRetCode;
memset (&ncb, 0, sizeof (ncb));
// ncb
ncb.ncb_command = NCBRESET;
// Reset

ncb.ncb_lsn = 0;
ncb.ncb_lana_num = LANANUM;
ncb.ncb_callname[0] = MAX_SESSION;
ncb.ncb_callname[2] = MAX_NAMES;
uRetCode = Netbios((NCB*) &ncb );
if ( uRetCode != 0 )
{
cout << "error NCBRESET " << endl;
exit(1);
}
//
int i_strlen;
NCB ncb1;
memset(&ncb1, 0, sizeof (ncb1));// ncb1
i_strlen = strlen(LOCALNAME);
if (i_strlen > NCBNAMSZ)
i_strlen = NCBNAMSZ;
memset (ncb1.ncb_name, ' ', NCBNAMSZ);
memcpy (ncb1.ncb_name, LOCALNAME, i_strlen);
// NetBios-
ncb1.ncb_command = NCBADDNAME;
ncb1.ncb_lana_num = LANANUM;
uRetCode = Netbios((NCB*) &ncb1 );
if ( uRetCode != 0 )
{
cout << "error NCBADDNAME " << endl;
exit(1);
}
// NetBios-
NCB ncb2; //
ADAPTER_STATUS *pStatus;
memset (&ncb2, 0, sizeof (ncb2));// ncb2
HANDLE hHeap;
int cbBuffer;
hHeap = GetProcessHeap();
//
// ADAPTER_STATUS
cbBuffer = sizeof (ADAPTER_STATUS) + 255 * sizeof (NAME_BUFFER);
pStatus = (ADAPTER_STATUS *) HeapAlloc (hHeap, 0, cbBuffer);
memset (ncb2.ncb_callname, ' ', NCBNAMSZ);
memcpy (ncb2.ncb_callname, LOCALNAME, i_strlen);
ncb2.ncb_command = NCBASTAT;
// NCBASTAT
ncb2.ncb_lana_num = LANANUM;
ncb2.ncb_buffer = (PUCHAR) pStatus;
ncb2.ncb_length = cbBuffer;
uRetCode = Netbios((NCB*) &ncb2 );
if ( uRetCode != 0 )
{
cout << "error NCBASTAT " << endl;
exit(1);
}
//
NAME_BUFFER *pNames;
pNames = (NAME_BUFFER *) (pStatus + 1);
for (int i = 0; i < pStatus->name_count; i++) printf ("\t%.*s\n", NCBNAMSZ, pNames[i].name);
HeapFree (hHeap, 0, pStatus);
cout << pStatus->name_count << endl;
cout << "Cansel" << endl;
}

OLEG MSHOME,
- LOCAL NET. .

82.1.1.2.
WinSock

NetBIOS-

NetBIOS
"NetBIOS TCP - NBT",
WinSock-.
NetBIOS.
NetBIOS- WinSock
WSNETBS.H:
#define NETBIOS_NAME_LENGTH 16
typedef struct sockaddr_nb
{
short
snb_family;
//AF_NETBIOS
u_short snb_type;
char
snb_name[NETBIOS_NAME_LENGTH];
} SOCKADDR_NB, *PSOCKADDR_NB, FAR *LPSOCKADDR_NB;

// snb_type - .
#define NETBIOS_UNIQUE_NAME
#define NETBIOS_GROUP_NAME

(0x0000)
(0x0001)

snb_name NetBIOS-.
WSNETBS.H SET_NETBIOS_SOCKADDR(),
:
#define SET_NETBIOS_SOCKADDR(_snb, _type, _name, _port)
\
{
\
int _i;
\
(_snb)->snb_family = AF_NETBIOS;
\
(_snb)->snb_type = (_type);
\
for (_i = 0; _i < NETBIOS_NAME_LENGTH - 1; _i++)
\
{
\
(_snb)->snb_name[_i] = ' ';
\
}
\
for (_i = 0; *((_name) + _i) != '\0'
\
&& _i < NETBIOS_NAME_LENGTH - 1; _i++)
\
{
\
(_snb)->snb_name[_i] = *((_name)+_i);
\
}
\
(_snb)->snb_name[NETBIOS_NAME_LENGTH - 1] = (_port); \
}

SOCKADDR_NB
AF_NETBIOS. _type - NETBIOS_UNIQUE_NAME
NETBIOS_GROUP_NAME. NetBIOS
. .
LANA.
, LANA , -
NetBIOS .
NETBIOS- .
socket() WSASocket():
sd = WSASocket(AF_NETBIOS, SOCK_DGRAM, -LANA, NULL, 0, WSA_FLAG_OVERLAPPED);

SOCK_DGRAM
SOCK_SEQPACKET. "" LANA

(.. ), , "".
NULL, WSAPROTOCOL_INFO
, . , dwFlags
WSA_FLAG_ OVERLAPPED, .
NetBIOS-
LANA , LANA
WinSock . , NCB()
NCBENUM, .
5- WSAEnumProtocols().
, :
5.3 WSAPROTOCOL_INFO

SOCKET sd[MAX];
int i,j;
dwNum = WSAEnumProtocols(NULL, lpProtocolBuf, &dwBufLen);
if (dwNum == SOCKET_ERROR){
// Error}
for (i = 0; i < dwNum; i++)
{
// AF_NETBIOS
if (lpProtocolBuf[i].iAddressFamily == AF_NETBIOS)
{
// - SOCK_DGRAM
if (lpProtocolBuf[i].iSocketType == SOCK_DGRAM)
{
sd[j++] = WSASocket(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO,
&lpProtocolBuf[i], 0, WSA_FLAG_OVERLAPPED);
}
}
}

,
AF_NETBIOS
WSAPROTOCOL_INFO.
LANA iProtocol ( LANA=0;
iProtocol LANA 0x80000000,
WinSock.) j .

33.
. 2.1 ,
.
,
,
.

. ,
RARP UNIX- ,
.

,
UNIX- Windows-:
1. BPF BSD Packet Filter. 1992 , 1993 .
Steven McCanne Van Jacobson "The BSD Packet Filter: A
New Architecture forUser-level Packet Capture. Proceedings of the 1993 Winter USENIX
Technical Conference (San Diego, CA, Jan. 1993), USENIX". BPF

4.4BSD, BSD/386, NetBSD FreeBSD, ,



.
,
. BPF
UNIX- tcpdump.
, BPF
.
2. DLPI Data Link Provider Interface
SVR4 .
AT&T UNIX-
.
3. Linux-.
,
SOCK_PACKET , : sd=socket(AF_UNIX,
SOCK_PACKET, htons(ETH_P_ALL)); sd=socket(PF_PACKET, SOCK_RAW, htons
(ETH_P_ALL));
Ethernet ETH_P_XXX,
XXX IP, IPV6, ARP ALL .
,
. , Linux Socket Filter
(LSF).
4. Windows-. NDIS
WinDump, UNIX tcpdump. WinDump WinPcap (.
) Windows- (win32).
, Windows 9x,
Windows , Windows NT Windows 2000
, .
WinDump - - 4.
,
, promiscuous
mode ("" ).

"" (LINUX)
(tcpdump, WinDump). DLPI
.

. 5.1
.

.5.1

BPF :
1. BPF ( ) ,
. BPF
ioctl(). ( 4 )
BPF. (store buffer )
, (hold buffer )

"", ,
, .
2. ,
.
BPF, (hook),

, " capture length". , tcpdump
68 , 14 Ethernetheader +20 IP-header + 20 TCP-header + 14 .
,
BPF- ,

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

UNIX- -
libcap libpcap (packet capture
library.) BPF.

. ( ), BPF
.


(Ethernet, FDDI ..),
- . Windows-
tcpdump, WinDump Windows- UNIX- WinPcap, (

http://www.cherepovetscity.ru/insecure/reading/papers/libpcap.htm.)
libpcap 25- ,
BPF.
.
, 5.1
WinDump WinPCAP. ,
PCAP (Packet Capture ),
NDIS (Network Driver Interface Specification
)
- IP, IPX .. NDIS ,

.
BPF BPF, .
PCAP ( WinPCAP) NDIS, BPF:

,
.
,
, , .
, BPF.

, ,
,
.
.

, (packet capture driver),
libpcap,
.

Windows WinPCAP,
PCAP Windows. PCAP Win32
, UNIX.
, libpcap,
pcap-xxx.c (
pcap-xxx.h), xxx (, pcaplinux.c), pcap-win32.c pcap-win32.h.

. Libpcap Win32
, packet.dll. ,
"UNIX- ", ,
UNIX select(), ,
, Windows select() .
Windows- libpcap
,
(, libpcap ).
packet.dll Win32
.

libpcap
, Windows,
#ifdef #ifndef, libpcap Windows,
UNIX, :
#ifdef WIN32
/* Windows */
#endif

WinPCAP Win32 API


,
. , WinPCAP
: (paket.vxd),
(packet.dll) - wpcap.dll ( libpcap
0.5).
()
Linux. ,
. :
a. eth0,
IP , , MTU, ,
(promiscuous mode). ,
, ;
b.
(eth0).
- MAC- IP- ,
, IP , (TCP/UDP),
. SIGINT
( Ctrl+C);
c. SIGINT, ,
.
, .
getifconf().
. :
int getifconf(__u8 *, struct ifparam *, int);

, ;
, .
, .
getsock_recv(). .
int getsock_recv (int);

,
.
struct ifparam,
, analizator.h.
5.4. analizator.h
#include <linux/types.h>
#define PROMISC_MODE_ON 1
//
#define PROMISC_MODE_OFF 0 //
struct ifparam {
__u32 ip;
// IP
__u32 mask;
//
int mtu;
// MTU
int index;
//

} ifp;

.
5.5. ( getifconf.c)
#include <linux/socket.h>
#include <linux/ioctl.h>
#include <linux/if.h>
#include <linux/in.h>
#include "analizator.h"
int getifconf(__u8 *intf, struct ifparam *ifp, int mode)
{
int fd;
struct sockaddr_in s;
// ifreq <linux/if.h>
// .
struct ifreq ifr;
memset((void *)&ifr, 0, sizeof(struct ifreq));
if((fd = socket(AF_INET,SOCK_DGRAM,0)) < 0)return (-1);
sprintf(ifr.ifr_name,"%s",intf);
/* . 0,
* , setmode.
*/
if(!mode) goto setmode;
/* IP */
if(ioctl(fd, SIOCGIFADDR, &ifr) < 0)
{
perror("ioctl SIOCGIFADDR");
return -1;
}
memset((void *)&s, 0, sizeof(struct sockaddr_in));
memcpy((void *)&s, (void *)&ifr.ifr_addr, sizeof(struct sockaddr));
memcpy((void *)&ifp->ip, (void *)&s.sin_addr.s_addr, sizeof(__u32));
/* */
if(ioctl(fd, SIOCGIFNETMASK, &ifr) < 0)
{
perror("ioctl SIOCGIFNETMASK");
return -1;
}
memset((void *)&s, 0, sizeof(struct sockaddr_in));
memcpy((void *)&s, (void *)&ifr.ifr_netmask, sizeof(struct sockaddr));
memcpy((void *)&ifp->mask, (void *)&s.sin_addr.s_addr, sizeof(u_long));
/*
* MTU
*/
if(ioctl(fd, SIOCGIFMTU, &ifr) < 0)
{
perror("ioctl SIOCGIFMTU");
return -1;
}
ifp->mtu = ifr.ifr_mtu;
/*
*
*/
if(ioctl(fd, SIOCGIFINDEX, &ifr) < 0)
{
perror("ioctl SIOCGIFINDEX");
return -1;
}
ifp->index = ifr.ifr_ifindex;

/* */
setmode:
/* */
if(ioctl(fd, SIOCGIFFLAGS, &ifr) < 0)
{
perror("ioctl SIOCGIFFLAGS");
close(fd);
//
return -1;
}
/* ,
* */
if(mode) ifr.ifr_flags |= IFF_PROMISC;
else ifr.ifr_flags &= ~(IFF_PROMISC);
/* */
if(ioctl(fd, SIOCSIFFLAGS, &ifr) < 0)
{
perror("ioctl SIOCSIFFLAGS");
close(fd);
//
return (-1);
}
return 0;
}

ioctl() SIOCGIFADDR, SIOCGIFNETMASK, SIOCGIFMTU .


<linux/sockios.h>. , ..
<linux/socket.h>.
5.6 ( getsock_recv.c)
#include <linux/socket.h>
#include <linux/types.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
int getsock_recv(int index)
{
int sd; //
/*
* sockaddr_in sockaddr_ll
* (. <linux/if_packet.h>)
*/
struct sockaddr_ll s_ll;
/* C . .. MAC- ,
* type socket SOCK_RAW
*/
sd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if(sd < 0) return -1;
memset((void *)&s_ll, 0, sizeof(struct sockaddr_ll));
/* s_ll */
s_ll.sll_family = PF_PACKET;
//
s_ll.sll_protocol = htons(ETH_P_ALL);
//
s_ll.sll_ifindex = index;
//
/* . ,
* .
* ,
* ,
*/
if(bind(sd, (struct sockaddr *)&s_ll, sizeof(struct sockaddr_ll)) < 0) {
close(sd);
return -1;
}

return sd;
}


main().

eth0 setsockopt(), : rc =
setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, "eth0\x00", strlen("eth0\x00")+1); ,
.
5.7 ( analizator.c)
#include <stdio.h>
#include <signal.h>
#include <sys/socket.h>
#include <linux/if_ether.h>
#include <linux/in.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include "analizator.h"
/*
* buff . ETH_FRAME_LEN
* Ethernet (1514) <linux/if_ether.h>
*/
__u8 buff[ETH_FRAME_LEN];
/*
* mode_off SIGINT. -
* SIGINT "Promiscuous mode" .
*/
void mode_off()
{
if(getifconf("eth0", &ifp, PROMISC_MODE_OFF) < 0)
{
perror("getifconf");
exit(-1);
}
return;
}
/* */
int main()
{
__u32 num = 0;
int eth0_if, rec = 0, ihl = 0;
struct iphdr ip;
// IP
struct tcphdr tcp;
// TCP
struct ethhdr eth;
// Ethernet-
static struct sigaction act;
/* eth0 */
if(getifconf("eth0", &ifp, PROMISC_MODE_ON) < 0) {
perror("getifconf");
return -1;
}
/* */
printf("IP - %s\n",inet_ntoa(ifp.ip));
printf(" - %s\n",inet_ntoa(ifp.mask));
printf("MTU - %d\n", ifp.mtu);
printf(" - %d\n", ifp.index);
/* */
if((eth0_if = getsock_recv(ifp.index)) < 0) {
perror("getsock_recv");

return -1;
}
/* SIGINT - mode_off */
act.sa_handler = mode_off;
sigfillset(&(act.sa_mask));
sigaction(SIGINT, &act, NULL);
/* */
for(;;)
{
memset(buff, 0, ETH_FRAME_LEN);
rec = recvfrom(eth0_if, (char *)buff, ifp.mtu + 18, 0, NULL, NULL);
if(rec < 0 || rec > ETH_FRAME_LEN) {
perror("recvfrom");
return -1;
}
memcpy((void *)&eth, buff, ETH_HLEN);
memcpy((void *)&ip, buff + ETH_HLEN, sizeof(struct iphdr));
if((ip.version) != 4) continue;
memcpy((void *)&tcp, buff + ETH_HLEN + ip.ihl * 4, sizeof(struct tcphdr));
/* MAC- */
printf("\n%u\n", num++);
printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\t->\t",
eth.h_source[0],eth.h_source[1],eth.h_source[2],
eth.h_source[3],eth.h_source[4],eth.h_source[5]);
printf("%.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
eth.h_dest[0],eth.h_dest[1],eth.h_dest[2],
eth.h_dest[3],eth.h_dest[4],eth.h_dest[5]);
printf(" - %d, ", (ip.ihl * 4));
printf(" - %d\n", ntohs(ip.tot_len));
/* - TCP, IP */
if(ip.protocol == IPPROTO_TCP) {
printf("%s (%d)\t->\t",inet_ntoa(ip.saddr), ntohs(tcp.source));
printf("%s (%d)\n",inet_ntoa(ip.daddr), ntohs(tcp.dest));
printf("TCP \n");
}
}
return 0;
}


.
/var/log/messages:
eth0: Promiscuous mode enabled.
device eth0 entered promiscuous mode
Ctrl+C.
SIGINT, mode_off()
. /var/log/messages :
device eth0 left promiscuous mode

1. NetBIOS.
2. NetBIOS-?
3. NetBIOS .
?
4. NetBIOS TCP/IP? ,
?

5.
.
6. BPF , ?
7.
?
8. Linux- ?
9. , , ?
10. tcpdump Windows? ?

,
, , ,
,
, ,
,
.


UNIX Windows,
, MS TDI (Transport Driver Interface), MS NAL (Network
Abstraction Layer Interface), WinInet . ,
, ,
.


1. . Ethernet "LAN", 03, 1998 , "
" (www.osp.ru). http://www.osp.ru/lan/1998/03/23.htm
2. ., . Windows/. . .:
, 1996.
3. . /. c . .: " "
"Channel Trading Ltd", 1999. ISBN 5-7502-0102-3
4. ., connect(). http://www.kalinin.ru/programming/network/01_12_00.shtml
5. . . "LAN", 06, 1997 //
" " http://www.osp.ru/lan/1997/06/131.htm
6. . . - "LAN", 05, 1997 // "
" http://www.osp.ru/lan/1997/05/87.htm
7. . . 11/99 .
2, http://www.citforum.ru/internet/tifamily/optimize02.shtml
8. . " ". .
http://athena.vvsu.ru/net/book/ip.html
9. ., . Internet " "
02/99, http://opensystems.ru/os/1999/02/06.htm
10. .., .., .. Internet 3- . .: , 2000.
11.

http://www.fssr.ru/icccs/1251/fomenkov_99_2.htm

12. ., . Microsoft Windows , ISBN: 5-318-00725-2


"", 2002
13. ., . - . IP-
, http://www.citforum.ru/nets/ip/
14. Internet.
http://alice.stup.ac.ru/~dvn/complex/labin.htm
15. .. : . .: , 1998 .
16. .. ( ), Telecommunication technologies (v2.1). http://book.itep.ru
17. . Linux IP Stacks : 2001, ., , ISBN: 966-7393-83-6
18. . TCP/IP. . : ,
2001 ISBN 5-318-00453-9
19. .. UNIX: .: , 2003, ISBN:5-318-00535-7
20. .. UNIX: .: , 2003, ISBN:5-318-00534-9
21. .. TCP/IP, ..,
. rk6fed@wwwcdl.bmstu.ru
22. . TCP/IP/. . .: , 2000.
23. .., .. . Internet, Email, FTP, WWW HTML, Windows Sockets.
; . 23 .: -, 1996.
24. Albitz P., Cricket L. DNS and BIND, 4th Edition April 2001, ISBN: 0-596-00158-4

25. Beej's Guide to Network Programming Using Internet Sockets Version 1.5.3 (01-Nov-1997).
http://www.ecst.csuchico.edu/~beej/guide/net
26. De Goyeneche J-M. Multicast over TCP/IP HOWTO http://docs.iho.ru/HOWTO/en/MulticastHOWTO.html#toc6
27. Jones A., Ohlund J., Ohlund Jim Network Programming for Microsoft Windows, Second Edition
Microsoft Press, February 13, 2002 ISBN: 0735615799
28. Jones A., Ohlund J. Network Programming for Microsoft Windows (Microsoft Press, 1999)
29. McCanne S. and Jacobson V. The BSD Packet Filter: A New Architecture for User-level Packet Capture.
Proceedings of the 1993 Winter USENIX Technical Conference (San Diego, CA, Jan. 1993), USENIX.
30. MSDN 6.0/Platform SDK/Networking and Distributed Services/ Windows Sockets version 2 / Windows
Sockets version 2 API / Reference
31. Net Programing. http://www.kgtu.runnet.ru/WD/TUTOR/tcpip/netprg2.html
32. Quinn B., Shute D. Windows Sockets Network Programming. Addison Wesley Professional Copyright,
1996. ISBN 0-201-63372-8
33. RFC-1180 Network Working Group Request for Comments: 1180 T. Socolofsky C. Kale, Spider
Systems Limited. January 1991. A TCP/IP Tutorial
34. RFC-793. TCP. . , 1994 . http://info.internet.isi.edu/innotes/rfc/files/rfc793.txt
35. RFC-791 Internet . Darpa Internet. , 1981.
36. Roberts D. Developing for the Internet with WinSock, www.itknowledge.com. Publication Date:
09/01/95.
37. Stevens W. R. TCP/IP Illustrated, Volume 1: The Protocols, Addison-Wesley, 1994, ISBN 0-201-633469
38. The Single UNIX Specification, Version 2, 1997 The Open Group
39. Windows Sockets. An Open Interface for Network Programming under Microsoft Windows Version
1.1
40. . : 2003, BHV
41. : Delphi. : Windows
http://www.compdoc.ru/prog/pascal/use_sockets2/


1
IPv4

/* Copyright (c) 1989, 1993


The Regents of the University of California. All rights
reserved.
* This code is derived from software contributed to Berkeley by Mike Muuss.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
*
notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
*
notice, this list of conditions and the following disclaimer in the
*
documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
*
must display the following acknowledgement:
*
This product includes software developed by the University of
*
California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
*
may be used to endorse or promote products derived from this software
*
without specific prior written permission.
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
/* in_cksum -Checksum routine for Internet Protocol family headers (C Version) */
unsigned short in_cksum(unsigned short *addr, int len)
{
register int sum = 0;
u_short answer = 0;
register u_short *w = addr;
register int nleft = len;
/* Our algorithm is using a 32 bit accumulator (sum), we add sequential 16 bit words
* to it, and at the end, fold back all the carry bits from the top 16 bits into the
* lower 16 bits. */
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
/* mop up an odd byte, if necessary */
if (nleft == 1)
{
*(u_char *)(&answer) = *(u_char *)w ;
sum += answer;
}
/* add back carry outs from top 16 bits to low 16 bits */
sum = (sum >> 16) + (sum & 0xffff);
/* add hi 16 to low 16 */
sum += (sum >> 16);
/* add carry */
answer = ~sum;
/* truncate to 16 bits */
return(answer);


, TCP UDP.

2
IPV6
IPv6 3-11 .
, "Format Prefix".
IPv6,
, .


NSAP
IPX


















0000 0000
0000 000
0000 00
0000010
0000011
0000 1
0001
001
010
011
100

1/256
1/256
1/128
1/128
1/128
1/32
1/16
1/8
1/8
1/8
1/8

101
110
1110
1111 0
1111 10
1111 110
1111 11100
1111 1110 10
1111 1110 11
1111 1111

1/8
1/8
1/16
1/32
1/64
1/128
1/512
1/1024
1/1024
1/256

3
PING
,
Ping. :

(,
).
ICMP (nIcmpId nIcmpSeq)
ECHO- ECHO-.
, ECHO- , .
. Berkeley,
ICMP , IP
, ICMP .
, IP_TTL, TTL
ICMP ECHO, ICMP-
, .
- Windows.

/* ICMP types */
#define ICMP_ECHOREPLY 0
/* ICMP : */
#define ICMP_ECHOREQ 8
/* ICMP : */
/* ICMP RFC 792 */
typedef struct icmp_hdr
{
u_char icmp_type;
/* */
u_char icmp_code;
/* */
u_short icmp_cksum;
/* */
u_short icmp_id;
/* */
u_short icmp_seq;
/* */
char icmp_data[1];
/* */
} ICMP_HDR, *PICMPHDR, FAR *LPICMPHDR;
#define ICMP_HDR_LEN sizeof(ICMP_HDR)
/* IP 4 RFC 791 */
#define IPVERSION 4
typedef struct ip_hdr {
u_char ip_hl;
/* */
u_char ip_v;
/* */
u_char ip_tos;
/* */
short ip_len;
/* */
u_short ip_id;
/* */
short ip_off;
/* */
u_char ip_ttl;
/* TTL */
u_char ip_p;
/* */
u_short ip_cksum;
/* . */
struct in_addr ip_src;
/* */
struct in_addr ip_dst;
/* */
} IP_HDR, *PIP_HDR, *LPIP_HDR;
#define IP_HDR_LEN sizeof(IP_HDR)
#define PNGBUFSIZE 8192+ICMP_HDR_LEN+IP_HDR_LEN
/* */
extern void WSAErrMsg(LPSTR);
/* private */

static
static
static
static
static
/*

ICMP_HDR FAR lpIcmpHdr; /* I/O */


IP_HDR FAR *lpIpHdr;
char achIOBuf[PNGBUFSIZE];
SOCKADDR_IN stFromAddr;
DWORD lCurrentTime, lRoundTripTime;
Function icmp_open()
: "" ICMP . */
SOCKET icmp_open(void) {
SOCKET s;
s = socket (AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (s == SOCKET_ERROR) {
WSAErrMsg("socket(type=SOCK_RAW, protocol=IPROTO_ICMP) ");
return (INVALID_SOCKET);
}
return (s);
} /* icmp_open() */
/* Function: icmp_sendto()
: ICMP-, ICMP
, ICMP - . */
int icmp_sendto (SOCKET s,
HWND hwnd,
LPSOCKADDR_IN lpstToAddr,
int nIcmpId,
int nIcmpSeq,
int nEchoDataLen) {
int nAddrLen = sizeof(SOCKADDR_IN);
int nRet;
u_short i;
char c;
/*--------------------- ICMP- -----------------------*/
lpIcmpHdr = (ICMP_HDR FAR *)achIOBuf;
lpIcmpHdr->icmp_type = ICMP_ECHOREQ;
lpIcmpHdr->icmp_code = 0;
lpIcmpHdr->icmp_cksum = 0;
lpIcmpHdr->icmp_id
= nIcmpId++;
lpIcmpHdr->icmp_seq
= nIcmpSeq++;
/*-------------------- ----------------------- ,
- */
lCurrentTime = GetCurrentTime();
_fmemcpy (&(achIOBuf[ICMP_HDR_LEN]),&lCurrentTime,sizeof(long));
/* ( icmp-) */
c=" ";
/* : , */
for (i=ICMP_HDR_LEN+sizeof(long);
((i < (nEchoDataLen+ICMP_HDR_LEN)) && (i < PNGBUFSIZE));i++) {
achIOBuf[i] = c;
c++;
if (c > "~") /* ASCII 126, 32 */
c= " ";
}
/*---------------------- ICMP --------------------- ICMP ICMP- , 0 */
lpIcmpHdr->icmp_cksum =
cksum((u_short FAR *)lpIcmpHdr, nEchoDataLen+ICMP_HDR_LEN);
/*--------------------- ICMP -------------------*/
nRet = sendto (s,
/* */
(LPSTR)lpIcmpHdr,
/* */
nEchoDataLen+ICMP_HDR_LEN+sizeof(long),
/* */
0,
/* */
(LPSOCKADDR)lpstToAddr,
/* */

sizeof(SOCKADDR_IN));
/* */
if (nRet == SOCKET_ERROR) {
WSAErrMsg("sendto()");
}
return (nRet);
} /* icmp_sendto() */
/* Function: icmp_recvfrom()
: icmp -,
ICMP . */
u_long icmp_recvfrom(SOCKET s, LPINT lpnIcmpId, LPINT lpnIcmpSeq, LPSOCKADDR_IN lpstFromAddr)
{
u_long lSendTime;
int nAddrLen = sizeof(struct sockaddr_in);
int nRet, i;
/*-------------------- ICMP - ------------------*/
stFromAddr.sin_family = AF_INET;
stFromAddr.sin_addr.s_addr = INADDR_ANY;
stFromAddr.sin_port = 0;
nRet = recvfrom (s,
/* */
(LPSTR)achIOBuf,
/* */
PNGBUFSIZE+ICMP_HDR_LEN+sizeof(long)+IP_HDR_LEN,
/* */
0,
/* */
(LPSOCKADDR)lpstFromAddr,
/* */
&nAddrLen);
/* */
if (nRet == SOCKET_ERROR) {
WSAErrMsg("recvfrom()");
}
/*------------------------- -------------------------- . : ,
Berkeley Sockets. , IP-,
. ,
, IP- ( 0x45 ). */
/* */
if (achIOBuf[0] == 0x45) { /* IP- ? */
i = IP_HDR_LEN + ICMP_HDR_LEN;
lpIcmpHdr = (LPICMPHDR) &(achIOBuf[IP_HDR_LEN]);
} else {
i = ICMP_HDR_LEN;
lpIcmpHdr = (LPICMPHDR) achIOBuf;
}
/* ICMP ID */
*lpnIcmpId = lpIcmpHdr->icmp_id;
*lpnIcmpSeq = lpIcmpHdr->icmp_seq;
/* ICMP- */
_fmemcpy (&lSendTime, (&achIOBuf[i]), sizeof(u_long));
return (lSendTime);
} /* end icmp_recvfrom() */
/* Function: cksum()

(one's complement sum of 16-bit words). IP, ICMP, UDP, IGMP. */
u_short cksum (u_short FAR*lpBuf, int nLen) {
register long lSum = 0L; /* */
/* : , ()
0 */
while (nLen > 0) {
lSum += (lpBuf++);
/* */
nLen -= 2;
/* 2 */
}
/* 32-bit 16-bit */
lSum = (lSum & 0xffff) + (lSum>>16);

lSum += (lSum >> 16);


/* .*/
return (~lSum);
} /* cksum() */

4
Log- 3- Internet-
Packet #1, Direction: Out, Time:20:55:56,780

MAC- DNS

Ethernet II

Destination MAC: FF:FF:FF:FF:FF:FF
,,
Source MAC: 44:45:53:54:00:00
MAC
Ethertype: 0x0806 (2054)
2054 (ARP)
ARP
Hardware: 0x0001 (1) Ethernet

Protocol: 0x0800 (2048) IP
IP
Hardware address length: 0x06 (6)
6
Protocol address length: 0x04 (4)
4
Operation: 0x0001 (1) ARP Request
ARP-
Sender MAC address: 44:45:53:54:00:00
MAC
Sender IP address: 195.216.161.32
IP-
Target MAC address: 00:00:00:00:00:00
MAC-
Target IP address: 195.216.160.130
IP-
Raw Data:
0x0000
FF FF FF FF FF FF 44 45-53 54 00 00 08 06 00 01
DEST......
0x0010
08 00 06 04 00 01 44 45-53 54 00 00 C3 D8 A1 20
......DEST..
0x0020
00 00 00 00 00 00 C3 D8-A0 82
......

Packet #2, Direction: Out, Time:20:55:56,780


Ethernet II
Destination MAC: 20:53:52:43:00:00
Source MAC: 44:45:53:54:00:00
Ethertype: 0x0800 (2048) IP
IP
IP version: 0x04 (4)
Header length: 0x05 (5) 20 bytes
Type of service: 0x00 (0)
Precedence: 000 Routine
Delay: 0 Normal delay
Throughput: 0 Normal throughput
Reliability: 0 Normal reliability
Total length: 0x003A (58)
ID: 0xF900 (63744)
Flags
Don't fragment bit: 0 May fragment
More fragments bit: 0 Last fragment
Fragment offset: 0x0000 (0)
Time to live: 0x80 (128)
Protocol: 0x11 (17) UDP
Checksum: 0x785E (30814) correct
Source IP: 195.216.161.32
Destination IP: 195.216.160.130
IP Options: None
UDP
Source port: 1055
Destination port: 53
Length: 0x0026 (38)
Checksum: 0x5648 (22088) correct
DNS
ID: 0x0009 (9)
Response packet: 0

DNS

Mac-
MAC
2048 (IP)
IP-
IP- 4
20
TOS 0




58
63744

DF 0
MF 0
0
IP TTL 128
UDP

IP
IP DNS

UDP
1055
DNS-53
UDP-

DNS-

Operation code: 0x00 (0) Standard query


Flags
Authoritative Answer: 0
Truncation: 0
Recursion Desired: 1
Recursion Available: 0
Result code: 0x00 (0) Success
Question records: 0x0001 (1)
Answer records: 0x0000 (0)
Authority records: 0x0000 (0)
Additional records: 0x0000 (0)
Question section
Record: 0x1 (1)
Name: www.aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
Raw Data:
0x0000
20
0x0010
00
0x0020
A0
0x0030
00
0x0040
02

53
3A
82
00
72

52
F9
04
00
75

43
00
1F
00
00

00
00
00
00
00

00
00
35
00
01

44
80
00
03
00

45-53
11-78
26-56
77-77
01-

54
5E
48
77

00
C3
00
05

00
D8
09
61

08
A1
01
70

00
20
00
6F





1
www.aport.ru


45
C3
00
72

Packet #3, Direction: In, Time:20:55:56,950


Ethernet II
Destination MAC: 44:45:53:54:00:00
Source MAC: 20:53:52:43:00:00
Ethertype: 0x0800 (2048) IP
IP
IP version: 0x04 (4)
Header length: 0x05 (5) 20 bytes
Type of service: 0x00 (0)
Precedence: 000 Routine
Delay: 0 Normal delay
Throughput: 0 Normal throughput
Reliability: 0 Normal reliability
Total length: 0x00C6 (198)
ID: 0x38A2 (14498)
Flags
Don't fragment bit: 0 May fragment
More fragments bit: 0 Last fragment
Fragment offset: 0x0000 (0)
Time to live: 0x3E (62)
Protocol: 0x11 (17) UDP
Checksum: 0x7A31 (31281) correct
Source IP: 195.216.160.130
Destination IP: 195.216.161.32
IP Options: None
UDP
Source port: 53
Destination port: 1055
Length: 0x00B2 (178)
Checksum: 0x7C3F (31807) correct
DNS
ID: 0x0009 (9)
Response packet: 1
Operation code: 0x00 (0) Standard query
Flags
Authoritative Answer: 0
Truncation: 0
Recursion Desired: 1
Recursion Available: 1
Result code: 0x00 (0) Success
Question records: 0x0001 (1)
Answer records: 0x0002 (2)

00
D8
01
74

SRC..DEST....E.
.:....x^
...5.&VH......
.......www.aport
.ru.....

DNS

Authority records: 0x0003 (3)


Additional records: 0x0003 (3)
Question section
Record: 0x1 (1)
Name: www.aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
Answer section
Record: 0x1 (1)

Name: www.aport.ru
Type: 0x0005 (5) CNAME
Class: 0x0001 (1) IN
TTL: 1534 25 Minutes 34 sec
CNAME: aport.ru
Record: 0x2 (2)
Name: aport.ru
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 1534 25 Minutes 34 sec
IP address: 194.67.26.89
Authority section
Record: 0x1 (1)
Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns1.gldn.net
Record: 0x2 (2)
Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns2.gldn.net

Record: 0x3 (3)


Name: aport.ru
Type: 0x0002 (2) NS
Class: 0x0001 (1) IN
TTL: 333 5 Minutes 33 sec
NSDNAME: ns3.gldn.net
Additional section
Record: 0x1 (1)
Name: ns1.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.2.108
Record: 0x2 (2)
Name: ns2.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.2.109
Record: 0x3 (3)
Name: ns3.gldn.net
Type: 0x0001 (1) A
Class: 0x0001 (1) IN
TTL: 146243 1 Day 16 Hours 37
Minutes 23 sec
IP address: 194.67.7.1

TTL DNS- cache


32 !

IP- www.aport.ru

. RFC 1034

Raw Data:
0x0000
44
0x0010
00
0x0020
A1
0x0030
00

45
C6
20
02

53
38
00
00

54
A2
35
03

00
00
04
00

00
00
1F
03

20
3E
00
03

53-52
11-7A
B2-7C
77-77

43
31
3F
77

00
C3
00
05

00
D8
09
61

08
A0
81
70

00
82
80
6F

45
C3
00
72

00
D8
01
74

DEST.. SRC....E.
.8...>.z1
.5...|?....
.......www.aport

5
( IANA)

1. ()

1
2
3
5
7
9
11
13
15
17
18
19
20
21
22
23
24
25
27
29
31
33
35
37
38
39
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

TCP-MUX - TCP Port Service Multiplexer


COMPRESSNET - Management Utility
COMPRESSNET - Compression Process
RJE - Remote Job Entry
ECHO - Echo
DISCARD - Discard
SYSSTAT - System Status
DAYTIME - Daytime
NETSTAT - Network Status
QOTD - Quote of the Day
MSP - Message Send Protocol
CHARGEN - Character Generator
FTP-DATA - File Transfer Protocol [Default Data]
FTP - File Transfer Protocol [Control]
SSH - SSH (Secure Shell) Remote Login Protocol
TELNET - Telnet
PMS - Private Mail System
SMTP - Simple Mail Transfer Protocol
NSW-FE - NSW User System FE
MSG-ICP - Messege ICP
MSG-AUTH - Messege Authentication
DSP - Display Support Protocol
PPS - Private Printer Server
TIME - Time
RAP - Route Access Protocol
RLP - Resource Location Protocol
GRAPHICS - Graphics
NAMESERVER - Host Name Server
WHOIS - Who Is
MPM-FLAGS - MPM FLAGS Protocol
MPM - Message Processing Module [recv]
MPM-SND - MPM [default send]
NI-FTP - NI FTP (File Transfer Protocol)
AUDITD - Digital Audit Daemon
BBN-LOGIN - Login Host Protocol (TACACS)
RE-MAIL-CK - Remote Mail Checking Protocol
LA-MAINT - IMP Logical Address Maintenance
XNS-TIME - XNS Time Protocol
DOMAIN - Domain Name Server
XNS-CH - XNS Clearinghouse
ISI-GL - ISI Graphics Language
XNS-AUTH - XNS Authentication
MTP - Private terminal access

58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

XNS-MAIL - XNS Mail


PFS - Private File System
Unassigned
NI-MAIL - NI MAIL
ACAS - ACA Services
WHOIS++ - whois++
COVIA - Communications Integrator (CI)
TACACS-DS - TACACS-Database Service
SQL*NET - Oracle SQL*NET
BOOTPS - Bootstrap Protocol Server
BOOTPC - Bootstrap Protocol Client
TFTP - Trivial File Transfer Protocol
GOPHER - Gopher
NETRJS-1 - Remote Job Service
NETRJS-2 - Remote Job Service
NETRJS-3 - Remote Job Service
NETRJS-4 - Remote Job Service
PDOS - Private dial out service
DEOS - Distributed External Object Store
RJE - Private RJE (Remote Job Entry) service
VETTCP - vettcp
FINGER - Finger
WWW-HTTP - World Wide Web HTTP (Hyper Text Transfer Protocol)
HOSTS2-NS - HOSTS2 Name Server
XFER - XFER Utility
MIT-ML-DEV - MIT ML Device
CTF - Common Trace Facility
MIT-ML-DEV - MIT ML Device
MFCOBOL - Micro Focus Cobol
LINK - Private terminal link
KERBEROS - Kerberos
SU-MIT-TG - SU/MIT Telnet Gateway
DNSIX - DNSIX Securit Attribute Token Map
MIT-DOV - MIT Dover Spooler
NPP - Network Printing Protocol
DCP - Device Control Protocol
OBJCALL - Tivoli Object Dispatcher
SUPDUP - SUPDUP
DIXIE - DIXIE Protocol Specification
SWIFT-RVF - Swift Remote Virtural File Protocol
TACNEWS - TAC News
METAGRAM - Metagram Relay
NEWACCT - [unauthorized use]
HOSTNAMES - NIC Host Name Server
ISO-TSAP - ISO-TSAP Class 0
X400 - x400
X400-SND - x400-snd
CSNET-NS - Mailbox Name Nameserver
3COM-TSMUX - 3COM-TSMUX
RTELNET - Remote Telnet Service
SNAGAS - SNA Gateway Access Server
POP - Post Office Protocol - Version 2
POP3 - Post Office Protocol - Version 3
SUNRPC - SUN Remote Procedure Call
MCIDAS - McIDAS Data Transmission Protocol
IDENT - Authentication Service
AUDIONEWS - Audio News Multicast
SFTP - Simple File Transfer Protocol
ANSANOTIFY - ANSA REX Notify
UUCP-PATH - UUCP Path Service

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177

SQLSERV - SQL Services


NNTP - Network News Transfer Protocol
CFDPTKT - CFDPTKT
ERPC - Encore Expedited Remote Pro.Call
SMAKYNET - SMAKYNET
NTP - Network Time Protocol
ANSATRADER - ANSA REX Trader
LOCUS-MAP - Locus PC-Interface Net Map Ser
UNITARY - Unisys Unitary Login
LOCUS-CON - Locus PC-Interface Conn Server
GSS-XLICEN - GSS X License Verification
PWDGEN - Password Generator Protocol
CISCO-FNA - cisco FNATIVE
CISCO-TNA - cisco TNATIVE
CISCO-SYS - cisco SYSMAINT
STATSRV - Statistics Service
INGRES-NET - INGRES-NET Service
RPC-LOCATOR - RPC (Remote Procedure Call) Location Service
PROFILE - PROFILE Naming System
NETBIOS-NS - NETBIOS Name Service
NETBIOS-DGM - NETBIOS Datagram Service
NETBIOS-SSN - NETBIOS Session Service
EMFIS-DATA - EMFIS Data Service
EMFIS-CNTL - EMFIS Control Service
BL-IDM - Britton-Lee IDM
IMAP - Interim Mail Access Protocol v2
NEWS - NewS
UAAC - UAAC Protocol
ISO-TP0 - ISO-IP0
ISO-IP - ISO-IP
CRONUS - CRONUS-SUPPORT
AED-512 - AED 512 Emulation Service
SQL-NET - SQL-NET
HEMS - HEMS
BFTP - Background File Transfer Program
SGMP - SGMP
NETSC-PROD - NETSC
NETSC-DEV - NETSC
SQLSRV - SQL Service
KNET-CMP - KNET/VM Command/Message Protocol
PCMAIL-SRV - PCMail Server
NSS-ROUTING - NSS-Routing
SGMP-TRAPS - SGMP-TRAPS
SNMP - SNMP (Simple Network Management Protocol)
SNMPTRAP - SNMPTRAP (Simple Network Management Protocol)
CMIP-MAN - CMIP/TCP Manager
CMIP-AGENT - CMIP/TCP Agent
XNS-COURIER - Xerox
S-NET - Sirius Systems
NAMP - NAMP
RSVD - RSVD
SEND - SEND
PRINT-SRV - Network PostScript
MULTIPLEX - Network Innovations Multiplex
CL/1 - Network Innovations CL/1
XYPLEX-MUX - Xyplex
MAILQ - MAILQ
VMNET - VMNET
GENRAD-MUX - GENRAD-MUX
XDMCP - X Display Manager Control Protocol

178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
242
243
244
245
246
247
248
256
257
258
259
260
261
262

NEXTSTEP - NextStep Window Server


BGP - Border Gateway Protocol
RIS - Intergraph
UNIFY - Unify
AUDIT - Unisys Audit SITP
OCBINDER - OCBinder
OCSERVER - OCServer
REMOTE-KIS - Remote-KIS
KIS - KIS Protocol
ACI - Application Communication Interface
MUMPS - Plus Five's MUMPS
QFT - Queued File Transport
GACP - Gateway Access Control Protocol
PROSPERO - Prospero Directory Service
OSU-NMS - OSU Network Monitoring System
SRMP - Spider Remote Monitoring Protocol
IRC - Internet Relay Chat Protocol
DN6-NLM-AUD - DNSIX Network Level Module Audit
DN6-SMM-RED - DNSIX Session Mgt Module Audit Redir
DLS - Directory Location Service
DLS-MON - Directory Location Service Monitor
SMUX - SMUX
SRC - IBM System Resource Controller
AT-RTMP - AppleTalk Routing Maintenance
AT-NBP - AppleTalk Name Binding
AT-3 - AppleTalk Unused
AT-ECHO - AppleTalk Echo
AT-5 - AppleTalk Unused
AT-ZIS - AppleTalk Zone Information
AT-7 - AppleTalk Unused
AT-8 - AppleTalk Unused
QMTP - The Quick Mail Transfer Protocol
Z39.50 - ANSI Z39.50
914C/G - Texas Instruments 914C/G Terminal
ANET - ATEXSSTR
IPX - IPX
VMPWSCS - VM PWSCS
SOFTPC - Insignia Solutions
CAILIC - Computer Associates Int'l License Server
DBASE - dBASE Unix
MPP - Netix Message Posting Protocol
UARPS - Unisys ARPs
IMAP3 - Interactive Mail Access Protocol v3
FLN-SPX - Berkeley rlogind with SPX auth
RSH-SPX - Berkeley rshd with SPX auth
CDC - Certificate Distribution Center
DIRECT
SUR-MEAS - Survey Measurement
DAYNA
LINK - LINK
DSP3270 - Display Systems Protocol
SUBNTBCST_TFTP
BHFHS
RAP
SET - Secure Electronic Transaction
YAK-CHAT - Yak Winsock Personal Chat
ESRO-GEN - Efficient Short Remote Operations
OPENPORT
NSIIOPS - IIOP Name Service Over TLS/SSL
ARCISDMS

263
264
280
281
282
308
309
310
311
312
313
314
315
316
317
321
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
387
388

HDAP
BGMP
HTTP-MGMT
PERSONAL-LINK
CABLEPORT-AX - Cable Port A/X
NOVASTORBAKCUP - Novastor Backup
ENTRUSTTIME
BHMDS
ASIP-WEBADMIN - Appleshare IP Webadmin
VSLMP
MAGENTA-LOGIC
OPALIS-ROBOT
DPSI
DECAUTH
ZANNET
PIP
PDAP - Prospero Data Access Protocol
PAWSERV - Perf Analysis Workbench
ZSERV - Zebra server
FATSERV - Fatmen Server
CSI-SGWP - Cabletron Management Protocol
MFTP
MATIP-TYPE-A - MATIP Type A
MATIP-TYPE-B - MATIP Type B or bhoetty
DTAG-STE-SB - DTAG, or bhoedap4
NDSAUTH
BH611
DATEX-ASN
CLOANTO-NET-1 - Cloanto Net 1
BHEVENT
SHRINKWRAP
TENEBRIS_NTS - Tenebris Network Trace Service
SCOI2ODIALOG
SEMANTIX
SRSSEND - SRS Send
RSVP_TUNNEL
AURORA-CMGR
DTK - Deception Tool Kit
ODMR
MORTGAGEWARE
QBIKGDP
RPC2PORTMAP
CODAAUTH2
CLEARCASE - Clearcase
ULISTSERV - Unix Listserv
LEGENT-1 - Legent Corporation
LEGENT-2 - Legent Corporation
HASSLE - Hassle
NIP - Amiga Envoy Network Inquiry Proto
TNETOS - NEC Corporation
DSETOS - NEC Corporation
IS99C - TIA/EIA/IS-99 modem client
IS99S - TIA/EIA/IS-99 modem server
HP-COLLECTOR - HP Performance Data Collector
HP-MANAGED-NODE - HP Performance Data Managed Node
HP-ALARM-MGR - HP Performance Data Alarm Manager
ARNS - A Remote Network Server System
IBM-APP - IBM Application 386 ASA - ASA Message Router Object Def.
AURP - Appletalk Update-Based Routing Pro.
UNIDATA-LDM - Unidata LDM Version 4

389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448

LDAP - Lightweight Directory Access Protocol


UIS - UIS
SYNOTICS-RELAY - SynOptics SNMP Relay Port
SYNOTICS-BROKER - SynOptics Port Broker Port
DIS - Data Interpretation System
EMBL-NDT - EMBL Nucleic Data Transfer
NETCP - NETscout Control Protocol
NETWARE-IP - Novell Netware over IP
MPTN - Multi Protocol Trans. Net.
KRYPTOLAN - Kryptolan
ISO-TSAP-C2 - ISO Transport Class 2 Non-Control over TCP
WORK-SOL - Workstation Solutions
UPS - Uninterruptible Power Supply
GENIE - Genie Protocol
DECAP - decap
NCED - nced
NCLD - ncld
IMSP - Interactive Mail Support Protocol
TIMBUKTU - Timbuktu
PRM-SM - Prospero Resource Manager Sys. Man.
PRM-NM - Prospero Resource Manager Node Man.
DECLADEBUG - DECLadebug Remote Debug Protocol
RMT - Remote MT Protocol
SYNOPTICS-TRAP - Trap Convention Port
SMSP - SMSP
INFOSEEK - InfoSeek
BNET - BNet
SILVERPLATTER - Silverplatter
ONMUX - Onmux
HYPER-G - Hyper-G
ARIEL1 - Ariel
SMPTE - SMPTE
ARIEL2 - Ariel
ARIEL3 - Ariel
OPC-JOB-START - IBM Operations Planning and Control Start
OPC-JOB-TRACK - IBM Operations Planning and Control Track
ICAD-EL - ICAD
SMARTSDP - smartsdp
SVRLOC - Server Location
OCS_CMU - OCS_CMU
OCS_AMU - OCS_AMU
UTMPSD - UTMPSD
UTMPCD - UTMPCD
IASD - IASD
NNSP - NNSP
MOBILEIP-AGENT - MobileIP-Agent
MOBILIP-MN - MobilIP-MN
DNA-CML - DNA-CML
COMSCM - comscm
DSFGW - dsfgw
DASP - dasp
SGCP - sgcp
DECVMS-SYSMGT - decvms-sysmgt
CVC_HOSTD - cvc_hostd
HTTPS - HTTPS (Hyper Text Transfer Protocol Secure) - SSL (SecureSocket Layer)
SNPP - Simple Network Paging Protocol
MICROSOFT-DS - Microsoft-DS
DDM-RDB - DDM-RDB
DDM-DFM - DDM-RFM
DDM-BYTE - DDM-BYTE

449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508

AS-SERVERMAP - AS Server Mapper


TSERVER - TServer
SFS-SMP-NET - Cray Network Semaphore server
SFS-CONFIG - Cray SFS config server
CREATIVESERVER - CreativeServer
CONTENTSERVER - ContentServer
CREATIVEPARTNR - CreativePartnr
MACON-TCP - macon-tcp
SCOHELP - scohelp
APPLEQTC - Apple Quick Time
AMPR-RCMD - ampr-rcmd
SKRONK - skronk
DATASURFSRV - DataRampSrv
DATASURFSRVSEC - DataRampSrvSec
ALPES - alpes
KPASSWD - kpasswd
SSMTP - ssmtp
DIGITAL-VRC - digital-vrc
MYLEX-MAPD - mylex-mapd
PHOTURIS - proturis
RCP - Radio Control Protocol
SCX-PROXY - scx-proxy
MONDEX - Mondex
LJK-LOGIN - ljk-login
HYBRID-POP - hybrid-pop
TN-TL-W1 - tn-tl-w1
TCPNETHASPSRV - tcpnethaspsrv
TN-TL-FD1 - tn-tl-fd1
SS7NS - ss7ns
SPSC - spsc
IAFSERVER - iafserver
IAFDBASE - iafdbase
PH - Ph service
BGS-NSI - bgs-nsi
ULPNET - ulpnet
INTEGRA-SME - Integra Software Management Environment
POWERBURST - Air Soft Power Burst
AVIAN - avian
SAFT - saft
GSS-HTTP - gss-http
NEST-PROTOCOL - nest-protocol
MICOM-PFS - micom-pfs
GO-LOGIN - go-login
TICF-1 - Transport Independent Convergence for FNA
TICF-2 - Transport Independent Convergence for FNA
POV-RAY - POV-Ray
INTECOURIER
PIM-RP-DISC
DANTZ
SIAM
ISO-ILL - ISO ILL Protocol
ISAKMP
STMF
ASA-APPL-PROTO
INTRINSA
CITADEL
MAILBOX-LM
OHIMSRV
CRS
XVTTP

509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568

SNARE
FCP - FirstClass Protocol
PASSGO EXEC - Remote Process Execution
LOGIN - Remote Login via Telnet;
SHELL - Automatic Remote Process Execution
PRINTER - Printer Spooler
VIDEOTEX
TALK
NTALK
UTIME - Unix Time
EFS - Extended File Server
RIPNG
ULP
IBM-DB2
NCP
TIMED - Time Server
TEMPO - newdate
STX - Stock IXChange
CUSTIX - Customer IXChange
IRC-SERV
COURIER - rpc
CONFERENCE - chat
NETNEWS - readnews
NETWALL - Emergency Broadcasts
MM-ADMIN - MegaMedia Admin
IIOP
OPALIS-RDV
NMSP - Networked Media Streaming Protocol
GDOMAP
APERTUS-LDP - Apertus Technologies Load Determination
UUCP - UUCPD (Unix to Unix Copy)
UUCP-RLOGIN - uucp (Unix to Unix Copy) - rlogin (Remote Login)
COMMERCE
KLOGIN
KSHELL - krcmd
APPLEQTCSRVR - Apple qtcsrvr
DHCP-CLIENT - DHCP (Dynamic Host Configuration Protocol) Client
DHCP-SERVER - DHCP (Dynamic Host Configuration Protocol) Server
AFPOVERTCP - AFP over TCP
IDFP
NEW-RWHO - new-who
CYBERCASH - CyberCash
DEVICESHARE - deviceshare
PIRP - pirp
RTSP - Real Time Stream Control Protocol
DSF
REMOTEFS - rfs (Remote File System) server
OPENVMS-SYSIPC - openvms-sysipc
SDNSKMP - SDNSKMP
TEEDTAP - TEEDTAP
RMONITOR - rmonitord
MONITOR
CHSHELL - chcmd
SNEWS - snews
9PFS - plan 9 file service
WHOAMI - whoami
STREETTALK - streettalk
BANYAN-RPC - banyan-rpc
MS-SHUTTLE - Microsoft Shuttle

569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
606
607
608
609
610
611
628
633
634
635
636
640
650
666
674
704
709
729
730
731
737
740
741
742
744
747
748
749

MS-ROME - Microsoft Rome


METER - demon
METER - udemon
SONAR - sonar
BANYAN-VIP - banyan-vip
FTP-AGENT - FTP Software Agent System
VEMMI - VEMMI
IPCD
VNAS
IPDD
DECBSRV
SNTP-HEARTBEAT BDP - Bundle Discovery Protocol
SCC-SECURITY
PHILIPS-VC - PHilips Video-Conferencing
KEYSERVER
IMAP4-SSL - IMAP4+SSL
PASSWORD-CHG
SUBMISSION
CAL
EYELINK
TNS-CML
HTTP-ALT - FileMaker, Inc. - HTTP Alternate
EUDORA-SET HTTP-RPC-EPMAP - HTTP RPC Ep Map
TPIP CAB-PROTOCOL SMSD PTCNAMESERVICE - PTC Name Service
SCO-WEBSRVRMG3 - SCO Web Server Manager 3
ACP - Aeolon Core Protocol
IPCSERVER - Sun IPC server
URM - Cray Unified Resource Manager
NQS - nqs
SIFT-UFT - Sender-Initiated/Unsolicited File Transfer
NPMP-TRAP - npmp-trap
NPMP-LOCAL - npmp-local
NPMP-GUI - npmp-gui
QMQP - Qmail Quick Mail Queueing
SERVSTAT - Service Status update (Sterling Software)
GINAD - ginad
MOUNT - NFS Mount Service
LDAPSSL - LDAP Over SSL
PCNFS - PC-NFS DOS Authentication
BWNFS - BW-NFS DOS Authentication
DOOM - doom Id Software
PORT
ELCSD - errlog copy/server daemon
ENTRUSTMANAGER - EntrustManager
NETVIEWDM1 - IBM NetView DM/6000 Server/Client
NETVIEWDM2 - IBM NetView DM/6000 send/tcp
NETVIEWDM3 - IBM NetView DM/6000 receive/tcp
SOMETIMES-RPC2 - Rusersd on my OpenBSD Box
NETCP - NETscout Control Protocol
NETGW - netGW
NETRCS - Network based Rev. Cont. Sys.
FLEXLM - Flexible License Manager
FUJITSU-DEV - Fujitsu Device Control
RIS-CM - Russell Info Sci Calendar Manager
KERBEROS-ADM - kerberos administration

750
751
752
753
754
758
759
760
761
762
763
764
765
767
769
770
771
772
773
774
775
776
780
781
782
783
786
799
800
801
808
871
888
901
911
989
990
992
993
995
996
997
998
999
1000
1001
1008
1010
1011
1012
1015
1023

KERBEROS-SEC
KERBEROS_MASTER
QRH
RRH
KBR5_PROP
NLOGIN
CON
NS
RXE
QUOTAD
CYCLESERV
OMSERV
WEBSTER
PHONEBOOK - phone
VID
CADLOCK
RTIP
CYCLESERV2
SUBMIT
RPASSWD
ENTOMB
WPAGES
WPGS
HP-COLLECTOR - HP Performance Data Collector
HP-MANAGED-NODE - HP Performance Data Managed Node
HP-ALARM-MGR - HP Performance Data Alarm Manager
CONCERT - Concert
CONTROLIT
MDBS_DAEMON
DEVICE
PORT
SUPFILESRV -SUP Server
CDDATABASE - CDDataBase
PORT
Dark Shadow
FTPS-DATA - FTP Over TLS/SSL
FTP Control TLS/SSL
TELNETS - telnet protocol over TLS/SSL
IMAPS - Imap4 protocol over TLS/SSL
POP3S - Pop3 (Post Office Protocol) over TLS/SSL
VSINET - vsinet
MAITRD
BUSBOY
PUPROUTER
CADLOCK
Silence
UFSD - UFSD
Doly-Trojan
Doly-Trojan
Doly-Trojan
Doly-Trojan
RESERVED Reserved

2.

1024
OLD_FINGER - old_finger
1025
LISTEN - listen
1026
NTERM - nterm
1027
NT
1028
NT

1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1058
1059
1067
1068
1080
1083
1084
1090
1103
1109
1110
1112
1127
1155
1167
1170
1178
1212
1222
1234
1241
1243
1245
1248
1269
1330
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358

NT
IAD1 - BBN IAD
IAD2 - BBN IAD
IAD3 - BBN IAD
NT
NT
NT
NT
NT
NT
NT
NT
NT
Bla
NT
NT
Rasmin
NT
NT
NT
NT
NIM - nim
NIMREG - nimreg
INSTL_BOOTS - Installation Bootstrap Proto. Serv.
INSTL_BOOTC - Installation Bootstrap Proto. Cli.
SOCKS - Socks
ANSOFT-LM-1 - Anasoft License Manager
ANSOFT-LM-2 - Anasoft License Manager
Xtreme
XAUDIO - Xaserver
KPOP - kpop
NFSD-STATUS - Cluster Status Info
MSQL - Mini-SQL Server
SUPFILEDBG - SUP Debugging
NFA - Network File Access
PHONE - Conference Calling
Psyber Stream Server, Streaming Audio trojan, Voice
SKKSERV - SKK (Kanji Input)
LUPA - lupa
NERV - SNI R&D network
Ultors Trojan
MSG - Remote Message Server
BackDoor-G, SubSeven, SubSeven Apocalypse
Voodoo Doll
HERMES - Multi Media Conferencing
Mavericks Matrix
PORT
ALTA-ANA-LM - Alta Analytics License Manager
BBN-MMC - Multi Media Conferencing
BBN-MMX - Multi Media Conferencing
SBOOK - Registration Network Protocol
EDITBENCH - Registration Network Protocol
EQUATIONBUILDER - Digital Tool Works (MIT)
LOTUSNOTE - Lotus Note
RELIEF - Relief Consulting
RIGHTBRAIN - RightBrain Software
INTUITIVE EDGE - Intuitive Edge
CUILLAMARTIN - CuillaMartin Company
PEGBOARD - Electronic PegBoard
CONNLCLI - CONNLCLI

1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418

FTSRV - FTSRV
MIMER - MIMER
LINX - LinX
TIMEFLIES - TimeFlies
NDM-REQUESTER - Network DataMover Requester
NDM-SERVER - Network DataMover Server
ADAPT-SNA - Network Software Associates
NETWARE-CSP - Novell NetWare Comm Service Platform
DCS - DCS
SCREENCAST - ScreenCast
GV-US - GlobalView to Unix Shell
US-GV - Unix Shell to GlobalView
FC-CLI - Fujitsu Config Protocol
FC-SER - Fujitsu Config Protocol
CHROMAGRAFX - Chromagrafx
MOLLY - EPI Software Systems
BYTEX - Bytex
IBM-PPS - IBM Person to Person Software
CICHLID - Cichlid License Manager
ELAN - Elan License Manager
DBREPORTER - Integrity Solutions
TELESIS-LICMAN - Telesis Network License Manager
APPLE-LICMAN - Apple Network License Manager
UDT_OS GWHA - GW Hannaway Network License Manager
OS-LICMAN - Objective Solutions License Manager
ATEX_ELMD - Atex Publishing License Manager
CHECKSUM - CheckSum License Manager
CADSI-LM - Computer Aided Design Software Inc LM
OBJECTIVE-DBC - Objective Solutions DataBase Cache
ICLPV-DM - Document Manager
ICLPV-SC - Storage Controller
ICLPV-SAS - Storage Access Server
ICLPV-PM - Print Manager
ICLPV-NLS - Network Log Server
ICLPV-NLC - Network Log Client
ICLPV-WSM - PC Workstation Manager software
DVL-ACTIVEMAIL - DVL Active Mail
AUDIO-ACTIVMAIL - Audio Active Mail
VIDEO-ACTIVMAIL - Video Active Mail
CADKEY-LICMAN - Cadkey License Manager
CADKEY-TABLET - Cadkey Tablet Daemon
GOLDLEAF-LICMAN - Goldleaf License Manager
PRM-SM-NP - Prospero Resource Manager
PRM-NM-NP - Prospero Resource Manager
IGI-LM - Infinite Graphics License Manager
IBM-RES - IBM Remote Execution Starter
NETLABS-LM - NetLabs License Manager
DBSA-LM - DBSA License Manager
SOPHIA-LM - Sophia License Manager
HERE-LM - Here License Manager
HIQ - HiQ License Manager
AF - AudioFile
INNOSYS - InnoSys
INNOSYS-ACL - Innosys-ACL
IBM-MQSERIES - IBM MQSeries
DBSTAR - DBStar
NOVELL-LU6.2 - Novell LU6.2
TIMBUKTU-SRV1 - Timbuktu Service 1 Port
TIMBUKTU-SRV2 - Timbuktu Service 2 Port

1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478

TIMBUKTU-SRV3 - Timbuktu Service 3 Port


TIMBUKTU-SRV4 - Timbuktu Service 4 Port
GANDALF-LM - Gandalf License Manager
AUTODESK-LM - Autodesk License Manager
ESSBASE - Essbase Arbor Software
HYBRID - Hybrid Encryption Protocol
ZION-LM - Zion Software License Manager
SAIS - Satellite-data Acquisition System 1
MLOADD - mloadd monitoring tool
INFORMATIK-LM - Informatik License Manager
NMS - Hypercom NMS
TPDU - Hypercom TPDU
RGTP - Reverse Gossip Transport
BLUEBERRY-LM - Blueberry Software License Manager
MS-SQL-S - Microsoft-SQL-Server
MS-SQL-M - Microsoft-SQL-Monitor
IBM-CICS - IBM CICS
SAISM - Satellite-data Acquisition System 2
TABULA - Tabula
EICON-SERVER - Eicon Security Agent/Server
EICON-X25 - Eicon X25/SNA Gateway
EICON-SLP - Eicon Service Location Protocol
CADIS-1 - Cadis License Management
CADIS-2 - Cadis License Management
IES-LM - Integrated Engineering Software
MARCAM-LM - Marcam License Management
PROXIMA-LM - Proxima License Manager
ORA-LM - Optical Research Associates License Manager
APRI-LM - Applied Parallel Research LM
OC-LM - OpenConnect License Manager
PEPORT - PEport
DWF - Tandem Distributed Workbench Facility
INFOMAN - IBM Information Management
GTEGSC-LM - GTE Government Systems License Man
GENIE-LM - Genie License Manager
INTERHDL_ELMD - interHDL License Manager
ESL-LM - ESL License Manager
DCA - DCA
VALISYS-LM - Valisys License Manager
NRCABQ-LM - Nichols Research Corp.
PROSHARE1 - Proshare Notebook Application
PROSHARE2 - Proshare Notebook Application
IBM_WRLESS_LAN - IBM Wireless LAN
WORLD-LM - World License Manager
NUCLEUS - Nucleus
MSL_LMD - MSL License Manager
PIPES - Pipes Platform
OCEANSOFT-LM - Ocean Software License Manager
CSDMBASE - CSDMBASE
CSDM - CSDM
AAL-LM - Active Analysis Limited License Manager
UAIACT - Universal Analytics
CSDMBASE - csdmbase
CSDM - csdm
OPENMATH - OpenMath
TELEFINDER - Telefinder
TALIGENT-LM - Taligent License Manager
CLVM-CFG - clvm-cfg
MS-SNA-SERVER - ms-sna-server
MS-SNA-BASE - ms-sna-base

1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538

DBEREGISTER - dberegister
PACERFORUM - PacerForum
AIRS - AIRS
MITEKSYS-LM - Miteksys License Manager
AFS - AFS License Manager
CONFLUENT - Confluent License Manager
LANSOURCE - LANSource
NMS_TOPO_SERV - nms_topo_serv
LOCALINFOSRVR - LocalInfoSrvr
DOCSTOR - DocStor
DMDOCBROKER - dmdocbroker
INSITU-CONF - insitu-conf
ANYNETGATEWAY - anynetgateway
STONE-DESIGN-1 - stone-design-1
NETMAP_LM - netmap_lm
ICA - ica
CVC - cvc
LIBERTY-LM - liberty-lm
RFX-LM - rfx-lm
WATCOM-SQL - Watcom-SQL
FHC - Federico Heinz Consultora
VLSI-LM - VLSI License Manager
SAISCM - Satellite-data Acquisition System 3
SHIVADISCOVERY - Shiva
IMTC-MCS - Databeam
EVB-ELM - EVB Software Engineering License Manager
FUNKPROXY - Funk Software Inc.
UTCD - Universal Time daemon (utcd)
SYMPLEX - symplex
DIAGMOND - diagmond
ROBCAD-LM - Robcad Ltd. License Manager
MVX-LM - Midland Valley Exploration Ltd. Lic. Man.
3L-L1 - 3l-l1
WINS - Microsoft's Windows Internet Name Service
FUJITSU-DTC - Fujitsu Systems Business of America Inc
FUJITSU-DTCNS - Fujitsu Systems Business of America Inc
IFOR-PROTOCOL - ifor-protocol
VPAD - Virtual Places Audio data
VPAC - Virtual Places Audio control
VPVD - Virtual Places Video data
VPVC - Virtual Places Video control
ATM-ZIP-OFFICE - atm zip office
NCUBE-LM - nCube License Manager
RNA-LM - Ricardo North America License Manager
CICHILD-LM - cichild
INGRESLOCK - ingres
PROSPERO-NP - Prospero Directory Service non-priv
PDAP-NP - Prospero Data Access Prot non-priv
TLISRV - oracle
MCIAUTOREG - micautoreg
COAUTHOR - oracle
RAP-SERVICE - rap-service
RAP-LISTEN - rap-listen
MIROCONNECT - miroconnect
VIRTUAL-PLACES - Virtual Places Software
MICROMUSE-LM - micromuse-lm
AMPR-INFO - ampr-info
AMPR-INTER - ampr-inter
SDSC-LM - isi-lm
3DS-LM - 3ds-lm

1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598

INTELLISTOR-LM - Intellistor License Manager


RDS - rds
RDS2 - rds2
GRIDGEN-ELMD - gridgen-elmd
SIMBA-CS - simba-cs
ASPECLMD - aspeclmd
VISTIUM-SHARE - vistium-share
ABBACCURAY - abbaccuray
LAPLINK - laplink
AXON-LM - Axon License Manager
SHIVAHOSE - Shiva Hose
3M-IMAGE-LM - Image Storage license manager 3M Company
HECMTL-DB - HECMTL-DB
PCIARRAY - pciarray
SNA-CS - sna-cs
CACI-LM - CACI Products Company License Manager
LIVELAN - livelan
ASHWIN - AshWin CI Tecnologies
ARBORTEXT-LM - ArborText License Manager
XINGMPEG - xingmpeg
WEB2HOST - web2host
ASCI-VAL - asci-val
FACILITYVIEW - facilityview
PCONNECTMGR - pconnectmgr
CADABRA-LM - Cadabra License Manager
PAY-PER-VIEW - Pay-Per-View
WINDDLB - WinDD
CORELVIDEO - CORELVIDEO
JLICELMD - jlicelmd
TSSPMAP - tsspmap
ETS - ets
ORBIXD - orbixd
RDB-DBS-DISP - Oracle Remote Data Base
CHIP-LM - Chipcom License Manager
ITSCOMM-NS - itscomm-ns
MVEL-LM - mvel-lm
ORACLENAMES - oraclenames
MOLDFLOW-LM - moldflow-lm
HYPERCUBE-LM - hypercube-lm
JACOBUS-LM - Jacobus License Manager
IOC-SEA-LM - ioc-sea-lm
TN-TL-R1 - tn-tl-r1
VMF-MSG-PORT - vmf-msg-port
TAMS-LM - Toshiba America Medical Systems
SIMBAEXPRESS - simbaexpress
TN-TL-FD2 - tn-tl-fd2
INTV - intv
IBM-ABTACT - ibm-abtact
PRA_ELMD - pra_elmd
TRIQUEST-LM - triquest-lm
VQP - VQP
GEMINI-LM - gemini-lm
NCPM-PM - ncpm-pm
COMMONSPACE - commonspace
MAINSOFT-LM - mainsoft-lm
SIXTRAK - sixtrak
RADIO - radio
RADIO-SM - radio-sm
ORBPLUS-IIOP - orbplus-iiop
PICKNFS - picknfs

1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668

SIMBASERVICES - simbaservices
ISSD
AAS - aas
INSPECT - inspect
PICODBC - pickodbc
ICABROWSER - icabrowser
SLP - Salutation Manager (Salutation Protocol)
SLM-API - Salutation Manager (SLM-API)
STT - stt
SMART-LM - Smart Corp. License Manager
ISYSG-LM - isysg-lm
TAURUS-WH - taurus-wh
ILL - Inter Library Loan
NETBILL-TRANS - NetBill Transaction Server
NETBILL-KEYREP - NetBill Key Repository
NETBILL-CRED - NetBill Credential Server
NETBILL-AUTH - NetBill Authorization Server
NETBILL-PROD - NetBill Product Server
NIMROD-AGENT - Nimrod Inter-Agent Communication
SKYTELNET - skytelne
XS-OPENBACKUP - xs-openbackup
FAXPORTWINPORT - faxportwinport
SOFTDATAPHONE - softdataphone
ONTIME - ontime
JALEOSND - jaleosnd
UDP-SR-PORT - udp-sr-port
SVS-OMAGENT - svs-omagent
CNCP - CableNet Control Protocol
CNAP - CableNet Admin Protocol
CNIP - CableNet Info Protocol
CERT-INITIATOR - cert-initiator
CERT-RESPONDER - cert-responder
INVISION - InVision
ISIS-AM - isis-am
ISIS-AMBC - isis-ambc
SAISEH - Satellite-data Acquisition System 4
DATAMETRICS - datametrics
SA-MSG-PORT - sa-msg-port
RSAP - rsap
CONCURRENT-LM - concurrent-lm
INSPECT - inspect
NKD
SHIVA_CONFSRVR - shiva_confsrvr
XNMP - xnmp
ALPHATECH-LM - alphatech-lm
STARGATEALERTS - stargatealerts
DEC-MBADMIN - dec-mbadmin
DEC-MBADMIN-H - dec-mbadmin-h
FUJITSU-MMPDC - fujitsu-mmpdc
SIXNETUDR - sixnetudr
SG-LM - Silicon Grail License Manager
SKIP-MC-GIKREQ - skip-mc-gikreq
NETVIEW-AIX-1 - netview-aix-1
NETVIEW-AIX-2 - netview-aix-2
NETVIEW-AIX-3 - netview-aix-3
NETVIEW-AIX-4 - netview-aix-4
NETVIEW-AIX-5 - netview-aix-5
NETVIEW-AIX-6 - netview-aix-6
NETVIEW-AIX-7 - netview-aix-7
NETVIEW-AIX-8 - netview-aix-8

1669
1670
1671
1672
1673
1674
1675
1676
1677
1723
1807
1812
1813
1827
1981
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2030
2032

NETVIEW-AIX-9 - netview-aix-9
NETVIEW-AIX-10 - netview-aix-10
NETVIEW-AIX-11 - netview-aix-11
NETVIEW-AIX-12 - netview-aix-12
PROSHARE-MC-1 - Intel Proshare Multicast
PROSHARE-MC-2 - Intel Proshare Multicast
PDP - Pacific Data Products
NEFCOMM1 - netcomm1
GROUPWISE - groupwise
PPTP - pptp
SpySender
RADIUS - RADIUS Authentication Protocol
RADACCT - RADIUS Accounting Protocol
PCM - PCM Agent
Shockrave
LICENSEDAEMON - cisco license management
TR-RSRB-P1 - cisco RSRB Priority 1 port
TR-RSRB-P2 - cisco RSRB Priority 2 port
MSHNET - MHSnet system
STUN-P1 - cisco STUN Priority 1 port
STUN-P2 - cisco STUN Priority 2 port
IPSENDMSG - IPsendmsg
SNMP-TCP-PORT - cisco SNMP TCP port
STUN-PORT - cisco serial tunnel port
PERF-PORT - cisco perf port
TR-RSRB-PORT - cisco Remote SRB port
GDP-PORT - cisco Gateway Discovery Protocol
X25-SVC-PORT - cisco X.25 service (XOT)
TCP-ID-PORT - cisco identification port
CALLBOOK
DC
GLOBE
CFINGER - cfinger
MAILBOX
BERKNET
INVOKATOR
DECTALK
CONF
NEWS
SEARCH
RAID-CC - raid
TTYINFO RAID-AM
TROFF
CYPRESS
BOOTSERVER
CYPRESS-STAT
TERMINALDB
WHOSOCKAMI
XINUPAGESERVER
SERVEXEC
DOWN
XINUEXPANSION3
XINUEXPANSION4
ELLPACK
SCRABBLE

SHADOWSERVER
SUBMITSERVER
DEVICE2
BLACKBOARD

2033
2034
2035
2038
2040
2041
2042
2043
2044
2045
2046
2047
2048
2064
2065
2067
2080
2103
2104
2105
2106
2108
2111
2112
2115
2120
2140
2155
2201
2221
2222
2223
2232
2241
2283
2301
2307
2401
2430
2431
2432
2433
2500
2501
2564
2565
2583
2592
2600
2601
2602
2603
2604
2605
2627
2638
2700
2766
2784

GLOGGER
SCOREMGR
IMSLDOC
OBJECTMANAGER
LAM
INTERBASE
ISIS - isis
ISIS-BCAST - isis-bcast
RIMSL
CDFUNC
SDFUNC
DLS
DLS-MONITOR - dls-monitor
DISTRIB-NETASSHOLES - A group of lamers working on a closed-source client for solving the
RSA cryptographic challenge
DLSRPN - Data Link Switch Read Port Number
DLSWPN - Data Link Switch Write Port Number
Wingate Winsock Redirector Service
ZEPHYR-CLT - Zephyr Serv-HM Conncetion
Zephyr Host Manager
EKLOGIN - Kerberos (v4) Encrypted RLogin
EKSHELL - Kerberos (v4) Encrypted RShell
RKINIT - Kerberos (v4) Remote Initialization
KX - X Over Kerberos
KIP - IP Over Kerberos
Bugs
KAUTH - Remote kauth
Deep Throat, The Invasor
Illusion Mailer
ATS - Advanced Training System Program
UNREG-AB1 - Allen-Bradley unregistered port
UNREG-AB2 - Allen-Bradley unregistered port
INREG-AB3 - Allen-Bradley unregistered port
IVS-VIDEO - IVS Video default
IVSD - IVS Daemon
HVL Rat5
CIM - Compaq Insight Manager
PEHELP - pehelp
CVSPSERVER - CVS Network Server
VENUS
VENUS-SE
CODASRV
CODASRV-SE
RTSSERV - Resource Tracking system server
RTSCLIENT - Resource Tracking system client
HP-3000-TELNET - HP 3000 NS/VT block mode telnet
Striker
WinCrash
NETREK[GAME] - netrek[game]
Digital Rootbeer
ZEBRA - Zebra VTY
RIPD - RIPd VTY
RIPNGD - RIPngd VTY
OSPFD - OSPFd VTY
BGPD - BGPd VTY
WEBSTER Sybase Database
TQDATA - tqdata
LISTEN - System V Listener Port
WWW-DEV - world wide web - development

2800
2989
3000
3001
3005
3006
3024
3049
3064
3086
3128
3129
3130
3141
3150
3155
3264
3295
3306
3333
3421
3454
3455
3456
3457
3459
3700
3791
3801
3871
3900
3905
3908
3920
3921
3922
3923
3925
3975
3984
3985
3986
3996
4000
4001
4008
4045
4092
4132
4133
4321
4333
4343
4444
4500
4501
4557
4559
4567
4590

Phineas Phucker
(UDP) - RAT
UNKNOWN - Unknown Service
NESSUSD - Nessus Security Scanner
DESLOGIN - Encrypted Symmetric Telnet
DESLOGIND WinCrash
NSWS DISTRIB-NET-PROXY - Stupid closed source distrib.net proxy
SJ3 - SJ3 (Kanji Input)
RingZero Masters Paradise SQUID-IPC VMODEM - VMODEM
Deep Throat, The Invasor
HTTP Proxy
CCMAIL - cc:mail/lotus
PORT
MYSQL
DEC-NOTES - DEC Notes
BMAP - Bull Apprise portmapper
MIRA - Apple Remote Access Protocol
PRSVP - RSVP Port
VAT - VAT default data
VAT-CONTROL - VAT default control
Eclipse 2000
Portal of Doom
Eclypse
(UDP) - Eclypse
PORT
UDT_OS - Unidata UDT OS
PORT
PORT
PORT
PORT
PORT
PORT
PORT
PORT
MAPPER-NODEMGR - MAPPER network node manager
MAPPER-MAPETHD - MAPPER TCP/IP server
MAPPER-WS_ETHD - MAPPER workstation server
PORT
UNKNOWN - Unknown Service
PORT
NETCHEQUE - NetCheque accounting
LOCKD - NFS Lock Daemon
WinCrash
NUTS_DEM - NUTS Daemon
NUTS_BOOTP - NUTS Bootp Server
RWHOIS - Remote Who Is
MSQL - Mini SQL Server
UNICALL - UNICALL
NV-VIDEO - NV Video default
SAE-URN - sae-urn
URN-X-CDCHOICE - urn-x-cdchoice
FAX - fax
HYLAFAX - HylaFAX cli-svr Protocol
File Nail
ICQTrojan

4672
4899
5000
5001
5002
5003
5004
5005
5010
5011
5031
5050
5075
5145
5190
5191
5192
5193
5232
5236
5300
5301
5302
5303
5304
5305
5308
5321
5376
5400
5401
5402
5432
5500
5510
5512
5520
5530
5540
5550
5555
5556
5557
5569
5631
5632
5650
5680
5713
5714
5715
5716
5717
5742
5800
5801
5858
5900
5901
5902

RFA - remote file access server


RAdmin - Remote Administrator
UNKNOWN - Unknown Service
COMMPLEX-LINK RFE - radio free ethernet
CLARIS-FMPRO - Claris FileMaker Pro
AVT-PROFILE-1 - avt-profile-1
AVT-PROFILE-2 - avt-profile-2
TELELPATHSTART - TelepathStart
TELELPATHATTACK - TelepathAttack
NetMetro
MMCC - multimedia conference control tool
IISADMIN - IIS Administration Web Site
RMONITOR_SECURE
AOL - America-Online
AOL-1 - AmericaOnline1
AOL-2 - AmericaOnline2
AOL-3 - AmericaOnline3
SGI-DGL - SGI Distributed Graphics
PADL2SIM
HACL-HB - HA Cluster Heartbeat
HACL-GS - HA Cluster General Services
HACL-CFG - HA Cluster Configuration
HACL-PROBE - HA Cluster Probing
HACL-LOCAL
HACL-TEST
CFENGINE Firehotcker
MS FTP
Blade Runner, Back Construction
Blade Runner, Back Construction
Blade Runner, Back Construction
POSTGRES - Postgres Database Server
Hotline Server
SECUREIDPROP - ACE/Server Services
Illusion Maker
SDLOG - ACE/Server Services
SDSERV - ACE/Server Services
SDXAUTHD - ACE/Server Services
Xtcp
ServeMe
Bo
Bo
Robo-Hack
PCANYWHEREDATA
PCANYWHERESTAT
MS FTP PORT
CANNA - Canna (Jap Input)
PROSHAREAUDIO - proshare conf audio
PROSHAREVIDEO - proshare conf video
PROSHAREDATA - proshare conf data
PROSHAREREQUEST - proshare conf request
PROSHARENOTIFY - proshare conf notify
WinCrash
VNC - Virtual Network Computing
VNC - Virtual Network Computing
NETREK[GAME] - netrek[game]
VNC - Virtual Network Computing
VNC-1 - Virtual Network Computing Display
VNC-2 - Virtual Network Computing Display

5977
5978
5979
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6110
6111
6112
6141
6142
6143
6144
6145
6146
6147
6148
6149
6400
6455
6456
6558
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6771
6776
6912
6939
6969
6970
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009

NCD-PREF-TCP - NCD Preferences


NCD-DIAG-TCP - NCD Diagnostics
NCD-CONF-TCP - NCD Configuration
NCD-PREF - NCD Preferences Telnet
NCD-DIAG - NCD Diagnostics Telnet
NCD-CONF - NCD Configuration Telnet
X11 - X Window System
X11:1 - X Window Server
X11:2 - X Window Server
X11:3 - X Window Server
X11:4 - X Window Server
X11:5 - X Window Server
X11:6 - X Window Server
X11:7 - X Window Server
X11:8 - X Window Server
X11:9 - X Window Server
SOFTCM - HP SoftBench CM
SPC - HP SoftBench Sub-Process Control
DTSPCD - dtspcd
META-CORP - Meta Corporation License Manager
ASPENTEC-LM - Aspen Technology License Manager
WATERSHED-LM - Watershed License Manager
STATSCI1-LM - StatSci License Manager - 1
STATSCI2-LM - StatSci License Manager - 2
LONEWOLF-LM - Lone Wolf Systems License Manager
MONTAGE-LM - Montage License Manager
RICARDO-LM - Ricardo North America License Manager
TAL-POD - tal-pod
The Thing
SKIP-CERT-RECV - SKIP Certificate Receive
SKIP-CERT-SEND - SKIP Certificate Send
XDSXDM IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC-SERV - irc-serv
IRC - irc
IRC - irc
Vampyre
DeepThroat
IRC-SERV - irc-serv
DeepThroat
BackDoor-G, SubSeven
Shit Heep
Indoctrination
ACMSODA - acmsoda
GateCrasher, Priority, IRC 3
AFSSERV - file server itself
UNKNOWN - Unknown Service
UNKNOWN - Unknown Service
AFS3-VLSERVER - volume location database
AFS3-KASERVER - AFS/Kerberos authentication service
AFS3-VOLSER - volume managment server
AFS3-ERRORS - error interpretation service
AFS3-BOS - basic overseer process
AFS3-UPDATE - server-to-server updater
AFS3-RMTSYS - remote cache manager service

7010
7100
7120
7121
7200
7201
7300
7301
7306
7307
7308
7309
7326
7648
7649
7650
7651
7770
7777
7789
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8080
8081
8082
8083
8084
8085
8086
8087
8088
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8181
8383
8450
8765
8807
8888
8892
9000
9001

UPS-ONLINET - onlinet uninterruptable power supplies


FONT-SERVICE - X Font Service
IISADMIN - IIS Administration Web Site
VIRPROT-LM - Virtual Prototypes License Manager
FODMS - FODMS FLIP
DLIP - DLIP
NetMonitor
NetMonitor
NetMonitor
NetMonitor
NetMonitor
NetMonitor
ICB - Internet Citizen's Band
CUCME-1 - CucMe live video/Audio Server
CUCME-2 - CucMe live video/Audio Server
CUCME-3 - CucMe live video/Audio Server
CUCME-4 - CucMe live video/Audio Server
IRC
CBT - cbt
Back Door Setup, ICKiller
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
Generic - Shared service port
NPMP - npmp
Ultraseek
DEMOS NNTP
SiteScope - SiteScope Remote Server Monitoring
SEOSLOAD - eTrust ACX
UNKNOWN - Unknown Service
UNKNOWN

9010
9090
9095
9100
9200
9201
9202
9203
9400
9535
9872
9873
9874
9875
9876
9989
9998
9999
10005
10067
10080
10082
10083
10101
10167
10520
10607
11000
11223
11371
12067
12223
12345
12346
12361
12362
12631
13000
13326
16660
16969
17007
17300
18000
20000
20001
20005
20034
20203
21544
21845
21846
21847
22222
22273
22289
22305
22321
23456
23476

SERVICE
ZEUS-ADMIN - Zeus Admin Server
SERVICE
JETDIRECT - HP JetDirect Card
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
WAP - Wireless Application Protocol
InCommand
MAN
Portal of Doom
Portal of Doom
Portal of Doom
Portal of Doom
SD - Session Director
iNi-Killer
DEMOS SMTP
DISTINCT - distinct
STEL - Secure Telnet
(UDP) - Portal of Doom
AMANDA - Amanda Backup Util
AMANDA-IDX - Amanda Indexing
AMIDXTAPE - Amanda Tape Indexing
BrainSpy
(UDP) - Portal of Doom
Acid Shivers
Coma
Senna Spy
Progenic trojan
PKSD - PGP Pub. Key Server
Gjamer
Hack99 KeyLogger
NB - NetBus
GabanBus, NetBus, X-bill
Whack-a-mole
Whack-a-mole
Whackjob
Senna Spy
CROSSFIRE[GAME] - crossfire[game]
Stacheldraht Master Serverd
Priority
ISODE-DUA
Kuang2 The Virus
BIIMENU - Beckman Instruments Inc.
Millennium
Millennium backdoor
BTX - Xcept4
Netbus 2 Pro
Logged
Girlfriend
WEBPHONE - webphoned

INFO SERVER - info server


CONNECT SERVER - connect server
Prosiak
WNN6 - Wnn6 (Jap. Input)
WNN6_CN - Wnn6 (Chi. Input)
WNN6_KR - Wnn6 (Kor. Input)
WNN6_TW - Wnn6 (Tai. Input)
Evil FTP, Ugly FTP , Whack Job
Donald Dick

23477
24326
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
26000
26001
26002
26208
26274
27119
27444
27500
27501
27502
27665
27910
27911
27912
27913
27920
27960
29891
29970
30029
30100
30101
30102
30303
30999
31335
31336
31337
31338
31457
31666
31785
31787
31788
31789
31791
31792
32000
33333
33911
34324
40193
40412
40421
40422
40423
40426
43188

Donald Dick
Netscape Server
ICL-TWOBASE1 - icl-twobase1
ICL-TWOBASE2 - icl-twobase2
ICL-TWOBASE3 - icl-twobase3
ICL-TWOBASE4 - icl-twobase4
ICL-TWOBASE5 - icl-twobase5
ICL-TWOBASE6 - icl-twobase6
ICL-TWOBASE7 - icl-twobase7
ICL-TWOBASE8 - icl-twobase8
ICL-TWOBASE9 - icl-twobase9
ICL-TWOBASE10 - icl-twobase10
QUAKEXX
QUAKEXX
QUAKEXX
WNN6_DS - Wnn6 (Dserver)
(UDP) - Delta Source
QUAKEXX
TRINOO_BCAST - Trinoo Attack Tool
QUAKEXX
QUAKEXX
QUAKEXX
TRINOO_MASTER - Trinoo Attack Tool
QUAKEXX
QUAKEXX
QUAKEXX
QUAKEXX
QUAKEXX
QUAKE3SERVER - Quake 3 Arena Server
(UDP) - The Unexplained
PORT
AOL Trojan
NetSphere
Netsphere
NetSphere
Sockets de Troie
Kuang2
TRINOO_REGISTER - Trinoo Attack Tool
Whack
BO - BackOrifice
NetSpy DK
TETRINET (Tetris GAME)
BO Whack
HackrarTack
HackrarTack
HackrarTack
HackrarTack (udp)
HackrarTack (udp)
HackrarTack
Generic - Shared service port
Prosiak
Spirit 2001a
BigGluck, TN
NetWare
The Spy
Agent 40421, Masters Paradise
Masters Paradise
Masters Paradise
Masters Paradise
REACHOUT

44333
WinRoute
47262
(UDP) - Delta Source
47557
DBBROWSE - Databeam Corporation
3.

50505
Sockets de Troie
50766
Fore, Schwindler
53001
Remote Window Shutdown
54320
BO 2K
54321
SchoolBus
60000
Deep Throat
61466
TeleCommando
65000
Devil
65301
PCANYWHERE

() .2,3
Internet.

6
TCP- connect()

#include <stdio.h>

#include <errno.h>

#include <netdb.h>

#include <fcntl.h>

#define port 3490 // server`s port number

#define MAXDATASIZE 100 // buffer size

int main( int argc, char *argv[])

// structures used by select(...)

10

fd_set rfds;

11

struct timeval tv;

12

int sockfd;

13

int numbytes;

14

char buf[MAXDATASIZE];

15

struct hostent *he;

16

struct sockaddr_in their_addr;

17

int flags;

18

// check for command line`s argument

19

if (argc!=2)

20

21

fprintf (stderr, "usage: client hostname\n");

22

exit(1);

23

24

// get IP address by name (for example, localhost -> 127.0.0.1)

25

if ((he=gethostbyname (argv [1]))==NULL)

26

27

herror ("gethostbyname");

28

exit(1);

29

30

// create a socket

31

if ((sockfd=socket (AF_INET, SOCK_STREAM, 0))==-1)

32

33

perror("socket");

34

exit(1);

35

36

// remove blocking from the socket

37

flags = fcntl(sockfd, F_GETFL, 0);

38

fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);

39

// fill their_addr structure (destination address)

40

their_addr.sin_family=AF_INET;

41

their_addr.sin_port=htons(port);

42

their_addr.sin_addr= *((struct in_addr *)he->h_addr);

43

bzero(&(their_addr.sin_zero), 8);

44

// prepare structures used by select(...)

45

tv.tv_sec=10;

46

tv.tv_usec=0;

47

FD_ZERO(&rfds);

48

FD_SET(sockfd,&rfds);

49

// try to connect to the server (connect(...) is NON blocking!!!)

50

printf("Connecting...\n");

51

if(connect(sockfd,(struct sockaddr*)&their_addr,sizeof(their_addr))!=0)

52

if(errno!=EINPROGRESS) // check for connection error (EINPROGRESS is NOT an


53 error!)
54

55

perror("connect");

56

exit(1);

57

58

59

else

60

61

printf("connected at once\n");

62

63

// wait for server`s response (block the program)

64

if(select(sockfd+1, &rfds, NULL, NULL, &tv) == -1)

65

66

perror("select");

67

exit(-1);

68

69

// if sockfd descriptor is in rfds set

70

// then server answered for our request

71

// otherwise time out occured

72

if(FD_ISSET(sockfd, &rfds))

73

74

socklen_t err_len;

75

int error;

76

err_len=sizeof(error);

77

// check for the server`s response

78

if(getsockopt(sockfd,SOL_SOCKET,SO_ERROR,&error,&err_len)==-1)

79

80

perror("getsockopt");

81

exit(1);

82

83

if(error != 0)

84

85

printf("SO_ERROR = %d\n", error);

86

printf("Connection failed\n");

87

exit(-1);

88

89

90

else

91

92

printf("Connection timed out\n");

93

exit(-1);

94

95

// return blocking state to the socket

96

fcntl(sockfd, F_SETFL, flags);

97

// wait for incoming message

98

if ((numbytes=recv(sockfd, buf, MAXDATASIZE, 0))==-1)

99

100

perror ("recv");

101

exit(1);

102

103

// show incomming message

104

buf [numbytes]='\0'; // zero terminated string

105

printf ("Received: %s \n", buf);

106

// close the socket

107

close (sockfd);

108

return 0;

109 }

:
. connect()
.
select().
fcntl() ( 37-38).
O_NONBLOCK, .
connect() ( 51) EINPROGRESS.
, connect() .
select() ( 64). rfds,
, . select() rfds
, . rfds
72 FD_ISSET.
78 . getsockopt()
. , .
96 , .. .
recv() ( 98) ,
.
:

. select()
timeout.

. TCP
TCP RST. timeout.

. TCP
TCP ACK. timeout.

#ifndef IP_MULTICAST_IF
/* include/netinet/in.h BSD 4.4. */
#define IP_MULTICAST_IF 9
/* / IP multicast */
#define IP_MULTICAST_TTL 10
/* / IP multicast TTL */
#define IP_MULTICAST_LOOP 11
/* / IP multicast */
#define IP_ADD_MEMBERSHIP 12
/* () IP- */
#define IP_DROP_MEMBERSHIP 13
/* IP- */
#define IP_DEFAULT_MULTICAST_TTL 1
#define IP_DEFAULT_MULTICAST_LOOP 1
#define IP_MAX_MEMBERSHIPS 20
/* / multicast- */

typedef struct ip_mreq {


struct in_addr imr_multiaddr;
/* */
struct in_addr imr_interface;
/* */
}IP_MREQ;
#endif
...
#define DESTINATION_MCAST "234.5.6.7"
#define DESTINATION_PORT 4567
#define BUFSIZE 1024
...
int nRet, nSize, nOptVal;
SOCKET hSock;
char achInBuf[BUFSIZE];
struct sockaddr_in stSourceAddr, stDestAddr;
u_short nSourcePort;
struct ip_mreq stIpMreq;
...
/* (UDP) */
hSock = socket(PF_INET, SOCK_DGRAM, 0);
if (hSock == INVALID_SOCKET)
{ }
...
/* multicast-. */
...
/* */
stSourceAddr.sin_family = AF_INET;
stSourceAddr.sin_port = htons(nSourcePort);
stSourceAddr.sin_addr.s_addr = INADDR_ANY;
/* bind() ,
*/
nRet=bind(hSock,(struct sockaddr FAR *)&stSourceAddr,sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
//
}
...
/* (loopback) multicast-, , . .
(. 2.9.3).*/
nOptVal = FALSE;
nRet=setsockopt(hSock,IPPROTO_IP,IP_MULTICAST_LOOP,(char FAR *)nOptVal, sizeof(int));
if (nRet == SOCKET_ERROR) {
/* , .
WinSock , . ,
loopback-, , .*/
bLoopFailed = TRUE;
}
...
/* IP TTL 1 64, multicast-
*/
nOptVal = 64;
nRet = setsockopt (hSock, IPPROTO_IP, IP_MULTICAST_TTL,(char FAR *)nOptVal, sizeof(int));
if (nRet == SOCKET_ERROR) {
}
...
/* */
stDestAddr.sin_family = AF_INET;
stDestAddr.sin_addr.s_addr = inet_addr (DESTINATION_MCAST);
stDestAddr.sin_port = htons (DESTINATION_PORT);
...
nRet = sendto (hSock, (char FAR *)achOutBuf,lstrlen(achOutBuf), 0,

(struct sockaddr FAR *) &stDestAddr,


sizeof(struct sockaddr));
if (nRet == SOCKET_ERROR)
{
//
}
...
/*----------------------- ------------------------ FD_READ ( , ,
) */
nRet = WSAAsyncSelect (hSock, hwnd, WM_READ_DATA, FD_READ);
if (nRet == SOCKET_ERROR)
{
//
}
...
/* , */
stIpMreq.imr_multiaddr.s_addr = DESTINATION_MCAST; /* */
stIpMreq.imr_interface.s_addr = INADDR_ANY; /* default */
nRet = setsockopt (hSock, IPPROTO_IP, IP_ADD_MEMBERSHIP,
(char FAR *)&stIpMreq, sizeof (struct ip_mreq));
if (nRet == SOCKET_ERROR) {
}
...
/* multicast- */
case WM_READ_DATA:
if (WSAGETSELECTERROR (lParam))
{
//
}
switch (WSAGETSELECTEVENT (lParam)) {
case FD_READ:
/* */
nSize = sizeof(struct sockaddr);
nRet = recvfrom (hSock, (char FAR *)achInBuf, BUFSIZE, 0, (struct sockaddr *) &stSockAddr,
&nSize);
if (nRet == SOCKET_ERROR)
{
//
} break;
}

8
UDP- (raw)

// Compile:
// cl -o Iphdrinc Iphdrinc.c ws2_32.lib
// Command Line Parameters/Arguments:
// iphdrinc [-fp:int] [-fi:str] [-tp:int] [-ti:str] [-n:int] [-m:str]
// -fp:int From -
// -fi:IP From - IP-
// -tp:int To
-
// -ti:IP To
- IP-
// -n:int
// -m:str
#pragma pack(1)
#define WIN32_LEAN_AND_MEAN //
#include <winsock2.h>
#include <ws2tcpip.h>
#include <stdio.h>

#include <stdlib.h>
#define MAX_MESSAGE 4068
#define MAX_PACKET 4096
//
#define DEFAULT_PORT 5150
#define DEFAULT_IP "10.0.0.1"
#define DEFAULT_COUNT 5
#define DEFAULT_MESSAGE "This is a test"
// IP-. .
typedef struct ip_hdr
{
unsigned char ip_verlen;
// IP
unsigned char ip_tos;
// TOS
unsigned short ip_totallength;
//
unsigned short ip_id;
//
unsigned short ip_offset;
//
unsigned char ip_ttl;
// TTL
unsigned char ip_protocol;
//
unsigned short ip_checksum;
//
unsigned int ip_srcaddr;
//
unsigned int ip_destaddr;
//
} IP_HDR, *PIP_HDR, FAR* LPIP_HDR;
// UDP-
typedef struct udp_hdr
{
unsigned short src_portno;
//
unsigned short dst_portno;
//
unsigned short udp_length;
// UDP-
unsigned short udp_checksum;
// UDP- ( )
} UDP_HDR, *PUDP_HDR;
//
unsigned long dwToIP,
// IP
dwFromIP;
// IP (spoof)
unsigned short iToPort,
//
iFromPort;
// (spoof)
DWORD dwCount;
//
char strMessage[MAX_MESSAGE];
//
//
void usage(char *progname)
{
printf("usage: %s [-fp:int] [-fi:str] [-tp:int] [-ti:str]\
[-n:int] [-m:str]\n", progname);
printf(" -fp:int From (sender) port number\n");
printf(" -fi:IP From (sender) IP address\n");
printf(" -fp:int To (recipient) port number\n");
printf(" -fi:IP To (recipient) IP address\n");
printf(" -n:int Number of times to read message\n");
printf(" -m:str Size of buffer to read\n\n");
ExitProcess(1); // WinAPI, .
}
//
void ValidateArgs(int argc, char **argv)
{
int i;
iToPort = DEFAULT_PORT;
iFromPort = DEFAULT_PORT;
dwToIP = inet_addr(DEFAULT_IP);
dwFromIP = inet_addr(DEFAULT_IP);
dwCount = DEFAULT_COUNT;
strcpy(strMessage, DEFAULT_MESSAGE);
for(i = 1; i < argc; i++)
{
if ((argv[i][0] == '-') || (argv[i][0] == '/'))
{
switch (tolower(argv[i][1]))
{
case 'f': // From address
switch (tolower(argv[i][2]))
{
case 'p':if (strlen(argv[i]) > 4) iFromPort = atoi(&argv[i][4]);
break;

case 'i': if (strlen(argv[i]) > 4) dwFromIP = inet_addr(&argv[i][4]);


break;
default: usage(argv[0]);
break;
}
break;
case 't': //
switch (tolower(argv[i][2]))
{
case 'p': if (strlen(argv[i]) > 4) iToPort = atoi(&argv[i][4]);
break;
case 'i': if (strlen(argv[i]) > 4) dwToIP = inet_addr(&argv[i][4]);
break;
default:
usage(argv[0]);
break;
}
break;
case 'n': //
if (strlen(argv[i]) > 3)dwCount = atol(&argv[i][3]);
break;
case 'm': if (strlen(argv[i]) > 3) strcpy(strMessage, &argv[i][3]);
break;
default:
usage(argv[0]);
break;
}
}
}
return;
}
//
//
USHORT checksum(USHORT *buffer, int size)
{
unsigned long cksum=0;
while (size > 1)
{
cksum += *buffer++;
size -= sizeof(USHORT);
}
if (size)
{
cksum += *(UCHAR*)buffer;
}
cksum = (cksum >> 16) + (cksum & 0xffff);
cksum += (cksum >>16);
return (USHORT)(~cksum);
}
// main(). , WinSock 2.0,
// IP_HDRINCL.
// IP UDP .
// .
int main(int argc, char **argv)
{
WSADATA wsd;
SOCKET sd;
BOOL bOpt=TRUE;
// IP_HDRINCL
struct sockaddr_in remote;
//
IP_HDR ipHdr;
// IP-
UDP_HDR udpHdr;
// UDP-
int ret;
DWORD i;
unsigned short iTotalSize,iUdpSize,iUdpChecksumSize, iIPVersion, iIPSize, cksum = 0;
char buf[MAX_PACKET], *ptr = NULL;
IN_ADDR addr;
//
ValidateArgs(argc, argv);
addr.S_un.S_addr = dwFromIP;
printf("From IP: <%s>\n Port: %d\n", inet_ntoa(addr),iFromPort);
addr.S_un.S_addr = dwToIP;

printf("To IP: <%s>\n Port: %d\n", inet_ntoa(addr), iToPort);


printf("Message: [%s]\n", strMessage);
printf("Count: %d\n", dwCount);
if (WSAStartup(MAKEWORD(2,2), &wsd) != 0) // WinSock
{
printf("WSAStartup() failed: %d\n", GetLastError());
return -1;
}
//
sd = WSASocket(AF_INET, SOCK_RAW, IPPROTO_UDP, NULL, 0,0);
if (sd == INVALID_SOCKET)
{
printf("WSASocket() failed: %d\n", WSAGetLastError());
return -1;
}
// IP_HDRINCL sd
ret = setsockopt(sd, IPPROTO_IP, IP_HDRINCL, (char *)&bOpt, sizeof(bOpt));
if (ret == SOCKET_ERROR)
{
printf("setsockopt(IP_HDRINCL) failed: %d\n", WSAGetLastError());
return -1;
}
// IP-
iTotalSize = sizeof(ipHdr) + sizeof(udpHdr) + strlen(strMessage);
iIPVersion = 4;
iIPSize = sizeof(ipHdr) / sizeof(unsigned long);
ipHdr.ip_verlen = (iIPVersion << 4) | iIPSize;
ipHdr.ip_tos = 0;
// TOS=0
ipHdr.ip_totallength = htons(iTotalSize); // IP-
ipHdr.ip_id = 0;
// , 0
ipHdr.ip_offset = 0;
//
ipHdr.ip_ttl = 128;
// TTL
ipHdr.ip_protocol = 0x11; // -(UDP)
ipHdr.ip_checksum = 0 ;
//
ipHdr.ip_srcaddr = dwFromIP;
//
ipHdr.ip_destaddr = dwToIP;
//
// UDP-
iUdpSize = sizeof(udpHdr) + strlen(strMessage);
udpHdr.src_portno = htons(iFromPort) ;
udpHdr.dst_portno = htons(iToPort) ;
udpHdr.udp_length = htons(iUdpSize) ;
udpHdr.udp_checksum = 0 ;
// UDP-
iUdpChecksumSize = 0;
ptr = buf;
ZeroMemory(buf, MAX_PACKET); // WinAPI, .
memcpy(ptr, &ipHdr.ip_srcaddr, sizeof(ipHdr.ip_srcaddr));
ptr += sizeof(ipHdr.ip_srcaddr);
iUdpChecksumSize += sizeof(ipHdr.ip_srcaddr);
memcpy(ptr, &ipHdr.ip_destaddr, sizeof(ipHdr.ip_destaddr));
ptr += sizeof(ipHdr.ip_destaddr);
iUdpChecksumSize += sizeof(ipHdr.ip_destaddr);
ptr++;
iUdpChecksumSize += 1;
memcpy(ptr, &ipHdr.ip_protocol, sizeof(ipHdr.ip_protocol));
ptr += sizeof(ipHdr.ip_protocol);
iUdpChecksumSize += sizeof(ipHdr.ip_protocol);
memcpy(ptr, &udpHdr.udp_length, sizeof(udpHdr.udp_length));
ptr += sizeof(udpHdr.udp_length);
iUdpChecksumSize += sizeof(udpHdr.udp_length);
memcpy(ptr, &udpHdr, sizeof(udpHdr));
ptr += sizeof(udpHdr);
iUdpChecksumSize += sizeof(udpHdr);
for(i = 0; i < strlen(strMessage); i++, ptr++)
*ptr = strMessage[i];
iUdpChecksumSize += strlen(strMessage);
cksum = checksum((USHORT *)buf, iUdpChecksumSize);
udpHdr.udp_checksum = cksum;
// IP UDP
ZeroMemory(buf, MAX_PACKET);
ptr = buf;

memcpy(ptr, &ipHdr, sizeof(ipHdr)); ptr += sizeof(ipHdr);


memcpy(ptr, &udpHdr, sizeof(udpHdr)); ptr += sizeof(udpHdr);
memcpy(ptr, strMessage, strlen(strMessage));
// sendto()
remote.sin_family = AF_INET;
remote.sin_port = htons(iToPort);
remote.sin_addr.s_addr = dwToIP;
for(i = 0; i < dwCount; i++) //
{
ret = sendto(sd, buf, iTotalSize, 0, (SOCKADDR *)&remote, sizeof(remote));
if (ret == SOCKET_ERROR)
{
printf("sendto() failed: %d\n", WSAGetLastError());
break;
}
else
printf("sent %d bytes\n", ret);
}
closesocket(sd) ;
WSACleanup() ;
return 0;
}

9
TCP- /

#include <stdio.h>
#include <winsock2.h>
#define PORT 3490
//
#define MAXDATASIZE 1000
//
#define TIME_TO_WAIT 100
//
char* msg = "Hello, server! Nice to meet you";//
int main(int argc, char* argv[])
{
struct hostent*
he;
struct sockaddr_in addr;
DWORD
read = 0, write = 0, flags = 0;
SOCKET
sock;
char
buffer[MAXDATASIZE + 1];
WSADATA
wsaData;
WSABUF
wsaBufRead;
WSABUF
wsaBufWrite;

WSAOVERLAPPED
wsaOverlappedRead;
WSAOVERLAPPED
wsaOverlappedWrite;
//
if ( argc != 2 )
{
fprintf( stderr, "Usage: client <hostname>\n" );
exit( 1 );
}
// WinSock
WSAStartup( MAKEWORD( 2, 0 ), &wsaData );
// DNS
if ( ( he = gethostbyname( argv[1] ) ) == NULL )
{
fprintf( stderr, "Failed to resolve host name\n" );
exit( 1 );
}
//
if ( ( sock = WSASocket( AF_INET, SOCK_STREAM, 0, NULL, 0, WSA_FLAG_OVERLAPPED ) )
== INVALID_SOCKET )
{
fprintf( stderr, "Failed creating socket\n" );
exit( 1 );
}
memset( &addr, 0, sizeof( addr ) );
//
addr.sin_family
= AF_INET;
addr.sin_port = htons( PORT );
addr.sin_addr = *((struct in_addr*) he->h_addr_list[0]);
//
if ( WSAConnect ( sock, (sockaddr*) &addr, sizeof( sockaddr ), NULL, NULL, NULL,
NULL ) == SOCKET_ERROR )
{
fprintf( stderr, "Failed connecting to remote host, %d\n", WSAGetLastError( ) );
closesocket( sock );
exit( 1 );
}
// 1.
wsaBufRead.buf = buffer;
wsaBufRead.len = MAXDATASIZE;
wsaOverlappedRead.hEvent = NULL;
//
if (
( WSARecv( sock, &wsaBufRead, 1, &read, &flags, &wsaOverlappedRead, NULL ) ==
SOCKET_ERROR ) &&
( WSAGetLastError( ) != WSA_IO_PENDING ))
{
fprintf( stderr, "Failed reading on socket\n" );
closesocket( sock );
exit( 1 );
}
// 2.
wsaBufWrite.buf = msg;
wsaBufWrite.len = strlen( msg );
wsaOverlappedWrite.hEvent = NULL;
//
if (
( WSASend( sock, &wsaBufWrite, 1, &write, 0, &wsaOverlappedWrite, NULL ) ==
SOCKET_ERROR ) &&
( WSAGetLastError( ) != WSA_IO_PENDING ))
{
fprintf( stderr, "Failed sending on socket\n" );
closesocket( sock );
exit( 1 );
}
// ( )
for ( ;; )
{
bool readCompleted = true;
bool writeCompleted = true;
// WSARecv()
if ( WSAGetOverlappedResult( sock, &wsaOverlappedRead, &read, FALSE, &flags
) == FALSE )

{
if ( WSAGetLastError( ) != WSA_IO_INCOMPLETE )
{
fprintf( stderr, "Failed reading data\n" );
break;
}
readCompleted = false;
}
// WSASend()
if ( WSAGetOverlappedResult( sock, &wsaOverlappedWrite, &write, FALSE,
&flags ) == FALSE )
{
if ( WSAGetLastError( ) != WSA_IO_INCOMPLETE )
{
fprintf( stderr, "Failed writing data\n" );
break;
}
writeCompleted = false;
}
printf( "Received: %d\t Sent: %d\n", read, write );
if ( ( readCompleted == true ) && ( writeCompleted == true ) )
{
buffer[read] = '\0';
printf( "Message from server: %s\n", buffer );
break;
}
Sleep( TIME_TO_WAIT );
}
//
closesocket( sock );
return 0;
}

10
o IOCP
-

#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <winsock2.h>
#pragma comment (lib,"ws2_32.lib")
#define PORT 28912
//
DWORD WINAPI ClientPool(SOCKET client); //
//--------------------------------------------------------------------------void main(void){
int j;
//
WORD wVersionRequested; //
WSADATA wsaData;
// -
int err;
//

char address[16]={0};
// ()
char buffer[128];
//
SOCKET sd;
//
HANDLE hThread;
//
DWORD ThreadId;
//
// ws2_32.dll
wVersionRequested=MAKEWORD(2,2);
err=WSAStartup(wVersionRequested,&wsaData);
if(err==SOCKET_ERROR){
strcpy(buffer," - WSAStartup ");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
WSACleanup(); //
getch();
return;
}
strcpy(buffer," ");
CharToOem(buffer,buffer);
printf("%s\n",buffer);
scanf("%s",address);
// C
sd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(sd==INVALID_SOCKET){
strcpy(buffer," - socket ");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
WSACleanup(); //
getch();
return;
}
SOCKADDR_IN sin;//
ZeroMemory(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr =inet_addr(address);
if(connect(sd, (PSOCKADDR)&sin, sizeof(SOCKADDR))==-1)
{
strcpy(buffer," ");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, GetLastError());
WSACleanup(); //
getch();
return;
}
strcpy(buffer," ");
CharToOem(buffer,buffer);
printf("%s\n",buffer);
// ClientPool()
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ClientPool,(void*)sd, 0,
&ThreadId);
while(true)
{
scanf("%s",buffer);
if(strcmp(buffer,"EXIT")==0)
{
TerminateThread(hThread,0);
if (sd!=INVALID_SOCKET)closesocket(sd);
//
break;
}
send(sd,buffer,strlen(buffer),0);
}
WSACleanup();
//
return;
}
//--------------------------------------------------------------------------//

//--------------------------------------------------------------------------DWORD WINAPI ClientPool(SOCKET client)
{
int bytes;
char buffer[128];

while(true)
{
bytes=recv(client,buffer,sizeof(buffer),0);
buffer[strlen(buffer)]='\0';
if(strlen(buffer)!=0)printf("%s\n",buffer);
}
return 0;
}

- IOCP
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <Winsock2.h>
#include <list>
// STL
#pragma comment (lib,"ws2_32.lib")
// ws2_32.lib
using namespace std;
// std
#define BUFF_SIZE
1024
//
#define PORT 28912
//
DWORD WINAPI ServerPool(HANDLE hp);
void SendToAll(char *buffer,unsigned long bytes);
//
//
SOCKET server_sock;
//
int ClientCount;
//
list <SOCKET> ClientList;
//
//--------------------------------------------------------------------------struct ovpConnection: public OVERLAPPED
{
int client_number;
//
SOCKET c;
//
char * buffer;
//
enum
{
op_type_send,
//
op_type_recv
//
}op_type;
//
};
//--------------------------------------------------------------------------void main(int argc, char *argv[])
{
int err;
//
char buffer[128];
//
WORD wVersionRequested; //
WSADATA wsaData;
// -
HANDLE hCp;
//
LPOVERLAPPED overlapped; // I/O
HANDLE hThread;
//
DWORD ThreadId;
//
DWORD flags;
// - WSARecv
// ws2_32.dll
wVersionRequested=MAKEWORD(2,2);
err=WSAStartup(wVersionRequested,&wsaData);
if(err==SOCKET_ERROR)
{
strcpy(buffer," - WSAStartup");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
WSACleanup(); //
getch();
return;
}
//
hCp=CreateIoCompletionPort(INVALID_HANDLE_VALUE,NULL,0,0);
if(hCp==NULL)
{
strcpy(buffer," - CreateIoCompletionPort");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, GetLastError());
WSACleanup(); //
getch();
return;
}

//
server_sock=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,NULL, WSA_FLAG_OVERLAPPED);
if(server_sock==INVALID_SOCKET)
{
strcpy(buffer," - WSASocket");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
WSACleanup(); //
getch();
return;
}
else
{
//
if(CreateIoCompletionPort((HANDLE)server_sock,hCp,0,0)==NULL)
{
strcpy(buffer," - CreateIoCompletionPort");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, GetLastError());
WSACleanup(); //
getch();
return;
}
}
//
SOCKADDR_IN sinServer;
sinServer.sin_family = AF_INET;
sinServer.sin_port = htons(PORT);
sinServer.sin_addr.s_addr = INADDR_ANY;
err = bind( server_sock,(LPSOCKADDR)&sinServer,sizeof(sinServer) );
if(err==-1)
{
strcpy(buffer," - bind");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, GetLastError());
WSACleanup(); //
getch();
return;
}
//
err = listen(server_sock, SOMAXCONN);
if(err==-1)
{
strcpy(buffer," - listen ");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, GetLastError());
WSACleanup(); //
getch();
return;
}
//C
hThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ServerPool,hCp,0, &ThreadId);
ClientCount=0;
strcpy(buffer," \n");
CharToOem(buffer,buffer);
printf("%s",buffer);
//
while(true)
{
// -
SOCKADDR_IN sinClient;
int lenClient=sizeof(sinClient);
SOCKET client = accept(server_sock,(struct sockaddr*)&sinClient, &lenClient);
CreateIoCompletionPort((HANDLE)client,hCp,0,0);
//
ClientList.insert(ClientList.end(),client);
// overlapped-
ovpConnection * op = new ovpConnection;
// overlapped-
op->sock_handle = client;
op->op_type = ovpConnection::op_type_recv;

op->buffer = new char[BUFF_SIZE];


op->hEvent = 0;
op->client_number=++ClientCount;
strcpy(buffer," %d , %d\n");
CharToOem(buffer,buffer);
printf(buffer,ClientCount,ClientList.size());
unsigned long b;
WSABUF buf;
buf.buf = op->buffer;
buf.len = BUFF_SIZE;
flags=0;
err=WSARecv(op->sock_handle, &buf, 1, &b, &flags, op, 0);
if(!err)
{
strcpy(buffer," - WSARecv");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
}
}
return;
}
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------DWORD WINAPI ServerPool(HANDLE hp)
{
int err;
//
unsigned long bytes;
// -
unsigned long key;
// ,
char buffer[128];
//
LPOVERLAPPED overlapped; // I/O
HANDLE hport=hp;
//
DWORD flags;
// - WSARecv()
while(true)
{
//
if(GetQueuedCompletionStatus(hport, &bytes, &key, &overlapped, INFINITE))
{
//
ovpConnection * op = (ovpConnection*)overlapped;
//
switch(op->op_type)
{
//
case ovpConnection::op_type_send:
delete [] op->buffer;
delete op;
break;
//
case ovpConnection::op_type_recv:
if(!bytes)
{
//
ClientList.remove(op->sock_handle);
closesocket(op->sock_handle);
strcpy(buffer," %d , %d\n");
CharToOem(buffer,buffer);
printf(buffer,op->client_number,ClientList.size());
break;
}
op->buffer[bytes]='\0';
if(op->buffer[0]=='*') // * - ,
//
{
strcpy(buffer," %d %s\n");
CharToOem(buffer,buffer);
printf(buffer,op->client_number,(op->buffer+1));
SendToAll(op->buffer, bytes); //
}
else
{

strcpy(buffer," %d %s\n");
CharToOem(buffer,buffer);
printf(buffer,op->client_number,op->buffer);
}
unsigned long b;
WSABUF buf;
buf.buf = op->buffer;
buf.len = BUFF_SIZE;
// buffer_len
err=WSARecv(op->sock_handle, &buf, 1, &b, &flags, op, 0);
if(!err)
{
strcpy(buffer," - WSARecv");
CharToOem(buffer,buffer);
printf("%s %d\n",buffer, WSAGetLastError());
}
}
}
else
{
if(!overlapped)
{
//
// , ,
for(list<SOCKET>::iterator i=ClientList.begin();i!=ClientList.end();i++)
{
closesocket(*i);
}
ClientList.clear();
closesocket(server_sock);
CloseHandle(hport);
strcpy(buffer," %d, \n");
CharToOem(buffer,buffer);
printf(buffer,GetLastError());
getch();
exit(0);
}
else
{
//
closesocket(((ovpConnection*)overlapped)->sock_handle);
ClientList.remove(((ovpConnection*)overlapped)->sock_handle);
strcpy(buffer," %d , %d\n");
CharToOem(buffer,buffer);
printf(buffer,((ovpConnection*)overlapped)->client_number,
ClientList.size());
}
}
}
return 0;
}
//--------------------------------------------------------------------------//
//--------------------------------------------------------------------------void SendToAll(char *buffer,unsigned long bytes)
{
//
for(list<SOCKET>::iterator i=ClientList.begin();i!=ClientList.end();i++)
{
ovpConnection * op = new ovpConnection;
op->sock_handle = *i;
op->op_type = ovpConnection::op_type_send;
op->buffer = new char[bytes-1];
memcpy(op->buffer, (buffer+1), bytes-1);
op->buffer[bytes-1]='\0';
unsigned long b;
WSABUF buf;
buf.buf = op->buffer;
buf.len = BUFF_SIZE;
WSASend(op->sock_handle,&buf,1,&b, 0, op, 0);
}
return;

11
NCB-

NCBACTION

NCBADDGRNAME

NCBADDNAME
NCBASTAT

Windows NT/2000/XP:
. NCBACTION TdiAction.
, ncb_buffer ,
ACTION_HEADER,
() .
NCBACTION NCBCANCEL.
NCBACTION - NetBIOS 3.0
.

,
.
.
TDI , .
()
. , ncb_buffer

NCBCALL
NCBCANCEL
NCBCHAINSEND
NCBCHAINSENDNA
NCBDELNAME
NCBDGRECV
NCBDGRECVBC
NCBDGSEND
NCBDGSENDBC
NCBENUM

NCBFINDNAME

NCBHANGUP
NCBLANSTALERT
NCBLISTEN
NCBRECV
NCBRECVANY
NCBRESET

NCBSEND
NCBSENDNA
NCBSSTAT

NCBTRACE
NCBUNLINK

,
ACTION_HEADER,
NAME_BUFFER.
.
.

.

.
.
.
.
.

(LAN).
Windows NT/2000/XP: LANA.
, ncb_buffer ,
LANA_ENUM. NCBENUM
NetBIOS 3.0.
.
, ncb_buffer ,
FIND_NAME_HEADER,
FIND_NAME_BUFFER.
.
Windows NT/2000/XP: e
, .
(
).
.
,
.
LAN-.
NCB-,

ncb_lana_num.
,
:
ncb_lsn 0x00, ,
ncb_lana_num, .
ncb_lsn 0x00, ,
ncb_lana_num, ,

ncb_callname[0]

,
ncb_callname[2]

ncb_callname[3] ,
NAME_NUMBER_1.
.
.
. ,
ncb_buffer ,
SESSION_HEADER,
.
NCB.
( ).
.
NetBIOS.
Windiws.

NRC_GOODRET
NRC_BUFLEN
NRC_ILLCMD
NRC_CMDTMO
NRC_INCOMP
NRC_BADDR
NRC_SNUMOUT
NRC_NORES
NRC_SCLOSED
NRC_CMDCAN
NRC_DUPNAME
NRC_NAMTFUL
NRC_ACTSES
NRC_LOCTFUL
NRC_REMTFUL
NRC_ILLNN
NRC_NOCALL
NRC_NOWILD
NRC_INUSE
NRC_NAMERR
NRC_SABORT
NRC_NAMCONF
NRC_IFBUSY
NRC_TOOMANY
NRC_BRIDGE
NRC_CANOCCR
NRC_CANCEL
NRC_DUPENV
NRC_ENVNOTDEF
NRC_OSRESNOTAV
NRC_MAXAPPS
NRC_NOSAPS
NRC_NORESOURCES
NRC_INVADDRESS

NRC_INVDDID
NRC_LOCKFAIL
NRC_OPENERR
NRC_SYSTEM
NRC_PENDING

.
.
.
.
.
.
.
.
.
.
.
.
.
;

.
.
.
.
.
.
ncb_name .
.
.
.
.
.
;
.
ncb_lana_num
.
.

NCBCANCEL

.
.
.
reset.
.
.
.
NetBIOS .
.
NCB .
IBM NetBIOS 3.0
NCB.
Netbios.
NCB DDID .

.

. NetBIOS
3.0.
.
.

Windows NT/2000/XP: Windows NT 3.1 .


Windows 95/98/Me: Windows 95 .
: Nb30.h.