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 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
99 virtual bool OnInit();
100 virtual void OnExit();
101 virtual bool CanUseEventLoop();
102 virtual bool Init_Socket(GSocket
*socket
);
103 virtual void Destroy_Socket(GSocket
*socket
);
104 virtual void Enable_Events(GSocket
*socket
);
105 virtual void Disable_Events(GSocket
*socket
);
108 bool GSocketGUIFunctionsTableNull::OnInit()
110 void GSocketGUIFunctionsTableNull::OnExit()
112 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
114 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
116 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
118 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
120 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
122 /* Global initialisers */
124 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
126 gs_gui_functions
= guifunc
;
129 int GSocket_Init(void)
133 if (!gs_gui_functions
)
135 static GSocketGUIFunctionsTableNull table
;
136 gs_gui_functions
= &table
;
138 if ( !gs_gui_functions
->OnInit() )
143 /* Initialize WinSocket */
144 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
147 void GSocket_Cleanup(void)
149 if (gs_gui_functions
)
151 gs_gui_functions
->OnExit();
154 /* Cleanup WinSocket */
158 /* Constructors / Destructors for GSocket */
164 m_fd
= INVALID_SOCKET
;
165 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
172 m_error
= GSOCK_NOERROR
;
175 m_non_blocking
= false;
176 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
177 m_timeout
.tv_usec
= 0;
178 m_establishing
= false;
181 assert(gs_gui_functions
);
182 /* Per-socket GUI-specific initialization */
183 m_ok
= gs_gui_functions
->Init_Socket(this);
186 void GSocket::Close()
188 gs_gui_functions
->Disable_Events(this);
190 m_fd
= INVALID_SOCKET
;
197 /* Per-socket GUI-specific cleanup */
198 gs_gui_functions
->Destroy_Socket(this);
200 /* Check that the socket is really shutdowned */
201 if (m_fd
!= INVALID_SOCKET
)
204 /* Destroy private addresses */
206 GAddress_destroy(m_local
);
209 GAddress_destroy(m_peer
);
213 * Disallow further read/write operations on this socket, close
214 * the fd and disable all callbacks.
216 void GSocket::Shutdown()
222 /* If socket has been created, shutdown it */
223 if (m_fd
!= INVALID_SOCKET
)
225 shutdown(m_fd
, 1 /* SD_SEND */);
229 /* Disable GUI callbacks */
230 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
231 m_cbacks
[evt
] = NULL
;
233 m_detected
= GSOCK_LOST_FLAG
;
236 /* Address handling */
242 * Set or get the local or peer address for this socket. The 'set'
243 * functions return GSOCK_NOERROR on success, an error code otherwise.
244 * The 'get' functions return a pointer to a GAddress object on success,
245 * or NULL otherwise, in which case they set the error code of the
246 * corresponding GSocket.
249 * GSOCK_INVSOCK - the socket is not valid.
250 * GSOCK_INVADDR - the address is not valid.
252 GSocketError
GSocket::SetLocal(GAddress
*address
)
256 /* the socket must be initialized, or it must be a server */
257 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
259 m_error
= GSOCK_INVSOCK
;
260 return GSOCK_INVSOCK
;
264 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
266 m_error
= GSOCK_INVADDR
;
267 return GSOCK_INVADDR
;
271 GAddress_destroy(m_local
);
273 m_local
= GAddress_copy(address
);
275 return GSOCK_NOERROR
;
278 GSocketError
GSocket::SetPeer(GAddress
*address
)
283 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
285 m_error
= GSOCK_INVADDR
;
286 return GSOCK_INVADDR
;
290 GAddress_destroy(m_peer
);
292 m_peer
= GAddress_copy(address
);
294 return GSOCK_NOERROR
;
297 GAddress
*GSocket::GetLocal()
300 struct sockaddr addr
;
301 WX_SOCKLEN_T size
= sizeof(addr
);
306 /* try to get it from the m_local var first */
308 return GAddress_copy(m_local
);
310 /* else, if the socket is initialized, try getsockname */
311 if (m_fd
== INVALID_SOCKET
)
313 m_error
= GSOCK_INVSOCK
;
317 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
319 m_error
= GSOCK_IOERR
;
323 /* got a valid address from getsockname, create a GAddress object */
324 if ((address
= GAddress_new()) == NULL
)
326 m_error
= GSOCK_MEMERR
;
330 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
332 GAddress_destroy(address
);
340 GAddress
*GSocket::GetPeer()
344 /* try to get it from the m_peer var */
346 return GAddress_copy(m_peer
);
351 /* Server specific parts */
353 /* GSocket_SetServer:
354 * Sets up this socket as a server. The local address must have been
355 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
356 * Returns GSOCK_NOERROR on success, one of the following otherwise:
359 * GSOCK_INVSOCK - the socket is in use.
360 * GSOCK_INVADDR - the local address has not been set.
361 * GSOCK_IOERR - low-level error.
363 GSocketError
GSocket::SetServer()
369 /* must not be in use */
370 if (m_fd
!= INVALID_SOCKET
)
372 m_error
= GSOCK_INVSOCK
;
373 return GSOCK_INVSOCK
;
376 /* the local addr must have been set */
379 m_error
= GSOCK_INVADDR
;
380 return GSOCK_INVADDR
;
383 /* Initialize all fields */
387 /* Create the socket */
388 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
390 if (m_fd
== INVALID_SOCKET
)
392 m_error
= GSOCK_IOERR
;
396 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
397 gs_gui_functions
->Enable_Events(this);
399 /* allow a socket to re-bind if the socket is in the TIME_WAIT
400 state after being previously closed.
404 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
407 /* Bind to the local address,
408 * retrieve the actual address bound,
409 * and listen up to 5 connections.
411 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
414 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
415 (listen(m_fd
, 5) != 0))
418 m_error
= GSOCK_IOERR
;
422 return GSOCK_NOERROR
;
425 /* GSocket_WaitConnection:
426 * Waits for an incoming client connection. Returns a pointer to
427 * a GSocket object, or NULL if there was an error, in which case
428 * the last error field will be updated for the calling GSocket.
430 * Error codes (set in the calling GSocket)
431 * GSOCK_INVSOCK - the socket is not valid or not a server.
432 * GSOCK_TIMEDOUT - timeout, no incoming connections.
433 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
434 * GSOCK_MEMERR - couldn't allocate memory.
435 * GSOCK_IOERR - low-level error.
437 GSocket
*GSocket::WaitConnection()
440 struct sockaddr from
;
441 WX_SOCKLEN_T fromlen
= sizeof(from
);
447 /* Reenable CONNECTION events */
448 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
450 /* If the socket has already been created, we exit immediately */
451 if (m_fd
== INVALID_SOCKET
|| !m_server
)
453 m_error
= GSOCK_INVSOCK
;
457 /* Create a GSocket object for the new connection */
458 connection
= GSocket_new();
462 m_error
= GSOCK_MEMERR
;
466 /* Wait for a connection (with timeout) */
467 if (Input_Timeout() == GSOCK_TIMEDOUT
)
470 /* m_error set by _GSocket_Input_Timeout */
474 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
476 if (connection
->m_fd
== INVALID_SOCKET
)
478 if (WSAGetLastError() == WSAEWOULDBLOCK
)
479 m_error
= GSOCK_WOULDBLOCK
;
481 m_error
= GSOCK_IOERR
;
487 /* Initialize all fields */
488 connection
->m_server
= false;
489 connection
->m_stream
= true;
491 /* Setup the peer address field */
492 connection
->m_peer
= GAddress_new();
493 if (!connection
->m_peer
)
496 m_error
= GSOCK_MEMERR
;
499 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
500 if (err
!= GSOCK_NOERROR
)
502 GAddress_destroy(connection
->m_peer
);
508 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
509 gs_gui_functions
->Enable_Events(connection
);
514 /* GSocket_SetReusable:
515 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
516 * make the appropriate setsockopt() call.
517 * Implemented as a GSocket function because clients (ie, wxSocketServer)
518 * don't have access to the GSocket struct information.
519 * Returns true if the flag was set correctly, false if an error occurred
520 * (ie, if the parameter was NULL)
522 bool GSocket::SetReusable()
524 /* socket must not be null, and must not be in use/already bound */
525 if (this && m_fd
== INVALID_SOCKET
) {
532 /* Client specific parts */
535 * For stream (connection oriented) sockets, GSocket_Connect() tries
536 * to establish a client connection to a server using the peer address
537 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
538 * connection has been successfully established, or one of the error
539 * codes listed below. Note that for nonblocking sockets, a return
540 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
541 * request can be completed later; you should use GSocket_Select()
542 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
543 * corresponding asynchronous events.
545 * For datagram (non connection oriented) sockets, GSocket_Connect()
546 * just sets the peer address established with GSocket_SetPeer() as
547 * default destination.
550 * GSOCK_INVSOCK - the socket is in use or not valid.
551 * GSOCK_INVADDR - the peer address has not been established.
552 * GSOCK_TIMEDOUT - timeout, the connection failed.
553 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
554 * GSOCK_MEMERR - couldn't allocate memory.
555 * GSOCK_IOERR - low-level error.
557 GSocketError
GSocket::Connect(GSocketStream stream
)
564 /* Enable CONNECTION events (needed for nonblocking connections) */
565 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
567 if (m_fd
!= INVALID_SOCKET
)
569 m_error
= GSOCK_INVSOCK
;
570 return GSOCK_INVSOCK
;
575 m_error
= GSOCK_INVADDR
;
576 return GSOCK_INVADDR
;
579 /* Streamed or dgram socket? */
580 m_stream
= (stream
== GSOCK_STREAMED
);
582 m_establishing
= false;
584 /* Create the socket */
585 m_fd
= socket(m_peer
->m_realfamily
,
586 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
588 if (m_fd
== INVALID_SOCKET
)
590 m_error
= GSOCK_IOERR
;
594 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
595 gs_gui_functions
->Enable_Events(this);
597 // If the reuse flag is set, use the applicable socket reuse flag
600 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
603 // If a local address has been set, then we need to bind to it before calling connect
604 if (m_local
&& m_local
->m_addr
)
606 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
609 /* Connect it to the peer address, with a timeout (see below) */
610 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
612 if (ret
== SOCKET_ERROR
)
614 err
= WSAGetLastError();
616 /* If connect failed with EWOULDBLOCK and the GSocket object
617 * is in blocking mode, we select() for the specified timeout
618 * checking for writability to see if the connection request
621 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
623 err
= Connect_Timeout();
625 if (err
!= GSOCK_NOERROR
)
628 /* m_error is set in _GSocket_Connect_Timeout */
631 return (GSocketError
) err
;
634 /* If connect failed with EWOULDBLOCK and the GSocket object
635 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
636 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
637 * this way if the connection completes, a GSOCK_CONNECTION
638 * event will be generated, if enabled.
640 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
642 m_establishing
= true;
643 m_error
= GSOCK_WOULDBLOCK
;
644 return GSOCK_WOULDBLOCK
;
647 /* If connect failed with an error other than EWOULDBLOCK,
648 * then the call to GSocket_Connect() has failed.
651 m_error
= GSOCK_IOERR
;
655 return GSOCK_NOERROR
;
658 /* Datagram sockets */
660 /* GSocket_SetNonOriented:
661 * Sets up this socket as a non-connection oriented (datagram) socket.
662 * Before using this function, the local address must have been set
663 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
664 * on success, or one of the following otherwise.
667 * GSOCK_INVSOCK - the socket is in use.
668 * GSOCK_INVADDR - the local address has not been set.
669 * GSOCK_IOERR - low-level error.
671 GSocketError
GSocket::SetNonOriented()
677 if (m_fd
!= INVALID_SOCKET
)
679 m_error
= GSOCK_INVSOCK
;
680 return GSOCK_INVSOCK
;
685 m_error
= GSOCK_INVADDR
;
686 return GSOCK_INVADDR
;
689 /* Initialize all fields */
693 /* Create the socket */
694 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
696 if (m_fd
== INVALID_SOCKET
)
698 m_error
= GSOCK_IOERR
;
702 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
703 gs_gui_functions
->Enable_Events(this);
707 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
710 /* Bind to the local address,
711 * and retrieve the actual address bound.
713 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
716 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0))
719 m_error
= GSOCK_IOERR
;
723 return GSOCK_NOERROR
;
728 /* Like recv(), send(), ... */
729 int GSocket::Read(char *buffer
, int size
)
735 /* Reenable INPUT events */
736 m_detected
&= ~GSOCK_INPUT_FLAG
;
738 if (m_fd
== INVALID_SOCKET
|| m_server
)
740 m_error
= GSOCK_INVSOCK
;
744 /* If the socket is blocking, wait for data (with a timeout) */
745 if (Input_Timeout() == GSOCK_TIMEDOUT
)
747 m_error
= GSOCK_TIMEDOUT
;
753 ret
= Recv_Stream(buffer
, size
);
755 ret
= Recv_Dgram(buffer
, size
);
757 if (ret
== SOCKET_ERROR
)
759 if (WSAGetLastError() != WSAEWOULDBLOCK
)
760 m_error
= GSOCK_IOERR
;
762 m_error
= GSOCK_WOULDBLOCK
;
769 int GSocket::Write(const char *buffer
, int size
)
775 if (m_fd
== INVALID_SOCKET
|| m_server
)
777 m_error
= GSOCK_INVSOCK
;
781 /* If the socket is blocking, wait for writability (with a timeout) */
782 if (Output_Timeout() == GSOCK_TIMEDOUT
)
787 ret
= Send_Stream(buffer
, size
);
789 ret
= Send_Dgram(buffer
, size
);
791 if (ret
== SOCKET_ERROR
)
793 if (WSAGetLastError() != WSAEWOULDBLOCK
)
794 m_error
= GSOCK_IOERR
;
796 m_error
= GSOCK_WOULDBLOCK
;
798 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
799 * does). Once the first OUTPUT event is received, users can assume
800 * that the socket is writable until a read operation fails. Only then
801 * will further OUTPUT events be posted.
803 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
811 * Polls the socket to determine its status. This function will
812 * check for the events specified in the 'flags' parameter, and
813 * it will return a mask indicating which operations can be
814 * performed. This function won't block, regardless of the
815 * mode (blocking | nonblocking) of the socket.
817 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
819 if (!gs_gui_functions
->CanUseEventLoop())
821 GSocketEventFlags result
= 0;
831 FD_SET(m_fd
, &readfds
);
832 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
833 FD_SET(m_fd
, &writefds
);
834 FD_SET(m_fd
, &exceptfds
);
836 /* Check 'sticky' CONNECTION flag first */
837 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
839 /* If we have already detected a LOST event, then don't try
840 * to do any further processing.
842 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
844 m_establishing
= false;
846 return (GSOCK_LOST_FLAG
& flags
);
850 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
853 /* What to do here? */
854 return (result
& flags
);
857 /* Check for exceptions and errors */
858 if (FD_ISSET(m_fd
, &exceptfds
))
860 m_establishing
= false;
861 m_detected
= GSOCK_LOST_FLAG
;
863 /* LOST event: Abort any further processing */
864 return (GSOCK_LOST_FLAG
& flags
);
867 /* Check for readability */
868 if (FD_ISSET(m_fd
, &readfds
))
870 result
|= GSOCK_INPUT_FLAG
;
872 if (m_server
&& m_stream
)
874 /* This is a TCP server socket that detected a connection.
875 While the INPUT_FLAG is also set, it doesn't matter on
876 this kind of sockets, as we can only Accept() from them. */
877 result
|= GSOCK_CONNECTION_FLAG
;
878 m_detected
|= GSOCK_CONNECTION_FLAG
;
882 /* Check for writability */
883 if (FD_ISSET(m_fd
, &writefds
))
885 if (m_establishing
&& !m_server
)
888 WX_SOCKLEN_T len
= sizeof(error
);
890 m_establishing
= false;
892 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
896 m_detected
= GSOCK_LOST_FLAG
;
898 /* LOST event: Abort any further processing */
899 return (GSOCK_LOST_FLAG
& flags
);
903 result
|= GSOCK_CONNECTION_FLAG
;
904 m_detected
|= GSOCK_CONNECTION_FLAG
;
909 result
|= GSOCK_OUTPUT_FLAG
;
913 return (result
& flags
);
918 return flags
& m_detected
;
924 /* GSocket_SetNonBlocking:
925 * Sets the socket to non-blocking mode. All IO calls will return
928 void GSocket::SetNonBlocking(bool non_block
)
932 m_non_blocking
= non_block
;
935 /* GSocket_SetTimeout:
936 * Sets the timeout for blocking calls. Time is expressed in
939 void GSocket::SetTimeout(unsigned long millis
)
943 m_timeout
.tv_sec
= (millis
/ 1000);
944 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
948 * Returns the last error occurred for this socket. Note that successful
949 * operations do not clear this back to GSOCK_NOERROR, so use it only
952 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
962 * There is data to be read in the input buffer. If, after a read
963 * operation, there is still data available, the callback function will
966 * The socket is available for writing. That is, the next write call
967 * won't block. This event is generated only once, when the connection is
968 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
969 * when the output buffer empties again. This means that the app should
970 * assume that it can write since the first OUTPUT event, and no more
971 * OUTPUT events will be generated unless an error occurs.
973 * Connection successfully established, for client sockets, or incoming
974 * client connection, for server sockets. Wait for this event (also watch
975 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
977 * The connection is lost (or a connection request failed); this could
978 * be due to a failure, or due to the peer closing it gracefully.
981 /* GSocket_SetCallback:
982 * Enables the callbacks specified by 'flags'. Note that 'flags'
983 * may be a combination of flags OR'ed toghether, so the same
984 * callback function can be made to accept different events.
985 * The callback function must have the following prototype:
987 * void function(GSocket *socket, GSocketEvent event, char *cdata)
989 void GSocket::SetCallback(GSocketEventFlags flags
,
990 GSocketCallback callback
, char *cdata
)
996 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
998 if ((flags
& (1 << count
)) != 0)
1000 m_cbacks
[count
] = callback
;
1001 m_data
[count
] = cdata
;
1006 /* GSocket_UnsetCallback:
1007 * Disables all callbacks specified by 'flags', which may be a
1008 * combination of flags OR'ed toghether.
1010 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1016 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1018 if ((flags
& (1 << count
)) != 0)
1020 m_cbacks
[count
] = NULL
;
1021 m_data
[count
] = NULL
;
1026 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1027 void *optval
, int *optlen
)
1029 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1031 return GSOCK_NOERROR
;
1033 return GSOCK_OPTERR
;
1036 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1037 const void *optval
, int optlen
)
1039 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1041 return GSOCK_NOERROR
;
1043 return GSOCK_OPTERR
;
1046 /* Internals (IO) */
1048 /* _GSocket_Input_Timeout:
1049 * For blocking sockets, wait until data is available or
1050 * until timeout ellapses.
1052 GSocketError
GSocket::Input_Timeout()
1056 if (!m_non_blocking
)
1059 FD_SET(m_fd
, &readfds
);
1060 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1062 m_error
= GSOCK_TIMEDOUT
;
1063 return GSOCK_TIMEDOUT
;
1066 return GSOCK_NOERROR
;
1069 /* _GSocket_Output_Timeout:
1070 * For blocking sockets, wait until data can be sent without
1071 * blocking or until timeout ellapses.
1073 GSocketError
GSocket::Output_Timeout()
1077 if (!m_non_blocking
)
1080 FD_SET(m_fd
, &writefds
);
1081 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1083 m_error
= GSOCK_TIMEDOUT
;
1084 return GSOCK_TIMEDOUT
;
1087 return GSOCK_NOERROR
;
1090 /* _GSocket_Connect_Timeout:
1091 * For blocking sockets, wait until the connection is
1092 * established or fails, or until timeout ellapses.
1094 GSocketError
GSocket::Connect_Timeout()
1100 FD_ZERO(&exceptfds
);
1101 FD_SET(m_fd
, &writefds
);
1102 FD_SET(m_fd
, &exceptfds
);
1103 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1105 m_error
= GSOCK_TIMEDOUT
;
1106 return GSOCK_TIMEDOUT
;
1108 if (!FD_ISSET(m_fd
, &writefds
))
1110 m_error
= GSOCK_IOERR
;
1114 return GSOCK_NOERROR
;
1117 int GSocket::Recv_Stream(char *buffer
, int size
)
1119 return recv(m_fd
, buffer
, size
, 0);
1122 int GSocket::Recv_Dgram(char *buffer
, int size
)
1124 struct sockaddr from
;
1125 WX_SOCKLEN_T fromlen
= sizeof(from
);
1129 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1131 if (ret
== SOCKET_ERROR
)
1132 return SOCKET_ERROR
;
1134 /* Translate a system address into a GSocket address */
1137 m_peer
= GAddress_new();
1140 m_error
= GSOCK_MEMERR
;
1144 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1145 if (err
!= GSOCK_NOERROR
)
1147 GAddress_destroy(m_peer
);
1156 int GSocket::Send_Stream(const char *buffer
, int size
)
1158 return send(m_fd
, buffer
, size
, 0);
1161 int GSocket::Send_Dgram(const char *buffer
, int size
)
1163 struct sockaddr
*addr
;
1169 m_error
= GSOCK_INVADDR
;
1173 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1174 if (err
!= GSOCK_NOERROR
)
1180 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1182 /* Frees memory allocated by _GAddress_translate_to */
1188 /* Compatibility functions for GSocket */
1189 GSocket
*GSocket_new(void)
1191 GSocket
*newsocket
= new GSocket();
1192 if(newsocket
->IsOk())
1200 * -------------------------------------------------------------------------
1202 * -------------------------------------------------------------------------
1205 /* CHECK_ADDRESS verifies that the current address family is either
1206 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1207 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1208 * an appropiate error code.
1210 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1212 #define CHECK_ADDRESS(address, family) \
1214 if (address->m_family == GSOCK_NOFAMILY) \
1215 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1216 return address->m_error; \
1217 if (address->m_family != GSOCK_##family) \
1219 address->m_error = GSOCK_INVADDR; \
1220 return GSOCK_INVADDR; \
1224 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1226 if (address->m_family == GSOCK_NOFAMILY) \
1227 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1229 if (address->m_family != GSOCK_##family) \
1231 address->m_error = GSOCK_INVADDR; \
1237 GAddress
*GAddress_new(void)
1241 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1244 address
->m_family
= GSOCK_NOFAMILY
;
1245 address
->m_addr
= NULL
;
1251 GAddress
*GAddress_copy(GAddress
*address
)
1255 assert(address
!= NULL
);
1257 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1260 memcpy(addr2
, address
, sizeof(GAddress
));
1262 if (address
->m_addr
)
1264 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1265 if (addr2
->m_addr
== NULL
)
1270 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1276 void GAddress_destroy(GAddress
*address
)
1278 assert(address
!= NULL
);
1280 if (address
->m_addr
)
1281 free(address
->m_addr
);
1286 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1288 assert(address
!= NULL
);
1290 address
->m_family
= type
;
1293 GAddressType
GAddress_GetFamily(GAddress
*address
)
1295 assert(address
!= NULL
);
1297 return address
->m_family
;
1300 GSocketError
_GAddress_translate_from(GAddress
*address
,
1301 struct sockaddr
*addr
, int len
)
1303 address
->m_realfamily
= addr
->sa_family
;
1304 switch (addr
->sa_family
)
1307 address
->m_family
= GSOCK_INET
;
1310 address
->m_family
= GSOCK_UNIX
;
1314 address
->m_family
= GSOCK_INET6
;
1319 address
->m_error
= GSOCK_INVOP
;
1324 if (address
->m_addr
)
1325 free(address
->m_addr
);
1327 address
->m_len
= len
;
1328 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1330 if (address
->m_addr
== NULL
)
1332 address
->m_error
= GSOCK_MEMERR
;
1333 return GSOCK_MEMERR
;
1335 memcpy(address
->m_addr
, addr
, len
);
1337 return GSOCK_NOERROR
;
1340 GSocketError
_GAddress_translate_to(GAddress
*address
,
1341 struct sockaddr
**addr
, int *len
)
1343 if (!address
->m_addr
)
1345 address
->m_error
= GSOCK_INVADDR
;
1346 return GSOCK_INVADDR
;
1349 *len
= address
->m_len
;
1350 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1353 address
->m_error
= GSOCK_MEMERR
;
1354 return GSOCK_MEMERR
;
1357 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1358 return GSOCK_NOERROR
;
1362 * -------------------------------------------------------------------------
1363 * Internet address family
1364 * -------------------------------------------------------------------------
1367 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1369 address
->m_len
= sizeof(struct sockaddr_in
);
1370 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1371 if (address
->m_addr
== NULL
)
1373 address
->m_error
= GSOCK_MEMERR
;
1374 return GSOCK_MEMERR
;
1377 address
->m_family
= GSOCK_INET
;
1378 address
->m_realfamily
= AF_INET
;
1379 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1380 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1382 return GSOCK_NOERROR
;
1385 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1388 struct in_addr
*addr
;
1390 assert(address
!= NULL
);
1392 CHECK_ADDRESS(address
, INET
);
1394 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1396 addr
->s_addr
= inet_addr(hostname
);
1398 /* If it is a numeric host name, convert it now */
1399 if (addr
->s_addr
== INADDR_NONE
)
1401 struct in_addr
*array_addr
;
1403 /* It is a real name, we solve it */
1404 if ((he
= gethostbyname(hostname
)) == NULL
)
1406 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1407 address
->m_error
= GSOCK_NOHOST
;
1408 return GSOCK_NOHOST
;
1410 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1411 addr
->s_addr
= array_addr
[0].s_addr
;
1413 return GSOCK_NOERROR
;
1416 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1418 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1421 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1422 unsigned long hostaddr
)
1424 struct in_addr
*addr
;
1426 assert(address
!= NULL
);
1428 CHECK_ADDRESS(address
, INET
);
1430 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1431 addr
->s_addr
= htonl(hostaddr
);
1433 return GSOCK_NOERROR
;
1436 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1437 const char *protocol
)
1440 struct sockaddr_in
*addr
;
1442 assert(address
!= NULL
);
1443 CHECK_ADDRESS(address
, INET
);
1447 address
->m_error
= GSOCK_INVPORT
;
1448 return GSOCK_INVPORT
;
1451 se
= getservbyname(port
, protocol
);
1454 if (isdigit(port
[0]))
1458 port_int
= atoi(port
);
1459 addr
= (struct sockaddr_in
*)address
->m_addr
;
1460 addr
->sin_port
= htons((u_short
) port_int
);
1461 return GSOCK_NOERROR
;
1464 address
->m_error
= GSOCK_INVPORT
;
1465 return GSOCK_INVPORT
;
1468 addr
= (struct sockaddr_in
*)address
->m_addr
;
1469 addr
->sin_port
= se
->s_port
;
1471 return GSOCK_NOERROR
;
1474 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1476 struct sockaddr_in
*addr
;
1478 assert(address
!= NULL
);
1479 CHECK_ADDRESS(address
, INET
);
1481 addr
= (struct sockaddr_in
*)address
->m_addr
;
1482 addr
->sin_port
= htons(port
);
1484 return GSOCK_NOERROR
;
1487 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1491 struct sockaddr_in
*addr
;
1493 assert(address
!= NULL
);
1494 CHECK_ADDRESS(address
, INET
);
1496 addr
= (struct sockaddr_in
*)address
->m_addr
;
1497 addr_buf
= (char *)&(addr
->sin_addr
);
1499 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1502 address
->m_error
= GSOCK_NOHOST
;
1503 return GSOCK_NOHOST
;
1506 strncpy(hostname
, he
->h_name
, sbuf
);
1508 return GSOCK_NOERROR
;
1511 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1513 struct sockaddr_in
*addr
;
1515 assert(address
!= NULL
);
1516 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1518 addr
= (struct sockaddr_in
*)address
->m_addr
;
1520 return ntohl(addr
->sin_addr
.s_addr
);
1523 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1525 struct sockaddr_in
*addr
;
1527 assert(address
!= NULL
);
1528 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1530 addr
= (struct sockaddr_in
*)address
->m_addr
;
1531 return ntohs(addr
->sin_port
);
1535 * -------------------------------------------------------------------------
1536 * Unix address family
1537 * -------------------------------------------------------------------------
1540 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1542 assert (address
!= NULL
);
1543 address
->m_error
= GSOCK_INVADDR
;
1544 return GSOCK_INVADDR
;
1547 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1549 assert (address
!= NULL
);
1550 address
->m_error
= GSOCK_INVADDR
;
1551 return GSOCK_INVADDR
;
1554 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1556 assert (address
!= NULL
);
1557 address
->m_error
= GSOCK_INVADDR
;
1558 return GSOCK_INVADDR
;
1561 #else /* !wxUSE_SOCKETS */
1564 * Translation unit shouldn't be empty, so include this typedef to make the
1565 * compiler (VC++ 6.0, for example) happy
1567 typedef void (*wxDummy
)();
1569 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */