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;
182 m_initialRecvBufferSize
= -1;
183 m_initialSendBufferSize
= -1;
185 assert(gs_gui_functions
);
186 /* Per-socket GUI-specific initialization */
187 m_ok
= gs_gui_functions
->Init_Socket(this);
190 void GSocket::Close()
192 gs_gui_functions
->Disable_Events(this);
194 m_fd
= INVALID_SOCKET
;
201 /* Per-socket GUI-specific cleanup */
202 gs_gui_functions
->Destroy_Socket(this);
204 /* Check that the socket is really shutdowned */
205 if (m_fd
!= INVALID_SOCKET
)
208 /* Destroy private addresses */
210 GAddress_destroy(m_local
);
213 GAddress_destroy(m_peer
);
217 * Disallow further read/write operations on this socket, close
218 * the fd and disable all callbacks.
220 void GSocket::Shutdown()
226 /* If socket has been created, shutdown it */
227 if (m_fd
!= INVALID_SOCKET
)
229 shutdown(m_fd
, 1 /* SD_SEND */);
233 /* Disable GUI callbacks */
234 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
235 m_cbacks
[evt
] = NULL
;
237 m_detected
= GSOCK_LOST_FLAG
;
240 /* Address handling */
246 * Set or get the local or peer address for this socket. The 'set'
247 * functions return GSOCK_NOERROR on success, an error code otherwise.
248 * The 'get' functions return a pointer to a GAddress object on success,
249 * or NULL otherwise, in which case they set the error code of the
250 * corresponding GSocket.
253 * GSOCK_INVSOCK - the socket is not valid.
254 * GSOCK_INVADDR - the address is not valid.
256 GSocketError
GSocket::SetLocal(GAddress
*address
)
260 /* the socket must be initialized, or it must be a server */
261 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
263 m_error
= GSOCK_INVSOCK
;
264 return GSOCK_INVSOCK
;
268 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
270 m_error
= GSOCK_INVADDR
;
271 return GSOCK_INVADDR
;
275 GAddress_destroy(m_local
);
277 m_local
= GAddress_copy(address
);
279 return GSOCK_NOERROR
;
282 GSocketError
GSocket::SetPeer(GAddress
*address
)
287 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
289 m_error
= GSOCK_INVADDR
;
290 return GSOCK_INVADDR
;
294 GAddress_destroy(m_peer
);
296 m_peer
= GAddress_copy(address
);
298 return GSOCK_NOERROR
;
301 GAddress
*GSocket::GetLocal()
304 struct sockaddr addr
;
305 WX_SOCKLEN_T size
= sizeof(addr
);
310 /* try to get it from the m_local var first */
312 return GAddress_copy(m_local
);
314 /* else, if the socket is initialized, try getsockname */
315 if (m_fd
== INVALID_SOCKET
)
317 m_error
= GSOCK_INVSOCK
;
321 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
323 m_error
= GSOCK_IOERR
;
327 /* got a valid address from getsockname, create a GAddress object */
328 if ((address
= GAddress_new()) == NULL
)
330 m_error
= GSOCK_MEMERR
;
334 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
336 GAddress_destroy(address
);
344 GAddress
*GSocket::GetPeer()
348 /* try to get it from the m_peer var */
350 return GAddress_copy(m_peer
);
355 /* Server specific parts */
357 /* GSocket_SetServer:
358 * Sets up this socket as a server. The local address must have been
359 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
360 * Returns GSOCK_NOERROR on success, one of the following otherwise:
363 * GSOCK_INVSOCK - the socket is in use.
364 * GSOCK_INVADDR - the local address has not been set.
365 * GSOCK_IOERR - low-level error.
367 GSocketError
GSocket::SetServer()
373 /* must not be in use */
374 if (m_fd
!= INVALID_SOCKET
)
376 m_error
= GSOCK_INVSOCK
;
377 return GSOCK_INVSOCK
;
380 /* the local addr must have been set */
383 m_error
= GSOCK_INVADDR
;
384 return GSOCK_INVADDR
;
387 /* Initialize all fields */
391 /* Create the socket */
392 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
394 if (m_fd
== INVALID_SOCKET
)
396 m_error
= GSOCK_IOERR
;
400 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
401 gs_gui_functions
->Enable_Events(this);
403 /* allow a socket to re-bind if the socket is in the TIME_WAIT
404 state after being previously closed.
408 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
411 /* Bind to the local address,
412 * retrieve the actual address bound,
413 * and listen up to 5 connections.
415 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
418 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
419 (listen(m_fd
, 5) != 0))
422 m_error
= GSOCK_IOERR
;
426 return GSOCK_NOERROR
;
429 /* GSocket_WaitConnection:
430 * Waits for an incoming client connection. Returns a pointer to
431 * a GSocket object, or NULL if there was an error, in which case
432 * the last error field will be updated for the calling GSocket.
434 * Error codes (set in the calling GSocket)
435 * GSOCK_INVSOCK - the socket is not valid or not a server.
436 * GSOCK_TIMEDOUT - timeout, no incoming connections.
437 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
438 * GSOCK_MEMERR - couldn't allocate memory.
439 * GSOCK_IOERR - low-level error.
441 GSocket
*GSocket::WaitConnection()
444 struct sockaddr from
;
445 WX_SOCKLEN_T fromlen
= sizeof(from
);
451 /* Reenable CONNECTION events */
452 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
454 /* If the socket has already been created, we exit immediately */
455 if (m_fd
== INVALID_SOCKET
|| !m_server
)
457 m_error
= GSOCK_INVSOCK
;
461 /* Create a GSocket object for the new connection */
462 connection
= GSocket_new();
466 m_error
= GSOCK_MEMERR
;
470 /* Wait for a connection (with timeout) */
471 if (Input_Timeout() == GSOCK_TIMEDOUT
)
474 /* m_error set by _GSocket_Input_Timeout */
478 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
480 if (connection
->m_fd
== INVALID_SOCKET
)
482 if (WSAGetLastError() == WSAEWOULDBLOCK
)
483 m_error
= GSOCK_WOULDBLOCK
;
485 m_error
= GSOCK_IOERR
;
491 /* Initialize all fields */
492 connection
->m_server
= false;
493 connection
->m_stream
= true;
495 /* Setup the peer address field */
496 connection
->m_peer
= GAddress_new();
497 if (!connection
->m_peer
)
500 m_error
= GSOCK_MEMERR
;
503 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
504 if (err
!= GSOCK_NOERROR
)
506 GAddress_destroy(connection
->m_peer
);
512 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
513 gs_gui_functions
->Enable_Events(connection
);
518 /* GSocket_SetReusable:
519 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
520 * make the appropriate setsockopt() call.
521 * Implemented as a GSocket function because clients (ie, wxSocketServer)
522 * don't have access to the GSocket struct information.
523 * Returns true if the flag was set correctly, false if an error occurred
524 * (ie, if the parameter was NULL)
526 bool GSocket::SetReusable()
528 /* socket must not be null, and must not be in use/already bound */
529 if (this && m_fd
== INVALID_SOCKET
) {
536 /* GSocket_SetBroadcast:
537 * Simply sets the m_broadcast flag on the socket. GSocket_SetServer will
538 * make the appropriate setsockopt() call.
539 * Implemented as a GSocket function because clients (ie, wxSocketServer)
540 * don't have access to the GSocket struct information.
541 * Returns true if the flag was set correctly, false if an error occurred
542 * (ie, if the parameter was NULL)
544 bool GSocket::SetBroadcast()
546 /* socket must not be in use/already bound */
547 if (m_fd
== INVALID_SOCKET
) {
554 bool GSocket::DontDoBind()
556 /* socket must not be in use/already bound */
557 if (m_fd
== INVALID_SOCKET
) {
564 /* Client specific parts */
567 * For stream (connection oriented) sockets, GSocket_Connect() tries
568 * to establish a client connection to a server using the peer address
569 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
570 * connection has been successfully established, or one of the error
571 * codes listed below. Note that for nonblocking sockets, a return
572 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
573 * request can be completed later; you should use GSocket_Select()
574 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
575 * corresponding asynchronous events.
577 * For datagram (non connection oriented) sockets, GSocket_Connect()
578 * just sets the peer address established with GSocket_SetPeer() as
579 * default destination.
582 * GSOCK_INVSOCK - the socket is in use or not valid.
583 * GSOCK_INVADDR - the peer address has not been established.
584 * GSOCK_TIMEDOUT - timeout, the connection failed.
585 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
586 * GSOCK_MEMERR - couldn't allocate memory.
587 * GSOCK_IOERR - low-level error.
589 GSocketError
GSocket::Connect(GSocketStream stream
)
596 /* Enable CONNECTION events (needed for nonblocking connections) */
597 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
599 if (m_fd
!= INVALID_SOCKET
)
601 m_error
= GSOCK_INVSOCK
;
602 return GSOCK_INVSOCK
;
607 m_error
= GSOCK_INVADDR
;
608 return GSOCK_INVADDR
;
611 /* Streamed or dgram socket? */
612 m_stream
= (stream
== GSOCK_STREAMED
);
614 m_establishing
= false;
616 /* Create the socket */
617 m_fd
= socket(m_peer
->m_realfamily
,
618 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
620 if (m_fd
== INVALID_SOCKET
)
622 m_error
= GSOCK_IOERR
;
626 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
627 gs_gui_functions
->Enable_Events(this);
629 // If the reuse flag is set, use the applicable socket reuse flag
632 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
635 if (m_initialRecvBufferSize
>= 0)
636 setsockopt(m_fd
, SOL_SOCKET
, SO_RCVBUF
, (const char*)&m_initialRecvBufferSize
, sizeof(m_initialRecvBufferSize
));
637 if (m_initialSendBufferSize
>= 0)
638 setsockopt(m_fd
, SOL_SOCKET
, SO_SNDBUF
, (const char*)&m_initialSendBufferSize
, sizeof(m_initialSendBufferSize
));
640 // If a local address has been set, then we need to bind to it before calling connect
641 if (m_local
&& m_local
->m_addr
)
643 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
646 /* Connect it to the peer address, with a timeout (see below) */
647 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
649 if (ret
== SOCKET_ERROR
)
651 err
= WSAGetLastError();
653 /* If connect failed with EWOULDBLOCK and the GSocket object
654 * is in blocking mode, we select() for the specified timeout
655 * checking for writability to see if the connection request
658 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
660 err
= Connect_Timeout();
662 if (err
!= GSOCK_NOERROR
)
665 /* m_error is set in _GSocket_Connect_Timeout */
668 return (GSocketError
) err
;
671 /* If connect failed with EWOULDBLOCK and the GSocket object
672 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
673 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
674 * this way if the connection completes, a GSOCK_CONNECTION
675 * event will be generated, if enabled.
677 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
679 m_establishing
= true;
680 m_error
= GSOCK_WOULDBLOCK
;
681 return GSOCK_WOULDBLOCK
;
684 /* If connect failed with an error other than EWOULDBLOCK,
685 * then the call to GSocket_Connect() has failed.
688 m_error
= GSOCK_IOERR
;
692 return GSOCK_NOERROR
;
695 /* Datagram sockets */
697 /* GSocket_SetNonOriented:
698 * Sets up this socket as a non-connection oriented (datagram) socket.
699 * Before using this function, the local address must have been set
700 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
701 * on success, or one of the following otherwise.
704 * GSOCK_INVSOCK - the socket is in use.
705 * GSOCK_INVADDR - the local address has not been set.
706 * GSOCK_IOERR - low-level error.
708 GSocketError
GSocket::SetNonOriented()
714 if (m_fd
!= INVALID_SOCKET
)
716 m_error
= GSOCK_INVSOCK
;
717 return GSOCK_INVSOCK
;
722 m_error
= GSOCK_INVADDR
;
723 return GSOCK_INVADDR
;
726 /* Initialize all fields */
730 /* Create the socket */
731 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
733 if (m_fd
== INVALID_SOCKET
)
735 m_error
= GSOCK_IOERR
;
739 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
740 gs_gui_functions
->Enable_Events(this);
744 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
748 setsockopt(m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char*)&arg
, sizeof(arg
));
752 /* Bind to the local address,
753 * and retrieve the actual address bound.
755 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
758 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0))
761 m_error
= GSOCK_IOERR
;
766 return GSOCK_NOERROR
;
771 /* Like recv(), send(), ... */
772 int GSocket::Read(char *buffer
, int size
)
778 /* Reenable INPUT events */
779 m_detected
&= ~GSOCK_INPUT_FLAG
;
781 if (m_fd
== INVALID_SOCKET
|| m_server
)
783 m_error
= GSOCK_INVSOCK
;
787 /* If the socket is blocking, wait for data (with a timeout) */
788 if (Input_Timeout() == GSOCK_TIMEDOUT
)
790 m_error
= GSOCK_TIMEDOUT
;
796 ret
= Recv_Stream(buffer
, size
);
798 ret
= Recv_Dgram(buffer
, size
);
800 if (ret
== SOCKET_ERROR
)
802 if (WSAGetLastError() != WSAEWOULDBLOCK
)
803 m_error
= GSOCK_IOERR
;
805 m_error
= GSOCK_WOULDBLOCK
;
812 int GSocket::Write(const char *buffer
, int size
)
818 if (m_fd
== INVALID_SOCKET
|| m_server
)
820 m_error
= GSOCK_INVSOCK
;
824 /* If the socket is blocking, wait for writability (with a timeout) */
825 if (Output_Timeout() == GSOCK_TIMEDOUT
)
830 ret
= Send_Stream(buffer
, size
);
832 ret
= Send_Dgram(buffer
, size
);
834 if (ret
== SOCKET_ERROR
)
836 if (WSAGetLastError() != WSAEWOULDBLOCK
)
837 m_error
= GSOCK_IOERR
;
839 m_error
= GSOCK_WOULDBLOCK
;
841 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
842 * does). Once the first OUTPUT event is received, users can assume
843 * that the socket is writable until a read operation fails. Only then
844 * will further OUTPUT events be posted.
846 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
854 * Polls the socket to determine its status. This function will
855 * check for the events specified in the 'flags' parameter, and
856 * it will return a mask indicating which operations can be
857 * performed. This function won't block, regardless of the
858 * mode (blocking | nonblocking) of the socket.
860 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
862 if (!gs_gui_functions
->CanUseEventLoop())
864 GSocketEventFlags result
= 0;
874 FD_SET(m_fd
, &readfds
);
875 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
876 FD_SET(m_fd
, &writefds
);
877 FD_SET(m_fd
, &exceptfds
);
879 /* Check 'sticky' CONNECTION flag first */
880 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
882 /* If we have already detected a LOST event, then don't try
883 * to do any further processing.
885 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
887 m_establishing
= false;
889 return (GSOCK_LOST_FLAG
& flags
);
893 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
896 /* What to do here? */
897 return (result
& flags
);
900 /* Check for exceptions and errors */
901 if (FD_ISSET(m_fd
, &exceptfds
))
903 m_establishing
= false;
904 m_detected
= GSOCK_LOST_FLAG
;
906 /* LOST event: Abort any further processing */
907 return (GSOCK_LOST_FLAG
& flags
);
910 /* Check for readability */
911 if (FD_ISSET(m_fd
, &readfds
))
913 result
|= GSOCK_INPUT_FLAG
;
915 if (m_server
&& m_stream
)
917 /* This is a TCP server socket that detected a connection.
918 While the INPUT_FLAG is also set, it doesn't matter on
919 this kind of sockets, as we can only Accept() from them. */
920 result
|= GSOCK_CONNECTION_FLAG
;
921 m_detected
|= GSOCK_CONNECTION_FLAG
;
925 /* Check for writability */
926 if (FD_ISSET(m_fd
, &writefds
))
928 if (m_establishing
&& !m_server
)
931 WX_SOCKLEN_T len
= sizeof(error
);
933 m_establishing
= false;
935 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
939 m_detected
= GSOCK_LOST_FLAG
;
941 /* LOST event: Abort any further processing */
942 return (GSOCK_LOST_FLAG
& flags
);
946 result
|= GSOCK_CONNECTION_FLAG
;
947 m_detected
|= GSOCK_CONNECTION_FLAG
;
952 result
|= GSOCK_OUTPUT_FLAG
;
956 return (result
& flags
);
961 return flags
& m_detected
;
967 /* GSocket_SetNonBlocking:
968 * Sets the socket to non-blocking mode. All IO calls will return
971 void GSocket::SetNonBlocking(bool non_block
)
975 m_non_blocking
= non_block
;
978 /* GSocket_SetTimeout:
979 * Sets the timeout for blocking calls. Time is expressed in
982 void GSocket::SetTimeout(unsigned long millis
)
986 m_timeout
.tv_sec
= (millis
/ 1000);
987 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
991 * Returns the last error occurred for this socket. Note that successful
992 * operations do not clear this back to GSOCK_NOERROR, so use it only
995 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1005 * There is data to be read in the input buffer. If, after a read
1006 * operation, there is still data available, the callback function will
1009 * The socket is available for writing. That is, the next write call
1010 * won't block. This event is generated only once, when the connection is
1011 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1012 * when the output buffer empties again. This means that the app should
1013 * assume that it can write since the first OUTPUT event, and no more
1014 * OUTPUT events will be generated unless an error occurs.
1016 * Connection successfully established, for client sockets, or incoming
1017 * client connection, for server sockets. Wait for this event (also watch
1018 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1020 * The connection is lost (or a connection request failed); this could
1021 * be due to a failure, or due to the peer closing it gracefully.
1024 /* GSocket_SetCallback:
1025 * Enables the callbacks specified by 'flags'. Note that 'flags'
1026 * may be a combination of flags OR'ed toghether, so the same
1027 * callback function can be made to accept different events.
1028 * The callback function must have the following prototype:
1030 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1032 void GSocket::SetCallback(GSocketEventFlags flags
,
1033 GSocketCallback callback
, char *cdata
)
1039 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1041 if ((flags
& (1 << count
)) != 0)
1043 m_cbacks
[count
] = callback
;
1044 m_data
[count
] = cdata
;
1049 /* GSocket_UnsetCallback:
1050 * Disables all callbacks specified by 'flags', which may be a
1051 * combination of flags OR'ed toghether.
1053 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1059 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1061 if ((flags
& (1 << count
)) != 0)
1063 m_cbacks
[count
] = NULL
;
1064 m_data
[count
] = NULL
;
1069 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1070 void *optval
, int *optlen
)
1072 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1074 return GSOCK_NOERROR
;
1076 return GSOCK_OPTERR
;
1079 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1080 const void *optval
, int optlen
)
1082 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1084 return GSOCK_NOERROR
;
1086 return GSOCK_OPTERR
;
1089 /* Internals (IO) */
1091 /* _GSocket_Input_Timeout:
1092 * For blocking sockets, wait until data is available or
1093 * until timeout ellapses.
1095 GSocketError
GSocket::Input_Timeout()
1099 if (!m_non_blocking
)
1102 FD_SET(m_fd
, &readfds
);
1103 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1105 m_error
= GSOCK_TIMEDOUT
;
1106 return GSOCK_TIMEDOUT
;
1109 return GSOCK_NOERROR
;
1112 /* _GSocket_Output_Timeout:
1113 * For blocking sockets, wait until data can be sent without
1114 * blocking or until timeout ellapses.
1116 GSocketError
GSocket::Output_Timeout()
1120 if (!m_non_blocking
)
1123 FD_SET(m_fd
, &writefds
);
1124 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1126 m_error
= GSOCK_TIMEDOUT
;
1127 return GSOCK_TIMEDOUT
;
1130 return GSOCK_NOERROR
;
1133 /* _GSocket_Connect_Timeout:
1134 * For blocking sockets, wait until the connection is
1135 * established or fails, or until timeout ellapses.
1137 GSocketError
GSocket::Connect_Timeout()
1143 FD_ZERO(&exceptfds
);
1144 FD_SET(m_fd
, &writefds
);
1145 FD_SET(m_fd
, &exceptfds
);
1146 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1148 m_error
= GSOCK_TIMEDOUT
;
1149 return GSOCK_TIMEDOUT
;
1151 if (!FD_ISSET(m_fd
, &writefds
))
1153 m_error
= GSOCK_IOERR
;
1157 return GSOCK_NOERROR
;
1160 int GSocket::Recv_Stream(char *buffer
, int size
)
1162 return recv(m_fd
, buffer
, size
, 0);
1165 int GSocket::Recv_Dgram(char *buffer
, int size
)
1167 struct sockaddr from
;
1168 WX_SOCKLEN_T fromlen
= sizeof(from
);
1172 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1174 if (ret
== SOCKET_ERROR
)
1175 return SOCKET_ERROR
;
1177 /* Translate a system address into a GSocket address */
1180 m_peer
= GAddress_new();
1183 m_error
= GSOCK_MEMERR
;
1187 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1188 if (err
!= GSOCK_NOERROR
)
1190 GAddress_destroy(m_peer
);
1199 int GSocket::Send_Stream(const char *buffer
, int size
)
1201 return send(m_fd
, buffer
, size
, 0);
1204 int GSocket::Send_Dgram(const char *buffer
, int size
)
1206 struct sockaddr
*addr
;
1212 m_error
= GSOCK_INVADDR
;
1216 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1217 if (err
!= GSOCK_NOERROR
)
1223 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1225 /* Frees memory allocated by _GAddress_translate_to */
1231 /* Compatibility functions for GSocket */
1232 GSocket
*GSocket_new(void)
1234 GSocket
*newsocket
= new GSocket();
1235 if(newsocket
->IsOk())
1243 * -------------------------------------------------------------------------
1245 * -------------------------------------------------------------------------
1248 /* CHECK_ADDRESS verifies that the current address family is either
1249 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1250 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1251 * an appropiate error code.
1253 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1255 #define CHECK_ADDRESS(address, family) \
1257 if (address->m_family == GSOCK_NOFAMILY) \
1258 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1259 return address->m_error; \
1260 if (address->m_family != GSOCK_##family) \
1262 address->m_error = GSOCK_INVADDR; \
1263 return GSOCK_INVADDR; \
1267 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1269 if (address->m_family == GSOCK_NOFAMILY) \
1270 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1272 if (address->m_family != GSOCK_##family) \
1274 address->m_error = GSOCK_INVADDR; \
1280 GAddress
*GAddress_new(void)
1284 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1287 address
->m_family
= GSOCK_NOFAMILY
;
1288 address
->m_addr
= NULL
;
1294 GAddress
*GAddress_copy(GAddress
*address
)
1298 assert(address
!= NULL
);
1300 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1303 memcpy(addr2
, address
, sizeof(GAddress
));
1305 if (address
->m_addr
)
1307 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1308 if (addr2
->m_addr
== NULL
)
1313 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1319 void GAddress_destroy(GAddress
*address
)
1321 assert(address
!= NULL
);
1323 if (address
->m_addr
)
1324 free(address
->m_addr
);
1329 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1331 assert(address
!= NULL
);
1333 address
->m_family
= type
;
1336 GAddressType
GAddress_GetFamily(GAddress
*address
)
1338 assert(address
!= NULL
);
1340 return address
->m_family
;
1343 GSocketError
_GAddress_translate_from(GAddress
*address
,
1344 struct sockaddr
*addr
, int len
)
1346 address
->m_realfamily
= addr
->sa_family
;
1347 switch (addr
->sa_family
)
1350 address
->m_family
= GSOCK_INET
;
1353 address
->m_family
= GSOCK_UNIX
;
1357 address
->m_family
= GSOCK_INET6
;
1362 address
->m_error
= GSOCK_INVOP
;
1367 if (address
->m_addr
)
1368 free(address
->m_addr
);
1370 address
->m_len
= len
;
1371 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1373 if (address
->m_addr
== NULL
)
1375 address
->m_error
= GSOCK_MEMERR
;
1376 return GSOCK_MEMERR
;
1378 memcpy(address
->m_addr
, addr
, len
);
1380 return GSOCK_NOERROR
;
1383 GSocketError
_GAddress_translate_to(GAddress
*address
,
1384 struct sockaddr
**addr
, int *len
)
1386 if (!address
->m_addr
)
1388 address
->m_error
= GSOCK_INVADDR
;
1389 return GSOCK_INVADDR
;
1392 *len
= address
->m_len
;
1393 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1396 address
->m_error
= GSOCK_MEMERR
;
1397 return GSOCK_MEMERR
;
1400 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1401 return GSOCK_NOERROR
;
1405 * -------------------------------------------------------------------------
1406 * Internet address family
1407 * -------------------------------------------------------------------------
1410 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1412 address
->m_len
= sizeof(struct sockaddr_in
);
1413 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1414 if (address
->m_addr
== NULL
)
1416 address
->m_error
= GSOCK_MEMERR
;
1417 return GSOCK_MEMERR
;
1420 address
->m_family
= GSOCK_INET
;
1421 address
->m_realfamily
= AF_INET
;
1422 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1423 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1425 return GSOCK_NOERROR
;
1428 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1431 struct in_addr
*addr
;
1433 assert(address
!= NULL
);
1435 CHECK_ADDRESS(address
, INET
);
1437 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1439 addr
->s_addr
= inet_addr(hostname
);
1441 /* If it is a numeric host name, convert it now */
1442 if (addr
->s_addr
== INADDR_NONE
)
1444 struct in_addr
*array_addr
;
1446 /* It is a real name, we solve it */
1447 if ((he
= gethostbyname(hostname
)) == NULL
)
1449 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1450 address
->m_error
= GSOCK_NOHOST
;
1451 return GSOCK_NOHOST
;
1453 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1454 addr
->s_addr
= array_addr
[0].s_addr
;
1456 return GSOCK_NOERROR
;
1459 GSocketError
GAddress_INET_SetBroadcastAddress(GAddress
*address
)
1461 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1464 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1466 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1469 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1470 unsigned long hostaddr
)
1472 struct in_addr
*addr
;
1474 assert(address
!= NULL
);
1476 CHECK_ADDRESS(address
, INET
);
1478 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1479 addr
->s_addr
= htonl(hostaddr
);
1481 return GSOCK_NOERROR
;
1484 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1485 const char *protocol
)
1488 struct sockaddr_in
*addr
;
1490 assert(address
!= NULL
);
1491 CHECK_ADDRESS(address
, INET
);
1495 address
->m_error
= GSOCK_INVPORT
;
1496 return GSOCK_INVPORT
;
1499 se
= getservbyname(port
, protocol
);
1502 if (isdigit(port
[0]))
1506 port_int
= atoi(port
);
1507 addr
= (struct sockaddr_in
*)address
->m_addr
;
1508 addr
->sin_port
= htons((u_short
) port_int
);
1509 return GSOCK_NOERROR
;
1512 address
->m_error
= GSOCK_INVPORT
;
1513 return GSOCK_INVPORT
;
1516 addr
= (struct sockaddr_in
*)address
->m_addr
;
1517 addr
->sin_port
= se
->s_port
;
1519 return GSOCK_NOERROR
;
1522 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1524 struct sockaddr_in
*addr
;
1526 assert(address
!= NULL
);
1527 CHECK_ADDRESS(address
, INET
);
1529 addr
= (struct sockaddr_in
*)address
->m_addr
;
1530 addr
->sin_port
= htons(port
);
1532 return GSOCK_NOERROR
;
1535 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1539 struct sockaddr_in
*addr
;
1541 assert(address
!= NULL
);
1542 CHECK_ADDRESS(address
, INET
);
1544 addr
= (struct sockaddr_in
*)address
->m_addr
;
1545 addr_buf
= (char *)&(addr
->sin_addr
);
1547 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1550 address
->m_error
= GSOCK_NOHOST
;
1551 return GSOCK_NOHOST
;
1554 strncpy(hostname
, he
->h_name
, sbuf
);
1556 return GSOCK_NOERROR
;
1559 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1561 struct sockaddr_in
*addr
;
1563 assert(address
!= NULL
);
1564 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1566 addr
= (struct sockaddr_in
*)address
->m_addr
;
1568 return ntohl(addr
->sin_addr
.s_addr
);
1571 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1573 struct sockaddr_in
*addr
;
1575 assert(address
!= NULL
);
1576 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1578 addr
= (struct sockaddr_in
*)address
->m_addr
;
1579 return ntohs(addr
->sin_port
);
1583 * -------------------------------------------------------------------------
1584 * Unix address family
1585 * -------------------------------------------------------------------------
1588 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1590 assert (address
!= NULL
);
1591 address
->m_error
= GSOCK_INVADDR
;
1592 return GSOCK_INVADDR
;
1595 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1597 assert (address
!= NULL
);
1598 address
->m_error
= GSOCK_INVADDR
;
1599 return GSOCK_INVADDR
;
1602 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1604 assert (address
!= NULL
);
1605 address
->m_error
= GSOCK_INVADDR
;
1606 return GSOCK_INVADDR
;
1609 #else /* !wxUSE_SOCKETS */
1612 * Translation unit shouldn't be empty, so include this typedef to make the
1613 * compiler (VC++ 6.0, for example) happy
1615 typedef void (*wxDummy
)();
1617 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */