1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Purpose: GSocket main MSW file
6 * -------------------------------------------------------------------------
9 #if defined(__GSOCKET_STANDALONE__) || defined(wxUSE_SOCKETS)
11 #ifndef __GSOCKET_STANDALONE__
14 #include "wx/msw/gsockmsw.h"
15 #include "wx/gsocket.h"
17 #define INSTANCE wxhInstance
24 /* If not using wxWindows, a global var called hInst must
25 * be available and it must containt the app's instance
28 #define INSTANCE hInst
30 #endif /* __GSOCKET_STANDALONE__ */
42 #define CLASSNAME "_GSocket_Internal_Window_Class"
43 #define WINDOWNAME "_GSocket_Internal_Window_Name"
45 /* Maximum number of different GSocket objects at a given time.
46 * This value can be modified at will, but it CANNOT be greater
47 * than (0x7FFF - WM_USER + 1)
49 #define MAXSOCKETS 1024
51 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
52 #error "MAXSOCKETS is too big!"
56 /* Global variables */
58 extern HINSTANCE INSTANCE
;
60 static CRITICAL_SECTION critical
;
61 static GSocket
* socketList
[MAXSOCKETS
];
62 static int firstAvailable
;
64 /* Global initializers */
72 /* Create internal window for event notifications */
74 winClass
.lpfnWndProc
= _GSocket_Internal_WinProc
;
75 winClass
.cbClsExtra
= 0;
76 winClass
.cbWndExtra
= 0;
77 winClass
.hInstance
= INSTANCE
;
78 winClass
.hIcon
= (HICON
) NULL
;
79 winClass
.hCursor
= (HCURSOR
) NULL
;
80 winClass
.hbrBackground
= (HBRUSH
) NULL
;
81 winClass
.lpszMenuName
= (LPCTSTR
) NULL
;
82 winClass
.lpszClassName
= CLASSNAME
;
84 RegisterClass(&winClass
);
85 hWin
= CreateWindow(CLASSNAME
,
88 (HWND
) NULL
, (HMENU
) NULL
, INSTANCE
, (LPVOID
) NULL
);
90 if (!hWin
) return FALSE
;
92 /* Initialize socket list */
93 InitializeCriticalSection(&critical
);
95 for (i
= 0; i
< MAXSOCKETS
; i
++)
101 /* Initialize WinSocket */
102 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
105 void GSocket_Cleanup()
107 /* Destroy internal window */
109 UnregisterClass(CLASSNAME
, INSTANCE
);
111 /* Delete critical section */
112 DeleteCriticalSection(&critical
);
114 /* Cleanup WinSocket */
118 /* Constructors / Destructors */
120 GSocket
*GSocket_new()
125 if ((socket
= (GSocket
*) malloc(sizeof(GSocket
))) == NULL
)
128 socket
->m_fd
= INVALID_SOCKET
;
129 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
131 socket
->m_cbacks
[i
] = NULL
;
133 socket
->m_local
= NULL
;
134 socket
->m_peer
= NULL
;
135 socket
->m_error
= GSOCK_NOERROR
;
136 socket
->m_server
= FALSE
;
137 socket
->m_stream
= TRUE
;
138 socket
->m_non_blocking
= FALSE
;
139 socket
->m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
140 socket
->m_timeout
.tv_usec
= 0;
142 /* Allocate a new message number for this socket */
143 EnterCriticalSection(&critical
);
146 while (socketList
[i
] != NULL
)
148 i
= (i
+ 1) % MAXSOCKETS
;
150 if (i
== firstAvailable
) /* abort! */
153 LeaveCriticalSection(&critical
);
157 socketList
[i
] = socket
;
158 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
159 socket
->m_msgnumber
= (i
+ WM_USER
);
161 LeaveCriticalSection(&critical
);
166 void GSocket_destroy(GSocket
*socket
)
168 assert(socket
!= NULL
);
170 /* We don't want more event notifications; so first of all we
171 * remove the socket from the list (NOTE: we won't get a CLOSE
172 * event for this socket if it wasn't closed before).
174 EnterCriticalSection(&critical
);
175 socketList
[(socket
->m_msgnumber
- WM_USER
)] = NULL
;
176 LeaveCriticalSection(&critical
);
178 /* We check that the socket is really shutdowned */
179 if (socket
->m_fd
!= INVALID_SOCKET
)
180 GSocket_Shutdown(socket
);
182 /* We destroy private addresses */
184 GAddress_destroy(socket
->m_local
);
187 GAddress_destroy(socket
->m_peer
);
189 /* We destroy socket itself */
193 void GSocket_Shutdown(GSocket
*socket
)
197 assert(socket
!= NULL
);
199 /* If socket has been created, we shutdown it */
200 if (socket
->m_fd
!= INVALID_SOCKET
)
202 shutdown(socket
->m_fd
, 2);
203 closesocket(socket
->m_fd
);
204 socket
->m_fd
= INVALID_SOCKET
;
207 /* We disable GUI callbacks */
208 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
210 socket
->m_cbacks
[evt
] = NULL
;
213 _GSocket_Configure_Callbacks(socket
);
216 /* Address handling */
218 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
220 assert(socket
!= NULL
);
222 if (socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
)
224 socket
->m_error
= GSOCK_INVSOCK
;
225 return GSOCK_INVSOCK
;
228 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
230 socket
->m_error
= GSOCK_INVADDR
;
231 return GSOCK_INVADDR
;
235 GAddress_destroy(socket
->m_local
);
237 socket
->m_local
= GAddress_copy(address
);
239 return GSOCK_NOERROR
;
242 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
244 assert(socket
!= NULL
);
246 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
248 socket
->m_error
= GSOCK_INVADDR
;
249 return GSOCK_INVADDR
;
253 GAddress_destroy(socket
->m_peer
);
255 socket
->m_peer
= GAddress_copy(address
);
257 return GSOCK_NOERROR
;
260 GAddress
*GSocket_GetLocal(GSocket
*socket
)
263 struct sockaddr addr
;
266 assert(socket
!= NULL
);
269 return GAddress_copy(socket
->m_local
);
271 if (socket
->m_fd
== INVALID_SOCKET
)
273 socket
->m_error
= GSOCK_INVSOCK
;
279 if (getsockname(socket
->m_fd
, &addr
, &size
) == SOCKET_ERROR
)
281 socket
->m_error
= GSOCK_IOERR
;
285 address
= GAddress_new();
288 socket
->m_error
= GSOCK_MEMERR
;
291 if (_GAddress_translate_from(address
, &addr
, size
) != GSOCK_NOERROR
)
293 socket
->m_error
= GSOCK_MEMERR
;
294 GAddress_destroy(address
);
301 GAddress
*GSocket_GetPeer(GSocket
*socket
)
303 assert(socket
!= NULL
);
306 return GAddress_copy(socket
->m_peer
);
311 /* Server specific parts */
313 /* GSocket_SetServer:
314 * Sets up the socket as a server. It uses the "Local" field of GSocket.
315 * "Local" must be set by GSocket_SetLocal() before GSocket_SetServer()
316 * is called. Possible error codes are: GSOCK_INVSOCK if socket has not
317 * been initialized, GSOCK_INVADDR if the local address has not been
318 * defined and GSOCK_IOERR for other internal errors.
320 GSocketError
GSocket_SetServer(GSocket
*sck
)
326 if (sck
->m_fd
!= INVALID_SOCKET
)
328 sck
->m_error
= GSOCK_INVSOCK
;
329 return GSOCK_INVSOCK
;
334 sck
->m_error
= GSOCK_INVADDR
;
335 return GSOCK_INVADDR
;
338 /* Initialize all fields */
339 sck
->m_server
= TRUE
;
340 sck
->m_stream
= TRUE
;
341 sck
->m_oriented
= TRUE
;
343 /* Create the socket */
344 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
346 if (sck
->m_fd
== INVALID_SOCKET
)
348 sck
->m_error
= GSOCK_IOERR
;
352 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
353 _GSocket_Configure_Callbacks(sck
);
355 /* Bind the socket to the LOCAL address */
356 if (bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0)
358 closesocket(sck
->m_fd
);
359 sck
->m_fd
= INVALID_SOCKET
;
360 sck
->m_error
= GSOCK_IOERR
;
364 /* Enable listening up to 5 connections */
365 if (listen(sck
->m_fd
, 5) != 0)
367 closesocket(sck
->m_fd
);
368 sck
->m_fd
= INVALID_SOCKET
;
369 sck
->m_error
= GSOCK_IOERR
;
373 return GSOCK_NOERROR
;
376 /* GSocket_WaitConnection:
377 * Waits for an incoming client connection.
379 GSocket
*GSocket_WaitConnection(GSocket
*sck
)
386 /* If the socket has already been created, we exit immediately */
387 if (sck
->m_fd
== INVALID_SOCKET
|| !sck
->m_server
)
389 sck
->m_error
= GSOCK_INVSOCK
;
393 /* Create a GSocket object for the new connection */
394 connection
= GSocket_new();
398 sck
->m_error
= GSOCK_MEMERR
;
402 /* Wait for a connection (with timeout) */
403 if (_GSocket_Input_Timeout(sck
) == GSOCK_TIMEDOUT
)
405 GSocket_destroy(connection
);
406 /* sck->m_error set by _GSocket_Input_Timeout */
410 connection
->m_fd
= accept(sck
->m_fd
, NULL
, NULL
);
412 if (connection
->m_fd
== INVALID_SOCKET
)
414 if (WSAGetLastError() == WSAEWOULDBLOCK
)
415 sck
->m_error
= GSOCK_WOULDBLOCK
;
417 sck
->m_error
= GSOCK_IOERR
;
419 GSocket_destroy(connection
);
423 /* Initialize all fields */
424 connection
->m_server
= FALSE
;
425 connection
->m_stream
= TRUE
;
426 connection
->m_oriented
= TRUE
;
428 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
429 _GSocket_Configure_Callbacks(connection
);
434 /* Non oriented connections */
436 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
442 if (sck
->m_fd
!= INVALID_SOCKET
)
444 sck
->m_error
= GSOCK_INVSOCK
;
445 return GSOCK_INVSOCK
;
450 sck
->m_error
= GSOCK_INVADDR
;
451 return GSOCK_INVADDR
;
454 /* Initialize all fields */
455 sck
->m_stream
= FALSE
;
456 sck
->m_server
= FALSE
;
457 sck
->m_oriented
= FALSE
;
459 /* Create the socket */
460 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
462 if (sck
->m_fd
== INVALID_SOCKET
)
464 sck
->m_error
= GSOCK_IOERR
;
468 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
469 _GSocket_Configure_Callbacks(sck
);
471 /* Bind it to the LOCAL address */
472 if (bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0)
474 closesocket(sck
->m_fd
);
475 sck
->m_fd
= INVALID_SOCKET
;
476 sck
->m_error
= GSOCK_IOERR
;
480 return GSOCK_NOERROR
;
483 GSocketError
GSocket_SetBroadcast(GSocket
*sck
)
489 if (GSocket_SetNonOriented(sck
) != GSOCK_NOERROR
)
493 setsockopt(sck
->m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char FAR
*) &b
, sizeof(b
));
495 return GSOCK_NOERROR
;
498 /* Client specific parts */
501 * Establishes a client connection to a server using the "Peer"
502 * field of GSocket. "Peer" must be set by GSocket_SetPeer() before
503 * GSocket_Connect() is called. Possible error codes are GSOCK_INVSOCK,
504 * GSOCK_INVADDR, GSOCK_TIMEDOUT, GSOCK_WOULDBLOCK and GSOCK_IOERR.
505 * If a socket is nonblocking and Connect() returns GSOCK_WOULDBLOCK,
506 * the connection request can be completed later. Use GSocket_Select()
507 * to check or wait for a GSOCK_CONNECTION event.
509 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
516 if (sck
->m_fd
!= INVALID_SOCKET
)
518 sck
->m_error
= GSOCK_INVSOCK
;
519 return GSOCK_INVSOCK
;
524 sck
->m_error
= GSOCK_INVADDR
;
525 return GSOCK_INVADDR
;
528 /* Test whether we want the socket to be a stream (e.g. TCP) */
529 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
530 sck
->m_oriented
= TRUE
;
531 sck
->m_server
= FALSE
;
538 /* Create the socket */
539 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
, type
, 0);
541 if (sck
->m_fd
== INVALID_SOCKET
)
543 sck
->m_error
= GSOCK_IOERR
;
547 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
548 _GSocket_Configure_Callbacks(sck
);
550 /* Connect it to the PEER address, with a timeout (see below) */
551 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
553 if (ret
== SOCKET_ERROR
)
555 err
= WSAGetLastError();
557 /* If connect failed with EWOULDBLOCK and the GSocket object
558 * is in blocking mode, we select() for the specified timeout
559 * checking for writability to see if the connection request
562 if ((err
== WSAEWOULDBLOCK
) && (!sck
->m_non_blocking
))
564 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
566 closesocket(sck
->m_fd
);
567 sck
->m_fd
= INVALID_SOCKET
;
568 /* sck->m_error is set in _GSocket_Output_Timeout */
569 return GSOCK_TIMEDOUT
;
572 return GSOCK_NOERROR
;
575 /* If connect failed with EWOULDBLOCK and the GSocket object
576 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
577 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
578 * this way if the connection completes, a GSOCK_CONNECTION
579 * event will be generated, if enabled.
581 if ((err
== WSAEWOULDBLOCK
) && (sck
->m_non_blocking
))
583 sck
->m_error
= GSOCK_WOULDBLOCK
;
584 return GSOCK_WOULDBLOCK
;
587 /* If connect failed with an error other than EWOULDBLOCK,
588 * then the call to GSocket_Connect has failed.
590 closesocket(sck
->m_fd
);
591 sck
->m_fd
= INVALID_SOCKET
;
592 sck
->m_error
= GSOCK_IOERR
;
596 return GSOCK_NOERROR
;
601 /* Like recv(), send(), ... */
602 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
604 assert(socket
!= NULL
);
606 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
608 socket
->m_error
= GSOCK_INVSOCK
;
612 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
615 if (socket
->m_stream
)
616 return _GSocket_Recv_Stream(socket
, buffer
, size
);
618 return _GSocket_Recv_Dgram(socket
, buffer
, size
);
621 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
623 assert(socket
!= NULL
);
625 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
627 socket
->m_error
= GSOCK_INVSOCK
;
631 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
634 if (socket
->m_stream
)
635 return _GSocket_Send_Stream(socket
, buffer
, size
);
637 return _GSocket_Send_Dgram(socket
, buffer
, size
);
641 * Polls the socket to determine its status. This function will
642 * check for the events specified in the 'flags' parameter, and
643 * it will return a mask indicating which operations can be
644 * performed. This function won't block, regardless of the
645 * mode (blocking|nonblocking) of the socket.
647 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
649 fd_set readfds
, writefds
, exceptfds
;
651 GSocketEventFlags mask
;
653 assert(socket
!= NULL
);
655 if (socket
->m_fd
== INVALID_SOCKET
)
657 socket
->m_error
= GSOCK_INVSOCK
;
664 FD_SET(socket
->m_fd
, &readfds
);
665 FD_SET(socket
->m_fd
, &writefds
);
666 FD_SET(socket
->m_fd
, &exceptfds
);
670 select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
);
674 /* If select() says that the socket is readable, then we have
675 * no way to distinguish if that means 'data available' (to
676 * recv) or 'incoming connection' (to accept). The same goes
677 * for writability: we cannot distinguish between 'you can
678 * send data' and 'connection request completed'. So we will
679 * assume the following: if the flag was set upon entry,
680 * that means that the event was possible.
682 if (FD_ISSET(socket
->m_fd
, &readfds
))
684 mask
|= (flags
& GSOCK_CONNECTION_FLAG
);
685 mask
|= (flags
& GSOCK_INPUT_FLAG
);
687 if (FD_ISSET(socket
->m_fd
, &writefds
))
689 mask
|= (flags
& GSOCK_CONNECTION_FLAG
);
690 mask
|= (flags
& GSOCK_OUTPUT_FLAG
);
692 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
693 mask
|= (flags
& GSOCK_LOST_FLAG
);
700 /* GSocket_SetNonBlocking:
701 * Sets the socket to non-blocking mode. This is useful if
702 * we don't want to wait.
704 void GSocket_SetNonBlocking(GSocket
*socket
, bool non_block
)
706 assert(socket
!= NULL
);
708 socket
->m_non_blocking
= non_block
;
711 /* GSocket_SetTimeout:
712 * Sets the timeout for blocking calls. Time is
713 * expressed in milliseconds.
715 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisecs
)
717 assert(socket
!= NULL
);
719 socket
->m_timeout
.tv_sec
= (millisecs
/ 1000);
720 socket
->m_timeout
.tv_usec
= (millisecs
% 1000) * 1000;
724 * Returns the last error occured for this socket.
726 GSocketError
GSocket_GetError(GSocket
*socket
)
728 assert(socket
!= NULL
);
730 return socket
->m_error
;
735 /* Only one callback is possible for each event (INPUT, OUTPUT, CONNECTION
736 * and LOST). The callbacks are called in the following situations:
738 * INPUT: There is at least one byte in the input buffer
739 * OUTPUT: The system is sure that the next write call will not block
740 * CONNECTION: Two cases are possible:
741 * Client socket -> the connection is established
742 * Server socket -> a client requests a connection
743 * LOST: The connection is lost
745 * An event is generated only once and its state is reseted when the
746 * relative IO call is requested.
747 * For example: INPUT -> GSocket_Read()
748 * CONNECTION -> GSocket_Accept()
751 /* GSocket_SetCallback:
752 * Enables the callbacks specified by 'flags'. Note that 'flags'
753 * may be a combination of flags OR'ed toghether, so the same
754 * callback function can be made to accept different events.
755 * The callback function must have the following prototype:
757 * void function(GSocket *socket, GSocketEvent event, char *cdata)
759 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
760 GSocketCallback callback
, char *cdata
)
764 assert (socket
!= NULL
);
766 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
768 /* We test each flag and enable the corresponding events */
769 if ((flags
& (1 << count
)) != 0)
771 socket
->m_cbacks
[count
] = callback
;
772 socket
->m_data
[count
] = cdata
;
776 _GSocket_Configure_Callbacks(socket
);
779 /* GSocket_UnsetCallback:
780 * Disables all callbacks specified by 'flags', which may be a
781 * combination of flags OR'ed toghether.
783 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
787 assert(socket
!= NULL
);
789 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
791 /* We test each flag and disable the corresponding events */
792 if ((flags
& (1 << count
)) != 0)
794 socket
->m_cbacks
[count
] = NULL
;
798 _GSocket_Configure_Callbacks(socket
);
804 void _GSocket_Configure_Callbacks(GSocket
*socket
)
809 if (socket
->m_fd
== INVALID_SOCKET
)
812 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
814 if (socket
->m_cbacks
[count
] != NULL
)
818 case GSOCK_INPUT
: mask
|= FD_READ
; break;
819 case GSOCK_OUTPUT
: mask
|= FD_WRITE
; break;
820 case GSOCK_CONNECTION
: mask
|= (FD_ACCEPT
| FD_CONNECT
); break;
821 case GSOCK_LOST
: mask
|= FD_CLOSE
; break;
826 WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, mask
);
829 LRESULT CALLBACK
_GSocket_Internal_WinProc(HWND hWnd
,
836 GSocketCallback cback
;
838 if (uMsg
>= WM_USER
&& uMsg
<= (WM_USER
+ MAXSOCKETS
- 1))
840 EnterCriticalSection(&critical
);
841 socket
= socketList
[(uMsg
- WM_USER
)];
845 /* Check that the socket still exists (it has not been
846 * destroyed) and for safety, check that the m_fd field
847 * is what we expect it to be.
849 if ((socket
!= NULL
) && (socket
->m_fd
== wParam
))
851 switch WSAGETSELECTEVENT(lParam
)
853 case FD_READ
: event
= GSOCK_INPUT
; break;
854 case FD_WRITE
: event
= GSOCK_OUTPUT
; break;
855 case FD_ACCEPT
: event
= GSOCK_CONNECTION
; break;
858 if (WSAGETSELECTERROR(lParam
) != 0)
861 event
= GSOCK_CONNECTION
;
864 case FD_CLOSE
: event
= GSOCK_LOST
; break;
868 cback
= socket
->m_cbacks
[event
];
871 /* OK, we can now leave the critical section because we have
872 * already obtained the callback address (we make no further
873 * accesses to socket->whatever)
875 LeaveCriticalSection(&critical
);
878 (cback
)(socket
, event
, socket
->m_data
[event
]);
883 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
887 /* _GSocket_Input_Timeout:
888 * For blocking sockets, wait until data is available or
889 * until timeout ellapses.
891 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
895 if (!socket
->m_non_blocking
)
898 FD_SET(socket
->m_fd
, &readfds
);
899 if (select(0, &readfds
, NULL
, NULL
, &socket
->m_timeout
) == 0)
901 socket
->m_error
= GSOCK_TIMEDOUT
;
902 return GSOCK_TIMEDOUT
;
905 return GSOCK_NOERROR
;
908 /* _GSocket_Output_Timeout:
909 * For blocking sockets, wait until data can be sent without
910 * blocking or until timeout ellapses.
912 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
916 if (!socket
->m_non_blocking
)
919 FD_SET(socket
->m_fd
, &writefds
);
920 if (select(0, NULL
, &writefds
, NULL
, &socket
->m_timeout
) == 0)
922 socket
->m_error
= GSOCK_TIMEDOUT
;
923 return GSOCK_TIMEDOUT
;
926 return GSOCK_NOERROR
;
929 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
933 ret
= recv(socket
->m_fd
, buffer
, size
, 0);
935 if (ret
== SOCKET_ERROR
)
937 if (WSAGetLastError() != WSAEWOULDBLOCK
)
938 socket
->m_error
= GSOCK_IOERR
;
940 socket
->m_error
= GSOCK_WOULDBLOCK
;
948 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
950 struct sockaddr from
;
954 fromlen
= sizeof(from
);
956 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, &fromlen
);
958 if (ret
== SOCKET_ERROR
)
960 if (WSAGetLastError() != WSAEWOULDBLOCK
)
961 socket
->m_error
= GSOCK_IOERR
;
963 socket
->m_error
= GSOCK_WOULDBLOCK
;
968 /* Translate a system address into a GSocket address */
971 socket
->m_peer
= GAddress_new();
974 socket
->m_error
= GSOCK_MEMERR
;
978 if (_GAddress_translate_from(socket
->m_peer
, &from
, fromlen
) != GSOCK_NOERROR
)
980 socket
->m_error
= GSOCK_MEMERR
;
981 GAddress_destroy(socket
->m_peer
);
988 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
992 ret
= send(socket
->m_fd
, buffer
, size
, 0);
994 if (ret
== SOCKET_ERROR
)
996 if (WSAGetLastError() != WSAEWOULDBLOCK
)
997 socket
->m_error
= GSOCK_IOERR
;
999 socket
->m_error
= GSOCK_WOULDBLOCK
;
1006 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1008 struct sockaddr
*addr
;
1011 if (!socket
->m_peer
)
1013 socket
->m_error
= GSOCK_INVADDR
;
1017 if (!_GAddress_translate_to(socket
->m_peer
, &addr
, &len
))
1019 socket
->m_error
= GSOCK_MEMERR
;
1023 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1025 /* Frees memory allocated by _GAddress_translate_to */
1028 if (ret
== SOCKET_ERROR
)
1030 if (WSAGetLastError() != WSAEWOULDBLOCK
)
1031 socket
->m_error
= GSOCK_IOERR
;
1033 socket
->m_error
= GSOCK_WOULDBLOCK
;
1042 * -------------------------------------------------------------------------
1044 * -------------------------------------------------------------------------
1047 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1048 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1049 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1051 #define CHECK_ADDRESS(address, family, retval) \
1053 if (address->m_family == GSOCK_NOFAMILY) \
1054 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1055 return address->m_error; \
1056 if (address->m_family != GSOCK_##family) \
1058 address->m_error = GSOCK_INVADDR; \
1063 GAddress
*GAddress_new()
1067 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1070 address
->m_family
= GSOCK_NOFAMILY
;
1071 address
->m_addr
= NULL
;
1077 GAddress
*GAddress_copy(GAddress
*address
)
1081 assert(address
!= NULL
);
1083 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1086 memcpy(addr2
, address
, sizeof(GAddress
));
1088 if (address
->m_addr
)
1090 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1091 if (addr2
->m_addr
== NULL
)
1096 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1102 void GAddress_destroy(GAddress
*address
)
1104 assert(address
!= NULL
);
1109 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1111 assert(address
!= NULL
);
1113 address
->m_family
= type
;
1116 GAddressType
GAddress_GetFamily(GAddress
*address
)
1118 assert(address
!= NULL
);
1120 return address
->m_family
;
1123 GSocketError
_GAddress_translate_from(GAddress
*address
,
1124 struct sockaddr
*addr
, int len
)
1126 address
->m_realfamily
= addr
->sa_family
;
1127 switch (addr
->sa_family
)
1130 address
->m_family
= GSOCK_INET
;
1133 address
->m_family
= GSOCK_UNIX
;
1137 address
->m_family
= GSOCK_INET6
;
1142 address
->m_error
= GSOCK_INVOP
;
1147 if (address
->m_addr
)
1148 free(address
->m_addr
);
1150 address
->m_len
= len
;
1151 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1153 if (address
->m_addr
== NULL
)
1155 address
->m_error
= GSOCK_MEMERR
;
1156 return GSOCK_MEMERR
;
1158 memcpy(address
->m_addr
, addr
, len
);
1160 return GSOCK_NOERROR
;
1163 GSocketError
_GAddress_translate_to(GAddress
*address
,
1164 struct sockaddr
**addr
, int *len
)
1166 if (!address
->m_addr
)
1168 address
->m_error
= GSOCK_INVADDR
;
1169 return GSOCK_INVADDR
;
1172 *len
= address
->m_len
;
1173 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1176 address
->m_error
= GSOCK_MEMERR
;
1177 return GSOCK_MEMERR
;
1180 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1181 return GSOCK_NOERROR
;
1185 * -------------------------------------------------------------------------
1186 * Internet address family
1187 * -------------------------------------------------------------------------
1190 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1192 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1193 if (address
->m_addr
== NULL
)
1195 address
->m_error
= GSOCK_MEMERR
;
1196 return GSOCK_MEMERR
;
1199 address
->m_len
= sizeof(struct sockaddr_in
);
1200 address
->m_family
= GSOCK_INET
;
1201 address
->m_realfamily
= PF_INET
;
1202 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1203 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1205 return GSOCK_NOERROR
;
1208 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1211 struct in_addr
*addr
;
1213 assert(address
!= NULL
);
1215 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1217 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1219 addr
->s_addr
= inet_addr(hostname
);
1221 /* If it is a numeric host name, convert it now */
1222 if (addr
->s_addr
== INADDR_NONE
)
1224 struct in_addr
*array_addr
;
1226 /* It is a real name, we solve it */
1227 if ((he
= gethostbyname(hostname
)) == NULL
)
1229 address
->m_error
= GSOCK_NOHOST
;
1230 return GSOCK_NOHOST
;
1232 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1233 addr
->s_addr
= array_addr
[0].s_addr
;
1235 return GSOCK_NOERROR
;
1238 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1239 unsigned long hostaddr
)
1241 struct in_addr
*addr
;
1243 assert(address
!= NULL
);
1245 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1247 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1248 addr
->s_addr
= hostaddr
;
1250 return GSOCK_NOERROR
;
1253 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1254 const char *protocol
)
1257 struct sockaddr_in
*addr
;
1259 assert(address
!= NULL
);
1260 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1264 address
->m_error
= GSOCK_INVPORT
;
1268 se
= getservbyname(port
, protocol
);
1271 if (isdigit(port
[0]))
1275 port_int
= atoi(port
);
1276 addr
= (struct sockaddr_in
*)address
->m_addr
;
1277 addr
->sin_port
= htons((u_short
) port_int
);
1278 return GSOCK_NOERROR
;
1281 address
->m_error
= GSOCK_INVPORT
;
1282 return GSOCK_INVPORT
;
1285 addr
= (struct sockaddr_in
*)address
->m_addr
;
1286 addr
->sin_port
= se
->s_port
;
1288 return GSOCK_NOERROR
;
1291 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1293 struct sockaddr_in
*addr
;
1295 assert(address
!= NULL
);
1296 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1298 addr
= (struct sockaddr_in
*)address
->m_addr
;
1299 addr
->sin_port
= htons(port
);
1301 return GSOCK_NOERROR
;
1304 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1308 struct sockaddr_in
*addr
;
1310 assert(address
!= NULL
);
1311 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1313 addr
= (struct sockaddr_in
*)address
->m_addr
;
1314 addr_buf
= (char *)&(addr
->sin_addr
);
1316 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1319 address
->m_error
= GSOCK_NOHOST
;
1320 return GSOCK_NOHOST
;
1323 strncpy(hostname
, he
->h_name
, sbuf
);
1325 return GSOCK_NOERROR
;
1328 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1330 struct sockaddr_in
*addr
;
1332 assert(address
!= NULL
);
1333 CHECK_ADDRESS(address
, INET
, 0);
1335 addr
= (struct sockaddr_in
*)address
->m_addr
;
1337 return addr
->sin_addr
.s_addr
;
1340 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1342 struct sockaddr_in
*addr
;
1344 assert(address
!= NULL
);
1345 CHECK_ADDRESS(address
, INET
, 0);
1347 addr
= (struct sockaddr_in
*)address
->m_addr
;
1348 return ntohs(addr
->sin_port
);
1352 * -------------------------------------------------------------------------
1353 * Unix address family
1354 * -------------------------------------------------------------------------
1357 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1359 assert (address
!= NULL
);
1360 address
->m_error
= GSOCK_INVADDR
;
1361 return GSOCK_INVADDR
;
1364 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1366 assert (address
!= NULL
);
1367 address
->m_error
= GSOCK_INVADDR
;
1368 return GSOCK_INVADDR
;
1371 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1373 assert (address
!= NULL
);
1374 address
->m_error
= GSOCK_INVADDR
;
1375 return GSOCK_INVADDR
;
1379 #endif /* defined(__GSOCKET_STANDALONE__) || defined(wxUSE_SOCKETS) */
1384 /* Diferencias con la version Unix:
1385 * - El descriptor es SOCKET y no int
1386 * - Constantes -1 pasan a INVALID_SOCKET
1387 * - Errores en muchas funciones pasan de -1 o <0 a SOCKET_ERROR
1388 * - ioctl y close pasan a ioctlsocket y closesocket
1389 * - inet_addr en lugar de inet_aton
1390 * - Codigo de inicializacion y terminacion para inicializar y
1391 * terminar WinSocket y para la ventana interna.
1392 * - SetTimeout en la version MSW simplemente guarda el valor en
1393 * socket.m_timeout, por tanto no hay necesidad de llamar a
1394 * SetTimeout cada vez que se crea realmente un socket (no
1396 * - Lo mismo para SetNonBlocking.