1
2 define
3 {
4 SD_RECEIVE = 0x00
5 SD_SEND = 0x01
6 SD_BOTH = 0x02
7
8 SOCKF_PROXY = 0x0001 //
9 SOCKF_FTP = 0x0002 // FTP
10 }
11
12 type socket
13 {
14 str host
15 ushort port
16 uint socket
17 uint flag
18 }
19
20 method uint socket.isproxy
21 {
22 return this.flag & $SOCKF_PROXY
23 }
24
25 method uint socket.close
26 {
27 ineterror = shutdown( this.socket, $SD_BOTH )
28 if !ineterror : ineterror = closesocket( this.socket )
29 return !ineterror
30 }
31
32 method uint socket.connect
33 {
34 sockaddr_in saddr
35 uint he ret
36
37 //
38 saddr.sin_addr = inet_addr( this.host.ptr() )
39 if saddr.sin_addr == 0xFFFFFFFF
40 {
41 he = gethostbyname( this.host.ptr() )
42 if !he : return inet_seterror()
43 saddr.sin_addr = ( he->hostent.h_addr_list->uint)->uint
44 }
45 //
46 this.socket = createsocket( $AF_INET, $SOCK_STREAM, $IPPROTO_TCP )
47 if this.socket == $INVALID_SOCKET : return inet_seterror()
48
49 saddr.sin_family = $AF_INET
50 saddr.sin_port = htons( this.port )
51
52 //
53 ret = connect( this.socket, &saddr, sizeof( sockaddr ))
54 if ret == $SOCKET_ERROR
55 {
56 //
57 this.close( )
58 return inet_seterror()
59 }
60 return 1
61 }
62
63 method uint socket.recv( buf data )
64 {
65 uint ret
66
67 if data.use + 0x7FFF > data.size
68 {
69 data.expand( data.size + 0x7FFF )
70 }
71 ret = recv( this.socket, data.ptr() + data.use, 0x7FFF, 0 )
72 if ret == $SOCKET_ERROR
73 {
74 return inet_seterror()
75 }
76 data.use += ret
77 return 1
78 }
79
80 method uint socket.send( str data )
81 {
82 if send( this.socket, data.ptr(), *data, 0 ) == $SOCKET_ERROR
83 {
84 return inet_seterror()
85 }
86 return 1
87 }
88
89 method uint socket.send( buf data )
90 {
91 uint off last = *data
92 uint sent
93
94 while last
95 {
96 sent = send( this.socket, data.ptr() + off, last, 0 )
97 if sent == $SOCKET_ERROR
98 {
99 return inet_seterror()
100 }
101 last -= sent
102 off += sent
103 }
104 return 1
105 }