1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
3 * Name: src/msw/gsocket.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket main MSW file
8 * Licence: The wxWindows licence
10 * -------------------------------------------------------------------------
13 // For compilers that support precompilation, includes "wx.h".
14 #include "wx/wxprec.h"
21 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
22 * warning: conditional expression is constant.
24 # pragma warning(disable:4115)
26 * warning: named type definition in parentheses.
28 # pragma warning(disable:4127)
29 /* GAddress_UNIX_GetPath,
30 * warning: unreferenced formal parameter.
32 # pragma warning(disable:4100)
35 /* windows.h results in tons of warnings at max warning level */
37 # pragma warning(push, 1)
42 # pragma warning(disable:4514)
48 #if defined(__CYGWIN__)
49 //CYGWIN gives annoying warning about runtime stuff if we don't do this
50 # define USE_SYS_TYPES_FD_SET
51 # include <sys/types.h>
56 #ifndef __GSOCKET_STANDALONE__
57 # include "wx/platform.h"
60 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
62 #ifndef __GSOCKET_STANDALONE__
63 # include "wx/msw/gsockmsw.h"
64 # include "wx/gsocket.h"
66 # include "gsockmsw.h"
68 #endif /* __GSOCKET_STANDALONE__ */
75 #define isdigit(x) (x > 47 && x < 58)
77 #include "wx/msw/wince/net.h"
86 /* if we use configure for MSW WX_SOCKLEN_T will be already defined */
88 # define WX_SOCKLEN_T int
91 /* Table of GUI-related functions. We must call them indirectly because
92 * of wxBase and GUI separation: */
94 static GSocketGUIFunctionsTable
*gs_gui_functions
;
96 /* Global initialisers */
98 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
100 gs_gui_functions
= guifunc
;
103 int GSocket_Init(void)
107 if (!gs_gui_functions
)
109 static GSocketGUIFunctionsTableConcrete table
;
110 gs_gui_functions
= &table
;
112 if ( !gs_gui_functions
->OnInit() )
117 /* Initialize WinSocket */
118 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
121 void GSocket_Cleanup(void)
123 if (gs_gui_functions
)
125 gs_gui_functions
->OnExit();
128 /* Cleanup WinSocket */
132 /* Constructors / Destructors for GSocket */
138 m_fd
= INVALID_SOCKET
;
139 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
146 m_error
= GSOCK_NOERROR
;
149 m_non_blocking
= false;
150 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
151 m_timeout
.tv_usec
= 0;
152 m_establishing
= false;
157 assert(gs_gui_functions
);
158 /* Per-socket GUI-specific initialization */
159 m_ok
= gs_gui_functions
->Init_Socket(this);
162 void GSocket::Close()
164 gs_gui_functions
->Disable_Events(this);
166 m_fd
= INVALID_SOCKET
;
173 /* Per-socket GUI-specific cleanup */
174 gs_gui_functions
->Destroy_Socket(this);
176 /* Check that the socket is really shutdowned */
177 if (m_fd
!= INVALID_SOCKET
)
180 /* Destroy private addresses */
182 GAddress_destroy(m_local
);
185 GAddress_destroy(m_peer
);
189 * Disallow further read/write operations on this socket, close
190 * the fd and disable all callbacks.
192 void GSocket::Shutdown()
198 /* If socket has been created, shutdown it */
199 if (m_fd
!= INVALID_SOCKET
)
201 shutdown(m_fd
, 1 /* SD_SEND */);
205 /* Disable GUI callbacks */
206 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
207 m_cbacks
[evt
] = NULL
;
209 m_detected
= GSOCK_LOST_FLAG
;
212 /* Address handling */
218 * Set or get the local or peer address for this socket. The 'set'
219 * functions return GSOCK_NOERROR on success, an error code otherwise.
220 * The 'get' functions return a pointer to a GAddress object on success,
221 * or NULL otherwise, in which case they set the error code of the
222 * corresponding GSocket.
225 * GSOCK_INVSOCK - the socket is not valid.
226 * GSOCK_INVADDR - the address is not valid.
228 GSocketError
GSocket::SetLocal(GAddress
*address
)
232 /* the socket must be initialized, or it must be a server */
233 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
235 m_error
= GSOCK_INVSOCK
;
236 return GSOCK_INVSOCK
;
240 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
242 m_error
= GSOCK_INVADDR
;
243 return GSOCK_INVADDR
;
247 GAddress_destroy(m_local
);
249 m_local
= GAddress_copy(address
);
251 return GSOCK_NOERROR
;
254 GSocketError
GSocket::SetPeer(GAddress
*address
)
259 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
261 m_error
= GSOCK_INVADDR
;
262 return GSOCK_INVADDR
;
266 GAddress_destroy(m_peer
);
268 m_peer
= GAddress_copy(address
);
270 return GSOCK_NOERROR
;
273 GAddress
*GSocket::GetLocal()
276 struct sockaddr addr
;
277 WX_SOCKLEN_T size
= sizeof(addr
);
282 /* try to get it from the m_local var first */
284 return GAddress_copy(m_local
);
286 /* else, if the socket is initialized, try getsockname */
287 if (m_fd
== INVALID_SOCKET
)
289 m_error
= GSOCK_INVSOCK
;
293 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
295 m_error
= GSOCK_IOERR
;
299 /* got a valid address from getsockname, create a GAddress object */
300 if ((address
= GAddress_new()) == NULL
)
302 m_error
= GSOCK_MEMERR
;
306 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
308 GAddress_destroy(address
);
316 GAddress
*GSocket::GetPeer()
320 /* try to get it from the m_peer var */
322 return GAddress_copy(m_peer
);
327 /* Server specific parts */
329 /* GSocket_SetServer:
330 * Sets up this socket as a server. The local address must have been
331 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
332 * Returns GSOCK_NOERROR on success, one of the following otherwise:
335 * GSOCK_INVSOCK - the socket is in use.
336 * GSOCK_INVADDR - the local address has not been set.
337 * GSOCK_IOERR - low-level error.
339 GSocketError
GSocket::SetServer()
345 /* must not be in use */
346 if (m_fd
!= INVALID_SOCKET
)
348 m_error
= GSOCK_INVSOCK
;
349 return GSOCK_INVSOCK
;
352 /* the local addr must have been set */
355 m_error
= GSOCK_INVADDR
;
356 return GSOCK_INVADDR
;
359 /* Initialize all fields */
363 /* Create the socket */
364 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
366 if (m_fd
== INVALID_SOCKET
)
368 m_error
= GSOCK_IOERR
;
372 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
373 gs_gui_functions
->Enable_Events(this);
375 /* allow a socket to re-bind if the socket is in the TIME_WAIT
376 state after being previously closed.
380 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
383 /* Bind to the local address,
384 * retrieve the actual address bound,
385 * and listen up to 5 connections.
387 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
390 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
391 (listen(m_fd
, 5) != 0))
394 m_error
= GSOCK_IOERR
;
398 return GSOCK_NOERROR
;
401 /* GSocket_WaitConnection:
402 * Waits for an incoming client connection. Returns a pointer to
403 * a GSocket object, or NULL if there was an error, in which case
404 * the last error field will be updated for the calling GSocket.
406 * Error codes (set in the calling GSocket)
407 * GSOCK_INVSOCK - the socket is not valid or not a server.
408 * GSOCK_TIMEDOUT - timeout, no incoming connections.
409 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
410 * GSOCK_MEMERR - couldn't allocate memory.
411 * GSOCK_IOERR - low-level error.
413 GSocket
*GSocket::WaitConnection()
416 struct sockaddr from
;
417 WX_SOCKLEN_T fromlen
= sizeof(from
);
423 /* Reenable CONNECTION events */
424 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
426 /* If the socket has already been created, we exit immediately */
427 if (m_fd
== INVALID_SOCKET
|| !m_server
)
429 m_error
= GSOCK_INVSOCK
;
433 /* Create a GSocket object for the new connection */
434 connection
= GSocket_new();
438 m_error
= GSOCK_MEMERR
;
442 /* Wait for a connection (with timeout) */
443 if (Input_Timeout() == GSOCK_TIMEDOUT
)
446 /* m_error set by _GSocket_Input_Timeout */
450 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
452 if (connection
->m_fd
== INVALID_SOCKET
)
454 if (WSAGetLastError() == WSAEWOULDBLOCK
)
455 m_error
= GSOCK_WOULDBLOCK
;
457 m_error
= GSOCK_IOERR
;
463 /* Initialize all fields */
464 connection
->m_server
= false;
465 connection
->m_stream
= true;
467 /* Setup the peer address field */
468 connection
->m_peer
= GAddress_new();
469 if (!connection
->m_peer
)
472 m_error
= GSOCK_MEMERR
;
475 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
476 if (err
!= GSOCK_NOERROR
)
478 GAddress_destroy(connection
->m_peer
);
484 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
485 gs_gui_functions
->Enable_Events(connection
);
490 /* GSocket_SetReusable:
491 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
492 * make the appropriate setsockopt() call.
493 * Implemented as a GSocket function because clients (ie, wxSocketServer)
494 * don't have access to the GSocket struct information.
495 * Returns true if the flag was set correctly, false if an error occurred
496 * (ie, if the parameter was NULL)
498 bool GSocket::SetReusable()
500 /* socket must not be null, and must not be in use/already bound */
501 if (this && m_fd
== INVALID_SOCKET
) {
508 /* GSocket_SetBroadcast:
509 * Simply sets the m_broadcast flag on the socket. GSocket_SetServer will
510 * make the appropriate setsockopt() call.
511 * Implemented as a GSocket function because clients (ie, wxSocketServer)
512 * don't have access to the GSocket struct information.
513 * Returns true if the flag was set correctly, false if an error occurred
514 * (ie, if the parameter was NULL)
516 bool GSocket::SetBroadcast()
518 /* socket must not be in use/already bound */
519 if (m_fd
== INVALID_SOCKET
) {
526 bool GSocket::DontDoBind()
528 /* socket must not be in use/already bound */
529 if (m_fd
== INVALID_SOCKET
) {
536 /* Client specific parts */
539 * For stream (connection oriented) sockets, GSocket_Connect() tries
540 * to establish a client connection to a server using the peer address
541 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
542 * connection has been successfully established, or one of the error
543 * codes listed below. Note that for nonblocking sockets, a return
544 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
545 * request can be completed later; you should use GSocket_Select()
546 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
547 * corresponding asynchronous events.
549 * For datagram (non connection oriented) sockets, GSocket_Connect()
550 * just sets the peer address established with GSocket_SetPeer() as
551 * default destination.
554 * GSOCK_INVSOCK - the socket is in use or not valid.
555 * GSOCK_INVADDR - the peer address has not been established.
556 * GSOCK_TIMEDOUT - timeout, the connection failed.
557 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
558 * GSOCK_MEMERR - couldn't allocate memory.
559 * GSOCK_IOERR - low-level error.
561 GSocketError
GSocket::Connect(GSocketStream stream
)
568 /* Enable CONNECTION events (needed for nonblocking connections) */
569 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
571 if (m_fd
!= INVALID_SOCKET
)
573 m_error
= GSOCK_INVSOCK
;
574 return GSOCK_INVSOCK
;
579 m_error
= GSOCK_INVADDR
;
580 return GSOCK_INVADDR
;
583 /* Streamed or dgram socket? */
584 m_stream
= (stream
== GSOCK_STREAMED
);
586 m_establishing
= false;
588 /* Create the socket */
589 m_fd
= socket(m_peer
->m_realfamily
,
590 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
592 if (m_fd
== INVALID_SOCKET
)
594 m_error
= GSOCK_IOERR
;
598 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
599 gs_gui_functions
->Enable_Events(this);
601 // If the reuse flag is set, use the applicable socket reuse flag
604 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
607 // If a local address has been set, then we need to bind to it before calling connect
608 if (m_local
&& m_local
->m_addr
)
610 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
613 /* Connect it to the peer address, with a timeout (see below) */
614 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
616 if (ret
== SOCKET_ERROR
)
618 err
= WSAGetLastError();
620 /* If connect failed with EWOULDBLOCK and the GSocket object
621 * is in blocking mode, we select() for the specified timeout
622 * checking for writability to see if the connection request
625 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
627 err
= Connect_Timeout();
629 if (err
!= GSOCK_NOERROR
)
632 /* m_error is set in _GSocket_Connect_Timeout */
635 return (GSocketError
) err
;
638 /* If connect failed with EWOULDBLOCK and the GSocket object
639 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
640 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
641 * this way if the connection completes, a GSOCK_CONNECTION
642 * event will be generated, if enabled.
644 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
646 m_establishing
= true;
647 m_error
= GSOCK_WOULDBLOCK
;
648 return GSOCK_WOULDBLOCK
;
651 /* If connect failed with an error other than EWOULDBLOCK,
652 * then the call to GSocket_Connect() has failed.
655 m_error
= GSOCK_IOERR
;
659 return GSOCK_NOERROR
;
662 /* Datagram sockets */
664 /* GSocket_SetNonOriented:
665 * Sets up this socket as a non-connection oriented (datagram) socket.
666 * Before using this function, the local address must have been set
667 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
668 * on success, or one of the following otherwise.
671 * GSOCK_INVSOCK - the socket is in use.
672 * GSOCK_INVADDR - the local address has not been set.
673 * GSOCK_IOERR - low-level error.
675 GSocketError
GSocket::SetNonOriented()
681 if (m_fd
!= INVALID_SOCKET
)
683 m_error
= GSOCK_INVSOCK
;
684 return GSOCK_INVSOCK
;
689 m_error
= GSOCK_INVADDR
;
690 return GSOCK_INVADDR
;
693 /* Initialize all fields */
697 /* Create the socket */
698 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
700 if (m_fd
== INVALID_SOCKET
)
702 m_error
= GSOCK_IOERR
;
706 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
707 gs_gui_functions
->Enable_Events(this);
711 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
715 setsockopt(m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char*)&arg
, sizeof(arg
));
719 /* Bind to the local address,
720 * and retrieve the actual address bound.
722 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
725 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0))
728 m_error
= GSOCK_IOERR
;
733 return GSOCK_NOERROR
;
738 /* Like recv(), send(), ... */
739 int GSocket::Read(char *buffer
, int size
)
745 /* Reenable INPUT events */
746 m_detected
&= ~GSOCK_INPUT_FLAG
;
748 if (m_fd
== INVALID_SOCKET
|| m_server
)
750 m_error
= GSOCK_INVSOCK
;
754 /* If the socket is blocking, wait for data (with a timeout) */
755 if (Input_Timeout() == GSOCK_TIMEDOUT
)
757 m_error
= GSOCK_TIMEDOUT
;
763 ret
= Recv_Stream(buffer
, size
);
765 ret
= Recv_Dgram(buffer
, size
);
767 if (ret
== SOCKET_ERROR
)
769 if (WSAGetLastError() != WSAEWOULDBLOCK
)
770 m_error
= GSOCK_IOERR
;
772 m_error
= GSOCK_WOULDBLOCK
;
779 int GSocket::Write(const char *buffer
, int size
)
785 if (m_fd
== INVALID_SOCKET
|| m_server
)
787 m_error
= GSOCK_INVSOCK
;
791 /* If the socket is blocking, wait for writability (with a timeout) */
792 if (Output_Timeout() == GSOCK_TIMEDOUT
)
797 ret
= Send_Stream(buffer
, size
);
799 ret
= Send_Dgram(buffer
, size
);
801 if (ret
== SOCKET_ERROR
)
803 if (WSAGetLastError() != WSAEWOULDBLOCK
)
804 m_error
= GSOCK_IOERR
;
806 m_error
= GSOCK_WOULDBLOCK
;
808 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
809 * does). Once the first OUTPUT event is received, users can assume
810 * that the socket is writable until a read operation fails. Only then
811 * will further OUTPUT events be posted.
813 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
821 * Polls the socket to determine its status. This function will
822 * check for the events specified in the 'flags' parameter, and
823 * it will return a mask indicating which operations can be
824 * performed. This function won't block, regardless of the
825 * mode (blocking | nonblocking) of the socket.
827 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
829 if (!gs_gui_functions
->CanUseEventLoop())
831 GSocketEventFlags result
= 0;
841 FD_SET(m_fd
, &readfds
);
842 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
843 FD_SET(m_fd
, &writefds
);
844 FD_SET(m_fd
, &exceptfds
);
846 /* Check 'sticky' CONNECTION flag first */
847 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
849 /* If we have already detected a LOST event, then don't try
850 * to do any further processing.
852 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
854 m_establishing
= false;
856 return (GSOCK_LOST_FLAG
& flags
);
860 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
863 /* What to do here? */
864 return (result
& flags
);
867 /* Check for exceptions and errors */
868 if (FD_ISSET(m_fd
, &exceptfds
))
870 m_establishing
= false;
871 m_detected
= GSOCK_LOST_FLAG
;
873 /* LOST event: Abort any further processing */
874 return (GSOCK_LOST_FLAG
& flags
);
877 /* Check for readability */
878 if (FD_ISSET(m_fd
, &readfds
))
880 result
|= GSOCK_INPUT_FLAG
;
882 if (m_server
&& m_stream
)
884 /* This is a TCP server socket that detected a connection.
885 While the INPUT_FLAG is also set, it doesn't matter on
886 this kind of sockets, as we can only Accept() from them. */
887 result
|= GSOCK_CONNECTION_FLAG
;
888 m_detected
|= GSOCK_CONNECTION_FLAG
;
892 /* Check for writability */
893 if (FD_ISSET(m_fd
, &writefds
))
895 if (m_establishing
&& !m_server
)
898 WX_SOCKLEN_T len
= sizeof(error
);
900 m_establishing
= false;
902 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
906 m_detected
= GSOCK_LOST_FLAG
;
908 /* LOST event: Abort any further processing */
909 return (GSOCK_LOST_FLAG
& flags
);
913 result
|= GSOCK_CONNECTION_FLAG
;
914 m_detected
|= GSOCK_CONNECTION_FLAG
;
919 result
|= GSOCK_OUTPUT_FLAG
;
923 return (result
& flags
);
928 return flags
& m_detected
;
934 /* GSocket_SetNonBlocking:
935 * Sets the socket to non-blocking mode. All IO calls will return
938 void GSocket::SetNonBlocking(bool non_block
)
942 m_non_blocking
= non_block
;
945 /* GSocket_SetTimeout:
946 * Sets the timeout for blocking calls. Time is expressed in
949 void GSocket::SetTimeout(unsigned long millis
)
953 m_timeout
.tv_sec
= (millis
/ 1000);
954 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
958 * Returns the last error occurred for this socket. Note that successful
959 * operations do not clear this back to GSOCK_NOERROR, so use it only
962 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
972 * There is data to be read in the input buffer. If, after a read
973 * operation, there is still data available, the callback function will
976 * The socket is available for writing. That is, the next write call
977 * won't block. This event is generated only once, when the connection is
978 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
979 * when the output buffer empties again. This means that the app should
980 * assume that it can write since the first OUTPUT event, and no more
981 * OUTPUT events will be generated unless an error occurs.
983 * Connection successfully established, for client sockets, or incoming
984 * client connection, for server sockets. Wait for this event (also watch
985 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
987 * The connection is lost (or a connection request failed); this could
988 * be due to a failure, or due to the peer closing it gracefully.
991 /* GSocket_SetCallback:
992 * Enables the callbacks specified by 'flags'. Note that 'flags'
993 * may be a combination of flags OR'ed toghether, so the same
994 * callback function can be made to accept different events.
995 * The callback function must have the following prototype:
997 * void function(GSocket *socket, GSocketEvent event, char *cdata)
999 void GSocket::SetCallback(GSocketEventFlags flags
,
1000 GSocketCallback callback
, char *cdata
)
1006 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1008 if ((flags
& (1 << count
)) != 0)
1010 m_cbacks
[count
] = callback
;
1011 m_data
[count
] = cdata
;
1016 /* GSocket_UnsetCallback:
1017 * Disables all callbacks specified by 'flags', which may be a
1018 * combination of flags OR'ed toghether.
1020 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1026 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1028 if ((flags
& (1 << count
)) != 0)
1030 m_cbacks
[count
] = NULL
;
1031 m_data
[count
] = NULL
;
1036 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1037 void *optval
, int *optlen
)
1039 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1041 return GSOCK_NOERROR
;
1043 return GSOCK_OPTERR
;
1046 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1047 const void *optval
, int optlen
)
1049 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1051 return GSOCK_NOERROR
;
1053 return GSOCK_OPTERR
;
1056 /* Internals (IO) */
1058 /* _GSocket_Input_Timeout:
1059 * For blocking sockets, wait until data is available or
1060 * until timeout ellapses.
1062 GSocketError
GSocket::Input_Timeout()
1066 if (!m_non_blocking
)
1069 FD_SET(m_fd
, &readfds
);
1070 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1072 m_error
= GSOCK_TIMEDOUT
;
1073 return GSOCK_TIMEDOUT
;
1076 return GSOCK_NOERROR
;
1079 /* _GSocket_Output_Timeout:
1080 * For blocking sockets, wait until data can be sent without
1081 * blocking or until timeout ellapses.
1083 GSocketError
GSocket::Output_Timeout()
1087 if (!m_non_blocking
)
1090 FD_SET(m_fd
, &writefds
);
1091 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1093 m_error
= GSOCK_TIMEDOUT
;
1094 return GSOCK_TIMEDOUT
;
1097 return GSOCK_NOERROR
;
1100 /* _GSocket_Connect_Timeout:
1101 * For blocking sockets, wait until the connection is
1102 * established or fails, or until timeout ellapses.
1104 GSocketError
GSocket::Connect_Timeout()
1110 FD_ZERO(&exceptfds
);
1111 FD_SET(m_fd
, &writefds
);
1112 FD_SET(m_fd
, &exceptfds
);
1113 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1115 m_error
= GSOCK_TIMEDOUT
;
1116 return GSOCK_TIMEDOUT
;
1118 if (!FD_ISSET(m_fd
, &writefds
))
1120 m_error
= GSOCK_IOERR
;
1124 return GSOCK_NOERROR
;
1127 int GSocket::Recv_Stream(char *buffer
, int size
)
1129 return recv(m_fd
, buffer
, size
, 0);
1132 int GSocket::Recv_Dgram(char *buffer
, int size
)
1134 struct sockaddr from
;
1135 WX_SOCKLEN_T fromlen
= sizeof(from
);
1139 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1141 if (ret
== SOCKET_ERROR
)
1142 return SOCKET_ERROR
;
1144 /* Translate a system address into a GSocket address */
1147 m_peer
= GAddress_new();
1150 m_error
= GSOCK_MEMERR
;
1154 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1155 if (err
!= GSOCK_NOERROR
)
1157 GAddress_destroy(m_peer
);
1166 int GSocket::Send_Stream(const char *buffer
, int size
)
1168 return send(m_fd
, buffer
, size
, 0);
1171 int GSocket::Send_Dgram(const char *buffer
, int size
)
1173 struct sockaddr
*addr
;
1179 m_error
= GSOCK_INVADDR
;
1183 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1184 if (err
!= GSOCK_NOERROR
)
1190 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1192 /* Frees memory allocated by _GAddress_translate_to */
1198 /* Compatibility functions for GSocket */
1199 GSocket
*GSocket_new(void)
1201 GSocket
*newsocket
= new GSocket();
1202 if(newsocket
->IsOk())
1210 * -------------------------------------------------------------------------
1212 * -------------------------------------------------------------------------
1215 /* CHECK_ADDRESS verifies that the current address family is either
1216 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1217 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1218 * an appropiate error code.
1220 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1222 #define CHECK_ADDRESS(address, family) \
1224 if (address->m_family == GSOCK_NOFAMILY) \
1225 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1226 return address->m_error; \
1227 if (address->m_family != GSOCK_##family) \
1229 address->m_error = GSOCK_INVADDR; \
1230 return GSOCK_INVADDR; \
1234 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1236 if (address->m_family == GSOCK_NOFAMILY) \
1237 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1239 if (address->m_family != GSOCK_##family) \
1241 address->m_error = GSOCK_INVADDR; \
1247 GAddress
*GAddress_new(void)
1251 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1254 address
->m_family
= GSOCK_NOFAMILY
;
1255 address
->m_addr
= NULL
;
1261 GAddress
*GAddress_copy(GAddress
*address
)
1265 assert(address
!= NULL
);
1267 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1270 memcpy(addr2
, address
, sizeof(GAddress
));
1272 if (address
->m_addr
)
1274 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1275 if (addr2
->m_addr
== NULL
)
1280 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1286 void GAddress_destroy(GAddress
*address
)
1288 assert(address
!= NULL
);
1290 if (address
->m_addr
)
1291 free(address
->m_addr
);
1296 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1298 assert(address
!= NULL
);
1300 address
->m_family
= type
;
1303 GAddressType
GAddress_GetFamily(GAddress
*address
)
1305 assert(address
!= NULL
);
1307 return address
->m_family
;
1310 GSocketError
_GAddress_translate_from(GAddress
*address
,
1311 struct sockaddr
*addr
, int len
)
1313 address
->m_realfamily
= addr
->sa_family
;
1314 switch (addr
->sa_family
)
1317 address
->m_family
= GSOCK_INET
;
1320 address
->m_family
= GSOCK_UNIX
;
1324 address
->m_family
= GSOCK_INET6
;
1329 address
->m_error
= GSOCK_INVOP
;
1334 if (address
->m_addr
)
1335 free(address
->m_addr
);
1337 address
->m_len
= len
;
1338 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1340 if (address
->m_addr
== NULL
)
1342 address
->m_error
= GSOCK_MEMERR
;
1343 return GSOCK_MEMERR
;
1345 memcpy(address
->m_addr
, addr
, len
);
1347 return GSOCK_NOERROR
;
1350 GSocketError
_GAddress_translate_to(GAddress
*address
,
1351 struct sockaddr
**addr
, int *len
)
1353 if (!address
->m_addr
)
1355 address
->m_error
= GSOCK_INVADDR
;
1356 return GSOCK_INVADDR
;
1359 *len
= address
->m_len
;
1360 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1363 address
->m_error
= GSOCK_MEMERR
;
1364 return GSOCK_MEMERR
;
1367 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1368 return GSOCK_NOERROR
;
1372 * -------------------------------------------------------------------------
1373 * Internet address family
1374 * -------------------------------------------------------------------------
1377 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1379 address
->m_len
= sizeof(struct sockaddr_in
);
1380 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1381 if (address
->m_addr
== NULL
)
1383 address
->m_error
= GSOCK_MEMERR
;
1384 return GSOCK_MEMERR
;
1387 address
->m_family
= GSOCK_INET
;
1388 address
->m_realfamily
= AF_INET
;
1389 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1390 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1392 return GSOCK_NOERROR
;
1395 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1398 struct in_addr
*addr
;
1400 assert(address
!= NULL
);
1402 CHECK_ADDRESS(address
, INET
);
1404 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1406 addr
->s_addr
= inet_addr(hostname
);
1408 /* If it is a numeric host name, convert it now */
1409 if (addr
->s_addr
== INADDR_NONE
)
1411 struct in_addr
*array_addr
;
1413 /* It is a real name, we solve it */
1414 if ((he
= gethostbyname(hostname
)) == NULL
)
1416 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1417 address
->m_error
= GSOCK_NOHOST
;
1418 return GSOCK_NOHOST
;
1420 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1421 addr
->s_addr
= array_addr
[0].s_addr
;
1423 return GSOCK_NOERROR
;
1426 GSocketError
GAddress_INET_SetBroadcastAddress(GAddress
*address
)
1428 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1431 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1433 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1436 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1437 unsigned long hostaddr
)
1439 struct in_addr
*addr
;
1441 assert(address
!= NULL
);
1443 CHECK_ADDRESS(address
, INET
);
1445 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1446 addr
->s_addr
= htonl(hostaddr
);
1448 return GSOCK_NOERROR
;
1451 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1452 const char *protocol
)
1455 struct sockaddr_in
*addr
;
1457 assert(address
!= NULL
);
1458 CHECK_ADDRESS(address
, INET
);
1462 address
->m_error
= GSOCK_INVPORT
;
1463 return GSOCK_INVPORT
;
1466 se
= getservbyname(port
, protocol
);
1469 if (isdigit(port
[0]))
1473 port_int
= atoi(port
);
1474 addr
= (struct sockaddr_in
*)address
->m_addr
;
1475 addr
->sin_port
= htons((u_short
) port_int
);
1476 return GSOCK_NOERROR
;
1479 address
->m_error
= GSOCK_INVPORT
;
1480 return GSOCK_INVPORT
;
1483 addr
= (struct sockaddr_in
*)address
->m_addr
;
1484 addr
->sin_port
= se
->s_port
;
1486 return GSOCK_NOERROR
;
1489 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1491 struct sockaddr_in
*addr
;
1493 assert(address
!= NULL
);
1494 CHECK_ADDRESS(address
, INET
);
1496 addr
= (struct sockaddr_in
*)address
->m_addr
;
1497 addr
->sin_port
= htons(port
);
1499 return GSOCK_NOERROR
;
1502 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1506 struct sockaddr_in
*addr
;
1508 assert(address
!= NULL
);
1509 CHECK_ADDRESS(address
, INET
);
1511 addr
= (struct sockaddr_in
*)address
->m_addr
;
1512 addr_buf
= (char *)&(addr
->sin_addr
);
1514 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1517 address
->m_error
= GSOCK_NOHOST
;
1518 return GSOCK_NOHOST
;
1521 strncpy(hostname
, he
->h_name
, sbuf
);
1523 return GSOCK_NOERROR
;
1526 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1528 struct sockaddr_in
*addr
;
1530 assert(address
!= NULL
);
1531 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1533 addr
= (struct sockaddr_in
*)address
->m_addr
;
1535 return ntohl(addr
->sin_addr
.s_addr
);
1538 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1540 struct sockaddr_in
*addr
;
1542 assert(address
!= NULL
);
1543 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1545 addr
= (struct sockaddr_in
*)address
->m_addr
;
1546 return ntohs(addr
->sin_port
);
1550 * -------------------------------------------------------------------------
1551 * Unix address family
1552 * -------------------------------------------------------------------------
1555 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1557 assert (address
!= NULL
);
1558 address
->m_error
= GSOCK_INVADDR
;
1559 return GSOCK_INVADDR
;
1562 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1564 assert (address
!= NULL
);
1565 address
->m_error
= GSOCK_INVADDR
;
1566 return GSOCK_INVADDR
;
1569 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1571 assert (address
!= NULL
);
1572 address
->m_error
= GSOCK_INVADDR
;
1573 return GSOCK_INVADDR
;
1576 #else /* !wxUSE_SOCKETS */
1579 * Translation unit shouldn't be empty, so include this typedef to make the
1580 * compiler (VC++ 6.0, for example) happy
1582 typedef void (*wxDummy
)();
1584 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */