1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
4 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
5 * Purpose: GSocket main MSW file
7 * -------------------------------------------------------------------------
11 * PLEASE don't put C++ comments here - this is a C source file.
14 #ifndef __GSOCKET_STANDALONE__
18 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
20 #ifndef __GSOCKET_STANDALONE__
22 #include "wx/msw/gsockmsw.h"
23 #include "wx/gsocket.h"
25 #define INSTANCE wxGetInstance()
32 /* If not using wxWindows, a global var called hInst must
33 * be available and it must containt the app's instance
36 #define INSTANCE hInst
38 #endif /* __GSOCKET_STANDALONE__ */
50 #define CLASSNAME "_GSocket_Internal_Window_Class"
51 #define WINDOWNAME "_GSocket_Internal_Window_Name"
53 /* Maximum number of different GSocket objects at a given time.
54 * This value can be modified at will, but it CANNOT be greater
55 * than (0x7FFF - WM_USER + 1)
57 #define MAXSOCKETS 1024
59 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
60 #error "MAXSOCKETS is too big!"
64 /* Global variables */
66 extern HINSTANCE INSTANCE
;
68 static CRITICAL_SECTION critical
;
69 static GSocket
* socketList
[MAXSOCKETS
];
70 static int firstAvailable
;
72 /* Global initializers */
80 /* Create internal window for event notifications */
82 winClass
.lpfnWndProc
= _GSocket_Internal_WinProc
;
83 winClass
.cbClsExtra
= 0;
84 winClass
.cbWndExtra
= 0;
85 winClass
.hInstance
= INSTANCE
;
86 winClass
.hIcon
= (HICON
) NULL
;
87 winClass
.hCursor
= (HCURSOR
) NULL
;
88 winClass
.hbrBackground
= (HBRUSH
) NULL
;
89 winClass
.lpszMenuName
= (LPCTSTR
) NULL
;
90 winClass
.lpszClassName
= CLASSNAME
;
92 RegisterClass(&winClass
);
93 hWin
= CreateWindow(CLASSNAME
,
96 (HWND
) NULL
, (HMENU
) NULL
, INSTANCE
, (LPVOID
) NULL
);
98 if (!hWin
) return FALSE
;
100 /* Initialize socket list */
101 InitializeCriticalSection(&critical
);
103 for (i
= 0; i
< MAXSOCKETS
; i
++)
105 socketList
[i
] = NULL
;
109 /* Initialize WinSocket */
110 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
113 void GSocket_Cleanup()
115 /* Destroy internal window */
117 UnregisterClass(CLASSNAME
, INSTANCE
);
119 /* Delete critical section */
120 DeleteCriticalSection(&critical
);
122 /* Cleanup WinSocket */
126 /* Constructors / Destructors for GSocket */
128 GSocket
*GSocket_new()
133 if ((socket
= (GSocket
*) malloc(sizeof(GSocket
))) == NULL
)
136 socket
->m_fd
= INVALID_SOCKET
;
137 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
139 socket
->m_cbacks
[i
] = NULL
;
141 socket
->m_local
= NULL
;
142 socket
->m_peer
= NULL
;
143 socket
->m_error
= GSOCK_NOERROR
;
144 socket
->m_server
= FALSE
;
145 socket
->m_stream
= TRUE
;
146 socket
->m_non_blocking
= FALSE
;
147 socket
->m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
148 socket
->m_timeout
.tv_usec
= 0;
149 socket
->m_detected
= 0;
151 /* Allocate a new message number for this socket */
152 EnterCriticalSection(&critical
);
155 while (socketList
[i
] != NULL
)
157 i
= (i
+ 1) % MAXSOCKETS
;
159 if (i
== firstAvailable
) /* abort! */
162 LeaveCriticalSection(&critical
);
166 socketList
[i
] = socket
;
167 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
168 socket
->m_msgnumber
= (i
+ WM_USER
);
170 LeaveCriticalSection(&critical
);
175 void GSocket_destroy(GSocket
*socket
)
177 assert(socket
!= NULL
);
179 /* Remove the socket from the list */
180 EnterCriticalSection(&critical
);
181 socketList
[(socket
->m_msgnumber
- WM_USER
)] = NULL
;
182 LeaveCriticalSection(&critical
);
184 /* Check that the socket is really shutdowned */
185 if (socket
->m_fd
!= INVALID_SOCKET
)
186 GSocket_Shutdown(socket
);
188 /* Destroy private addresses */
190 GAddress_destroy(socket
->m_local
);
193 GAddress_destroy(socket
->m_peer
);
195 /* Destroy the socket itself */
200 * Disallow further read/write operations on this socket, close
201 * the fd and disable all callbacks.
203 void GSocket_Shutdown(GSocket
*socket
)
207 assert(socket
!= NULL
);
209 /* If socket has been created, shutdown it */
210 if (socket
->m_fd
!= INVALID_SOCKET
)
212 shutdown(socket
->m_fd
, 2);
213 closesocket(socket
->m_fd
);
214 socket
->m_fd
= INVALID_SOCKET
;
217 /* Disable GUI callbacks */
218 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
219 socket
->m_cbacks
[evt
] = NULL
;
221 socket
->m_detected
= 0;
222 _GSocket_Disable_Events(socket
);
225 /* Address handling */
231 * Set or get the local or peer address for this socket. The 'set'
232 * functions return GSOCK_NOERROR on success, an error code otherwise.
233 * The 'get' functions return a pointer to a GAddress object on success,
234 * or NULL otherwise, in which case they set the error code of the
235 * corresponding GSocket.
238 * GSOCK_INVSOCK - the socket is not valid.
239 * GSOCK_INVADDR - the address is not valid.
241 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
243 assert(socket
!= NULL
);
245 /* the socket must be initialized, or it must be a server */
246 if (socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
)
248 socket
->m_error
= GSOCK_INVSOCK
;
249 return GSOCK_INVSOCK
;
253 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
255 socket
->m_error
= GSOCK_INVADDR
;
256 return GSOCK_INVADDR
;
260 GAddress_destroy(socket
->m_local
);
262 socket
->m_local
= GAddress_copy(address
);
264 return GSOCK_NOERROR
;
267 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
269 assert(socket
!= NULL
);
272 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
274 socket
->m_error
= GSOCK_INVADDR
;
275 return GSOCK_INVADDR
;
279 GAddress_destroy(socket
->m_peer
);
281 socket
->m_peer
= GAddress_copy(address
);
283 return GSOCK_NOERROR
;
286 GAddress
*GSocket_GetLocal(GSocket
*socket
)
289 struct sockaddr addr
;
290 SOCKLEN_T size
= sizeof(addr
);
293 assert(socket
!= NULL
);
295 /* try to get it from the m_local var first */
297 return GAddress_copy(socket
->m_local
);
299 /* else, if the socket is initialized, try getsockname */
300 if (socket
->m_fd
== INVALID_SOCKET
)
302 socket
->m_error
= GSOCK_INVSOCK
;
306 if (getsockname(socket
->m_fd
, &addr
, &size
) == SOCKET_ERROR
)
308 socket
->m_error
= GSOCK_IOERR
;
312 /* got a valid address from getsockname, create a GAddress object */
313 if ((address
= GAddress_new()) == NULL
)
315 socket
->m_error
= GSOCK_MEMERR
;
319 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
321 GAddress_destroy(address
);
322 socket
->m_error
= err
;
329 GAddress
*GSocket_GetPeer(GSocket
*socket
)
331 assert(socket
!= NULL
);
333 /* try to get it from the m_peer var */
335 return GAddress_copy(socket
->m_peer
);
340 /* Server specific parts */
342 /* GSocket_SetServer:
343 * Sets up this socket as a server. The local address must have been
344 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
345 * Returns GSOCK_NOERROR on success, one of the following otherwise:
348 * GSOCK_INVSOCK - the socket is in use.
349 * GSOCK_INVADDR - the local address has not been set.
350 * GSOCK_IOERR - low-level error.
352 GSocketError
GSocket_SetServer(GSocket
*sck
)
358 /* must not be in use */
359 if (sck
->m_fd
!= INVALID_SOCKET
)
361 sck
->m_error
= GSOCK_INVSOCK
;
362 return GSOCK_INVSOCK
;
365 /* the local addr must have been set */
368 sck
->m_error
= GSOCK_INVADDR
;
369 return GSOCK_INVADDR
;
372 /* Initialize all fields */
373 sck
->m_server
= TRUE
;
374 sck
->m_stream
= TRUE
;
375 sck
->m_oriented
= TRUE
;
377 /* Create the socket */
378 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
380 if (sck
->m_fd
== INVALID_SOCKET
)
382 sck
->m_error
= GSOCK_IOERR
;
386 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
387 _GSocket_Enable_Events(sck
);
389 /* Bind to the local address,
390 * retrieve the actual address bound,
391 * and listen up to 5 connections.
393 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
394 (getsockname(sck
->m_fd
,
395 sck
->m_local
->m_addr
,
396 &sck
->m_local
->m_len
) != 0) ||
397 (listen(sck
->m_fd
, 5) != 0))
399 closesocket(sck
->m_fd
);
400 sck
->m_fd
= INVALID_SOCKET
;
401 sck
->m_error
= GSOCK_IOERR
;
405 return GSOCK_NOERROR
;
408 /* GSocket_WaitConnection:
409 * Waits for an incoming client connection. Returns a pointer to
410 * a GSocket object, or NULL if there was an error, in which case
411 * the last error field will be updated for the calling GSocket.
413 * Error codes (set in the calling GSocket)
414 * GSOCK_INVSOCK - the socket is not valid or not a server.
415 * GSOCK_TIMEDOUT - timeout, no incoming connections.
416 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
417 * GSOCK_MEMERR - couldn't allocate memory.
418 * GSOCK_IOERR - low-level error.
420 GSocket
*GSocket_WaitConnection(GSocket
*sck
)
423 struct sockaddr from
;
424 SOCKLEN_T fromlen
= sizeof(from
);
430 /* Reenable CONNECTION events */
431 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
433 /* If the socket has already been created, we exit immediately */
434 if (sck
->m_fd
== INVALID_SOCKET
|| !sck
->m_server
)
436 sck
->m_error
= GSOCK_INVSOCK
;
440 /* Create a GSocket object for the new connection */
441 connection
= GSocket_new();
445 sck
->m_error
= GSOCK_MEMERR
;
449 /* Wait for a connection (with timeout) */
450 if (_GSocket_Input_Timeout(sck
) == GSOCK_TIMEDOUT
)
452 GSocket_destroy(connection
);
453 /* sck->m_error set by _GSocket_Input_Timeout */
457 connection
->m_fd
= accept(sck
->m_fd
, &from
, &fromlen
);
459 if (connection
->m_fd
== INVALID_SOCKET
)
461 if (WSAGetLastError() == WSAEWOULDBLOCK
)
462 sck
->m_error
= GSOCK_WOULDBLOCK
;
464 sck
->m_error
= GSOCK_IOERR
;
466 GSocket_destroy(connection
);
470 /* Initialize all fields */
471 connection
->m_server
= FALSE
;
472 connection
->m_stream
= TRUE
;
473 connection
->m_oriented
= TRUE
;
475 /* Setup the peer address field */
476 connection
->m_peer
= GAddress_new();
477 if (!connection
->m_peer
)
479 GSocket_destroy(connection
);
480 sck
->m_error
= GSOCK_MEMERR
;
483 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
484 if (err
!= GSOCK_NOERROR
)
486 GAddress_destroy(connection
->m_peer
);
487 GSocket_destroy(connection
);
492 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
493 _GSocket_Enable_Events(connection
);
498 /* Client specific parts */
501 * For stream (connection oriented) sockets, GSocket_Connect() tries
502 * to establish a client connection to a server using the peer address
503 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
504 * connection has been succesfully established, or one of the error
505 * codes listed below. Note that for nonblocking sockets, a return
506 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
507 * request can be completed later; you should use GSocket_Select()
508 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
509 * corresponding asynchronous events.
511 * For datagram (non connection oriented) sockets, GSocket_Connect()
512 * just sets the peer address established with GSocket_SetPeer() as
513 * default destination.
516 * GSOCK_INVSOCK - the socket is in use or not valid.
517 * GSOCK_INVADDR - the peer address has not been established.
518 * GSOCK_TIMEDOUT - timeout, the connection failed.
519 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
520 * GSOCK_MEMERR - couldn't allocate memory.
521 * GSOCK_IOERR - low-level error.
523 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
530 /* Enable CONNECTION events (needed for nonblocking connections) */
531 sck
->m_detected
&= ~GSOCK_CONNECTION_FLAG
;
533 if (sck
->m_fd
!= INVALID_SOCKET
)
535 sck
->m_error
= GSOCK_INVSOCK
;
536 return GSOCK_INVSOCK
;
541 sck
->m_error
= GSOCK_INVADDR
;
542 return GSOCK_INVADDR
;
545 /* Streamed or dgram socket? */
546 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
547 sck
->m_oriented
= TRUE
;
548 sck
->m_server
= FALSE
;
550 /* Create the socket */
551 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
,
552 sck
->m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
554 if (sck
->m_fd
== INVALID_SOCKET
)
556 sck
->m_error
= GSOCK_IOERR
;
560 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
561 _GSocket_Enable_Events(sck
);
563 /* Connect it to the peer address, with a timeout (see below) */
564 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
566 if (ret
== SOCKET_ERROR
)
568 err
= WSAGetLastError();
570 /* If connect failed with EWOULDBLOCK and the GSocket object
571 * is in blocking mode, we select() for the specified timeout
572 * checking for writability to see if the connection request
575 if ((err
== WSAEWOULDBLOCK
) && (!sck
->m_non_blocking
))
577 err
= _GSocket_Connect_Timeout(sck
);
579 if (err
!= GSOCK_NOERROR
)
581 closesocket(sck
->m_fd
);
582 sck
->m_fd
= INVALID_SOCKET
;
583 /* sck->m_error is set in _GSocket_Connect_Timeout */
589 /* If connect failed with EWOULDBLOCK and the GSocket object
590 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
591 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
592 * this way if the connection completes, a GSOCK_CONNECTION
593 * event will be generated, if enabled.
595 if ((err
== WSAEWOULDBLOCK
) && (sck
->m_non_blocking
))
597 sck
->m_error
= GSOCK_WOULDBLOCK
;
598 return GSOCK_WOULDBLOCK
;
601 /* If connect failed with an error other than EWOULDBLOCK,
602 * then the call to GSocket_Connect() has failed.
604 closesocket(sck
->m_fd
);
605 sck
->m_fd
= INVALID_SOCKET
;
606 sck
->m_error
= GSOCK_IOERR
;
610 return GSOCK_NOERROR
;
613 /* Datagram sockets */
615 /* GSocket_SetNonOriented:
616 * Sets up this socket as a non-connection oriented (datagram) socket.
617 * Before using this function, the local address must have been set
618 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
619 * on success, or one of the following otherwise.
622 * GSOCK_INVSOCK - the socket is in use.
623 * GSOCK_INVADDR - the local address has not been set.
624 * GSOCK_IOERR - low-level error.
626 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
632 if (sck
->m_fd
!= INVALID_SOCKET
)
634 sck
->m_error
= GSOCK_INVSOCK
;
635 return GSOCK_INVSOCK
;
640 sck
->m_error
= GSOCK_INVADDR
;
641 return GSOCK_INVADDR
;
644 /* Initialize all fields */
645 sck
->m_stream
= FALSE
;
646 sck
->m_server
= FALSE
;
647 sck
->m_oriented
= FALSE
;
649 /* Create the socket */
650 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
652 if (sck
->m_fd
== INVALID_SOCKET
)
654 sck
->m_error
= GSOCK_IOERR
;
658 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
659 _GSocket_Enable_Events(sck
);
661 /* Bind to the local address,
662 * and retrieve the actual address bound.
664 if ((bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0) ||
665 (getsockname(sck
->m_fd
,
666 sck
->m_local
->m_addr
,
667 &sck
->m_local
->m_len
) != 0))
669 closesocket(sck
->m_fd
);
670 sck
->m_fd
= INVALID_SOCKET
;
671 sck
->m_error
= GSOCK_IOERR
;
675 return GSOCK_NOERROR
;
681 /* Like recv(), send(), ... */
682 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
686 assert(socket
!= NULL
);
688 /* Reenable INPUT events */
689 socket
->m_detected
&= ~GSOCK_INPUT_FLAG
;
691 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
693 socket
->m_error
= GSOCK_INVSOCK
;
697 /* If the socket is blocking, wait for data (with a timeout) */
698 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
702 if (socket
->m_stream
)
703 ret
= _GSocket_Recv_Stream(socket
, buffer
, size
);
705 ret
= _GSocket_Recv_Dgram(socket
, buffer
, size
);
707 if (ret
== SOCKET_ERROR
)
709 if (WSAGetLastError() != WSAEWOULDBLOCK
)
710 socket
->m_error
= GSOCK_IOERR
;
712 socket
->m_error
= GSOCK_WOULDBLOCK
;
719 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
723 assert(socket
!= NULL
);
725 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
727 socket
->m_error
= GSOCK_INVSOCK
;
731 /* If the socket is blocking, wait for writability (with a timeout) */
732 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
736 if (socket
->m_stream
)
737 ret
= _GSocket_Send_Stream(socket
, buffer
, size
);
739 ret
= _GSocket_Send_Dgram(socket
, buffer
, size
);
741 if (ret
== SOCKET_ERROR
)
743 if (WSAGetLastError() != WSAEWOULDBLOCK
)
744 socket
->m_error
= GSOCK_IOERR
;
746 socket
->m_error
= GSOCK_WOULDBLOCK
;
748 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
749 * does). Once the first OUTPUT event is received, users can assume
750 * that the socket is writable until a read operation fails. Only then
751 * will further OUTPUT events be posted.
753 socket
->m_detected
&= ~GSOCK_OUTPUT_FLAG
;
761 * Polls the socket to determine its status. This function will
762 * check for the events specified in the 'flags' parameter, and
763 * it will return a mask indicating which operations can be
764 * performed. This function won't block, regardless of the
765 * mode (blocking | nonblocking) of the socket.
767 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
769 GSocketEventFlags result
= 0;
772 assert(socket
!= NULL
);
774 result
= flags
& socket
->m_detected
;
776 if ((flags
& GSOCK_INPUT_FLAG
) &&
777 (recv(socket
->m_fd
, &c
, 1, MSG_PEEK
) > 0))
779 result
|= GSOCK_INPUT_FLAG
;
787 /* GSocket_SetNonBlocking:
788 * Sets the socket to non-blocking mode. All IO calls will return
791 void GSocket_SetNonBlocking(GSocket
*socket
, bool non_block
)
793 assert(socket
!= NULL
);
795 socket
->m_non_blocking
= non_block
;
798 /* GSocket_SetTimeout:
799 * Sets the timeout for blocking calls. Time is expressed in
802 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millis
)
804 assert(socket
!= NULL
);
806 socket
->m_timeout
.tv_sec
= (millis
/ 1000);
807 socket
->m_timeout
.tv_usec
= (millis
% 1000) * 1000;
811 * Returns the last error occured for this socket. Note that successful
812 * operations do not clear this back to GSOCK_NOERROR, so use it only
815 GSocketError
GSocket_GetError(GSocket
*socket
)
817 assert(socket
!= NULL
);
819 return socket
->m_error
;
826 * There is data to be read in the input buffer. If, after a read
827 * operation, there is still data available, the callback function will
830 * The socket is available for writing. That is, the next write call
831 * won't block. This event is generated only once, when the connection is
832 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
833 * when the output buffer empties again. This means that the app should
834 * assume that it can write since the first OUTPUT event, and no more
835 * OUTPUT events will be generated unless an error occurs.
837 * Connection succesfully established, for client sockets, or incoming
838 * client connection, for server sockets. Wait for this event (also watch
839 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
841 * The connection is lost (or a connection request failed); this could
842 * be due to a failure, or due to the peer closing it gracefully.
845 /* GSocket_SetCallback:
846 * Enables the callbacks specified by 'flags'. Note that 'flags'
847 * may be a combination of flags OR'ed toghether, so the same
848 * callback function can be made to accept different events.
849 * The callback function must have the following prototype:
851 * void function(GSocket *socket, GSocketEvent event, char *cdata)
853 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
854 GSocketCallback callback
, char *cdata
)
858 assert(socket
!= NULL
);
860 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
862 if ((flags
& (1 << count
)) != 0)
864 socket
->m_cbacks
[count
] = callback
;
865 socket
->m_data
[count
] = cdata
;
870 /* GSocket_UnsetCallback:
871 * Disables all callbacks specified by 'flags', which may be a
872 * combination of flags OR'ed toghether.
874 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
878 assert(socket
!= NULL
);
880 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
882 if ((flags
& (1 << count
)) != 0)
884 socket
->m_cbacks
[count
] = NULL
;
885 socket
->m_data
[count
] = NULL
;
893 /* _GSocket_Enable_Events:
894 * Enable all event notifications; we need to be notified of all
895 * events for internal processing, but we will only notify users
896 * when an appropiate callback function has been installed.
898 void _GSocket_Enable_Events(GSocket
*socket
)
900 assert (socket
!= NULL
);
902 if (socket
->m_fd
!= INVALID_SOCKET
)
904 WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
,
905 FD_READ
| FD_WRITE
| FD_ACCEPT
| FD_CONNECT
| FD_CLOSE
);
909 /* _GSocket_Disable_Events:
910 * Disable event notifications (when shutdowning the socket)
912 void _GSocket_Disable_Events(GSocket
*socket
)
914 assert (socket
!= NULL
);
916 if (socket
->m_fd
!= INVALID_SOCKET
)
918 WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, 0);
923 LRESULT CALLBACK
_GSocket_Internal_WinProc(HWND hWnd
,
930 GSocketCallback cback
;
933 if (uMsg
>= WM_USER
&& uMsg
<= (WM_USER
+ MAXSOCKETS
- 1))
935 EnterCriticalSection(&critical
);
936 socket
= socketList
[(uMsg
- WM_USER
)];
941 /* Check that the socket still exists (it has not been
942 * destroyed) and for safety, check that the m_fd field
943 * is what we expect it to be.
945 if ((socket
!= NULL
) && (socket
->m_fd
== wParam
))
947 switch WSAGETSELECTEVENT(lParam
)
949 case FD_READ
: event
= GSOCK_INPUT
; break;
950 case FD_WRITE
: event
= GSOCK_OUTPUT
; break;
951 case FD_ACCEPT
: event
= GSOCK_CONNECTION
; break;
954 if (WSAGETSELECTERROR(lParam
) != 0)
957 event
= GSOCK_CONNECTION
;
960 case FD_CLOSE
: event
= GSOCK_LOST
; break;
965 cback
= socket
->m_cbacks
[event
];
966 data
= socket
->m_data
[event
];
968 if (event
== GSOCK_LOST
)
969 socket
->m_detected
= GSOCK_LOST_FLAG
;
971 socket
->m_detected
|= (1 << event
);
975 /* OK, we can now leave the critical section because we have
976 * already obtained the callback address (we make no further
977 * accesses to socket->whatever). However, the app should
978 * be prepared to handle events from a socket that has just
981 LeaveCriticalSection(&critical
);
984 (cback
)(socket
, event
, data
);
989 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
993 /* _GSocket_Input_Timeout:
994 * For blocking sockets, wait until data is available or
995 * until timeout ellapses.
997 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
1001 if (!socket
->m_non_blocking
)
1004 FD_SET(socket
->m_fd
, &readfds
);
1005 if (select(0, &readfds
, NULL
, NULL
, &socket
->m_timeout
) == 0)
1007 socket
->m_error
= GSOCK_TIMEDOUT
;
1008 return GSOCK_TIMEDOUT
;
1011 return GSOCK_NOERROR
;
1014 /* _GSocket_Output_Timeout:
1015 * For blocking sockets, wait until data can be sent without
1016 * blocking or until timeout ellapses.
1018 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
1022 if (!socket
->m_non_blocking
)
1025 FD_SET(socket
->m_fd
, &writefds
);
1026 if (select(0, NULL
, &writefds
, NULL
, &socket
->m_timeout
) == 0)
1028 socket
->m_error
= GSOCK_TIMEDOUT
;
1029 return GSOCK_TIMEDOUT
;
1032 return GSOCK_NOERROR
;
1035 /* _GSocket_Connect_Timeout:
1036 * For blocking sockets, wait until the connection is
1037 * established or fails, or until timeout ellapses.
1039 GSocketError
_GSocket_Connect_Timeout(GSocket
*socket
)
1044 if (!socket
->m_non_blocking
)
1047 FD_ZERO(&exceptfds
);
1048 FD_SET(socket
->m_fd
, &writefds
);
1049 FD_SET(socket
->m_fd
, &exceptfds
);
1050 if (select(0, NULL
, &writefds
, &exceptfds
, &socket
->m_timeout
) == 0)
1052 socket
->m_error
= GSOCK_TIMEDOUT
;
1053 return GSOCK_TIMEDOUT
;
1056 if (!FD_ISSET(socket
->m_fd
, &writefds
))
1058 socket
->m_error
= GSOCK_IOERR
;
1062 return GSOCK_NOERROR
;
1065 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
1067 return recv(socket
->m_fd
, buffer
, size
, 0);
1070 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
1072 struct sockaddr from
;
1073 SOCKLEN_T fromlen
= sizeof(from
);
1077 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1079 if (ret
== SOCKET_ERROR
)
1080 return SOCKET_ERROR
;
1082 /* Translate a system address into a GSocket address */
1083 if (!socket
->m_peer
)
1085 socket
->m_peer
= GAddress_new();
1086 if (!socket
->m_peer
)
1088 socket
->m_error
= GSOCK_MEMERR
;
1092 err
= _GAddress_translate_from(socket
->m_peer
, &from
, fromlen
);
1093 if (err
!= GSOCK_NOERROR
)
1095 GAddress_destroy(socket
->m_peer
);
1096 socket
->m_peer
= NULL
;
1097 socket
->m_error
= err
;
1104 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
1106 return send(socket
->m_fd
, buffer
, size
, 0);
1109 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1111 struct sockaddr
*addr
;
1115 if (!socket
->m_peer
)
1117 socket
->m_error
= GSOCK_INVADDR
;
1121 err
= _GAddress_translate_to(socket
->m_peer
, &addr
, &len
);
1122 if (err
!= GSOCK_NOERROR
)
1124 socket
->m_error
= err
;
1128 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1130 /* Frees memory allocated by _GAddress_translate_to */
1138 * -------------------------------------------------------------------------
1140 * -------------------------------------------------------------------------
1143 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1144 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1145 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1147 #define CHECK_ADDRESS(address, family, retval) \
1149 if (address->m_family == GSOCK_NOFAMILY) \
1150 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1151 return address->m_error; \
1152 if (address->m_family != GSOCK_##family) \
1154 address->m_error = GSOCK_INVADDR; \
1159 GAddress
*GAddress_new()
1163 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1166 address
->m_family
= GSOCK_NOFAMILY
;
1167 address
->m_addr
= NULL
;
1173 GAddress
*GAddress_copy(GAddress
*address
)
1177 assert(address
!= NULL
);
1179 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1182 memcpy(addr2
, address
, sizeof(GAddress
));
1184 if (address
->m_addr
)
1186 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1187 if (addr2
->m_addr
== NULL
)
1192 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1198 void GAddress_destroy(GAddress
*address
)
1200 assert(address
!= NULL
);
1205 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1207 assert(address
!= NULL
);
1209 address
->m_family
= type
;
1212 GAddressType
GAddress_GetFamily(GAddress
*address
)
1214 assert(address
!= NULL
);
1216 return address
->m_family
;
1219 GSocketError
_GAddress_translate_from(GAddress
*address
,
1220 struct sockaddr
*addr
, int len
)
1222 address
->m_realfamily
= addr
->sa_family
;
1223 switch (addr
->sa_family
)
1226 address
->m_family
= GSOCK_INET
;
1229 address
->m_family
= GSOCK_UNIX
;
1233 address
->m_family
= GSOCK_INET6
;
1238 address
->m_error
= GSOCK_INVOP
;
1243 if (address
->m_addr
)
1244 free(address
->m_addr
);
1246 address
->m_len
= len
;
1247 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1249 if (address
->m_addr
== NULL
)
1251 address
->m_error
= GSOCK_MEMERR
;
1252 return GSOCK_MEMERR
;
1254 memcpy(address
->m_addr
, addr
, len
);
1256 return GSOCK_NOERROR
;
1259 GSocketError
_GAddress_translate_to(GAddress
*address
,
1260 struct sockaddr
**addr
, int *len
)
1262 if (!address
->m_addr
)
1264 address
->m_error
= GSOCK_INVADDR
;
1265 return GSOCK_INVADDR
;
1268 *len
= address
->m_len
;
1269 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1272 address
->m_error
= GSOCK_MEMERR
;
1273 return GSOCK_MEMERR
;
1276 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1277 return GSOCK_NOERROR
;
1281 * -------------------------------------------------------------------------
1282 * Internet address family
1283 * -------------------------------------------------------------------------
1286 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1288 address
->m_len
= sizeof(struct sockaddr_in
);
1289 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1290 if (address
->m_addr
== NULL
)
1292 address
->m_error
= GSOCK_MEMERR
;
1293 return GSOCK_MEMERR
;
1296 address
->m_family
= GSOCK_INET
;
1297 address
->m_realfamily
= PF_INET
;
1298 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1299 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1301 return GSOCK_NOERROR
;
1304 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1307 struct in_addr
*addr
;
1309 assert(address
!= NULL
);
1311 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1313 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1315 addr
->s_addr
= inet_addr(hostname
);
1317 /* If it is a numeric host name, convert it now */
1318 if (addr
->s_addr
== INADDR_NONE
)
1320 struct in_addr
*array_addr
;
1322 /* It is a real name, we solve it */
1323 if ((he
= gethostbyname(hostname
)) == NULL
)
1325 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1326 address
->m_error
= GSOCK_NOHOST
;
1327 return GSOCK_NOHOST
;
1329 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1330 addr
->s_addr
= array_addr
[0].s_addr
;
1332 return GSOCK_NOERROR
;
1335 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1337 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1340 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1341 unsigned long hostaddr
)
1343 struct in_addr
*addr
;
1345 assert(address
!= NULL
);
1347 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1349 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1350 addr
->s_addr
= hostaddr
;
1352 return GSOCK_NOERROR
;
1355 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1356 const char *protocol
)
1359 struct sockaddr_in
*addr
;
1361 assert(address
!= NULL
);
1362 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1366 address
->m_error
= GSOCK_INVPORT
;
1367 return GSOCK_INVPORT
;
1370 se
= getservbyname(port
, protocol
);
1373 if (isdigit(port
[0]))
1377 port_int
= atoi(port
);
1378 addr
= (struct sockaddr_in
*)address
->m_addr
;
1379 addr
->sin_port
= htons((u_short
) port_int
);
1380 return GSOCK_NOERROR
;
1383 address
->m_error
= GSOCK_INVPORT
;
1384 return GSOCK_INVPORT
;
1387 addr
= (struct sockaddr_in
*)address
->m_addr
;
1388 addr
->sin_port
= se
->s_port
;
1390 return GSOCK_NOERROR
;
1393 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1395 struct sockaddr_in
*addr
;
1397 assert(address
!= NULL
);
1398 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1400 addr
= (struct sockaddr_in
*)address
->m_addr
;
1401 addr
->sin_port
= htons(port
);
1403 return GSOCK_NOERROR
;
1406 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1410 struct sockaddr_in
*addr
;
1412 assert(address
!= NULL
);
1413 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1415 addr
= (struct sockaddr_in
*)address
->m_addr
;
1416 addr_buf
= (char *)&(addr
->sin_addr
);
1418 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1421 address
->m_error
= GSOCK_NOHOST
;
1422 return GSOCK_NOHOST
;
1425 strncpy(hostname
, he
->h_name
, sbuf
);
1427 return GSOCK_NOERROR
;
1430 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1432 struct sockaddr_in
*addr
;
1434 assert(address
!= NULL
);
1435 CHECK_ADDRESS(address
, INET
, 0);
1437 addr
= (struct sockaddr_in
*)address
->m_addr
;
1439 return addr
->sin_addr
.s_addr
;
1442 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1444 struct sockaddr_in
*addr
;
1446 assert(address
!= NULL
);
1447 CHECK_ADDRESS(address
, INET
, 0);
1449 addr
= (struct sockaddr_in
*)address
->m_addr
;
1450 return ntohs(addr
->sin_port
);
1454 * -------------------------------------------------------------------------
1455 * Unix address family
1456 * -------------------------------------------------------------------------
1459 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1461 assert (address
!= NULL
);
1462 address
->m_error
= GSOCK_INVADDR
;
1463 return GSOCK_INVADDR
;
1466 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1468 assert (address
!= NULL
);
1469 address
->m_error
= GSOCK_INVADDR
;
1470 return GSOCK_INVADDR
;
1473 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1475 assert (address
!= NULL
);
1476 address
->m_error
= GSOCK_INVADDR
;
1477 return GSOCK_INVADDR
;
1480 #else /* !wxUSE_SOCKETS */
1483 * Translation unit shouldn't be empty, so include this typedef to make the
1484 * compiler (VC++ 6.0, for example) happy
1486 typedef (*wxDummy
)();
1488 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */