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
92 typedef struct sockaddr_storage wxSockAddr
;
94 typedef struct sockaddr wxSockAddr
;
98 /* Table of GUI-related functions. We must call them indirectly because
99 * of wxBase and GUI separation: */
101 static GSocketGUIFunctionsTable
*gs_gui_functions
;
103 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
106 virtual bool OnInit();
107 virtual void OnExit();
108 virtual bool CanUseEventLoop();
109 virtual bool Init_Socket(GSocket
*socket
);
110 virtual void Destroy_Socket(GSocket
*socket
);
111 virtual void Enable_Events(GSocket
*socket
);
112 virtual void Disable_Events(GSocket
*socket
);
115 bool GSocketGUIFunctionsTableNull::OnInit()
117 void GSocketGUIFunctionsTableNull::OnExit()
119 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
121 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
123 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
125 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
127 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
129 /* Global initialisers */
131 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
133 gs_gui_functions
= guifunc
;
136 int GSocket_Init(void)
140 if (!gs_gui_functions
)
142 static GSocketGUIFunctionsTableNull table
;
143 gs_gui_functions
= &table
;
145 if ( !gs_gui_functions
->OnInit() )
150 /* Initialize WinSocket */
151 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
154 void GSocket_Cleanup(void)
156 if (gs_gui_functions
)
158 gs_gui_functions
->OnExit();
161 /* Cleanup WinSocket */
165 /* Constructors / Destructors for GSocket */
171 m_fd
= INVALID_SOCKET
;
172 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
179 m_error
= GSOCK_NOERROR
;
182 m_non_blocking
= false;
183 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
184 m_timeout
.tv_usec
= 0;
185 m_establishing
= false;
189 m_initialRecvBufferSize
= -1;
190 m_initialSendBufferSize
= -1;
192 assert(gs_gui_functions
);
193 /* Per-socket GUI-specific initialization */
194 m_ok
= gs_gui_functions
->Init_Socket(this);
197 void GSocket::Close()
199 gs_gui_functions
->Disable_Events(this);
201 m_fd
= INVALID_SOCKET
;
208 /* Per-socket GUI-specific cleanup */
209 gs_gui_functions
->Destroy_Socket(this);
211 /* Check that the socket is really shutdowned */
212 if (m_fd
!= INVALID_SOCKET
)
215 /* Destroy private addresses */
217 GAddress_destroy(m_local
);
220 GAddress_destroy(m_peer
);
224 * Disallow further read/write operations on this socket, close
225 * the fd and disable all callbacks.
227 void GSocket::Shutdown()
233 /* If socket has been created, shutdown it */
234 if (m_fd
!= INVALID_SOCKET
)
236 shutdown(m_fd
, 1 /* SD_SEND */);
240 /* Disable GUI callbacks */
241 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
242 m_cbacks
[evt
] = NULL
;
244 m_detected
= GSOCK_LOST_FLAG
;
247 /* Address handling */
253 * Set or get the local or peer address for this socket. The 'set'
254 * functions return GSOCK_NOERROR on success, an error code otherwise.
255 * The 'get' functions return a pointer to a GAddress object on success,
256 * or NULL otherwise, in which case they set the error code of the
257 * corresponding GSocket.
260 * GSOCK_INVSOCK - the socket is not valid.
261 * GSOCK_INVADDR - the address is not valid.
263 GSocketError
GSocket::SetLocal(GAddress
*address
)
267 /* the socket must be initialized, or it must be a server */
268 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
270 m_error
= GSOCK_INVSOCK
;
271 return GSOCK_INVSOCK
;
275 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
277 m_error
= GSOCK_INVADDR
;
278 return GSOCK_INVADDR
;
282 GAddress_destroy(m_local
);
284 m_local
= GAddress_copy(address
);
286 return GSOCK_NOERROR
;
289 GSocketError
GSocket::SetPeer(GAddress
*address
)
294 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
296 m_error
= GSOCK_INVADDR
;
297 return GSOCK_INVADDR
;
301 GAddress_destroy(m_peer
);
303 m_peer
= GAddress_copy(address
);
305 return GSOCK_NOERROR
;
308 GAddress
*GSocket::GetLocal()
312 WX_SOCKLEN_T size
= sizeof(addr
);
317 /* try to get it from the m_local var first */
319 return GAddress_copy(m_local
);
321 /* else, if the socket is initialized, try getsockname */
322 if (m_fd
== INVALID_SOCKET
)
324 m_error
= GSOCK_INVSOCK
;
328 if (getsockname(m_fd
, (sockaddr
*)&addr
, &size
) == SOCKET_ERROR
)
330 m_error
= GSOCK_IOERR
;
334 /* got a valid address from getsockname, create a GAddress object */
335 if ((address
= GAddress_new()) == NULL
)
337 m_error
= GSOCK_MEMERR
;
341 if ((err
= _GAddress_translate_from(address
, (sockaddr
*)&addr
, size
)) != GSOCK_NOERROR
)
343 GAddress_destroy(address
);
351 GAddress
*GSocket::GetPeer()
355 /* try to get it from the m_peer var */
357 return GAddress_copy(m_peer
);
362 /* Server specific parts */
364 /* GSocket_SetServer:
365 * Sets up this socket as a server. The local address must have been
366 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
367 * Returns GSOCK_NOERROR on success, one of the following otherwise:
370 * GSOCK_INVSOCK - the socket is in use.
371 * GSOCK_INVADDR - the local address has not been set.
372 * GSOCK_IOERR - low-level error.
374 GSocketError
GSocket::SetServer()
380 /* must not be in use */
381 if (m_fd
!= INVALID_SOCKET
)
383 m_error
= GSOCK_INVSOCK
;
384 return GSOCK_INVSOCK
;
387 /* the local addr must have been set */
390 m_error
= GSOCK_INVADDR
;
391 return GSOCK_INVADDR
;
394 /* Initialize all fields */
398 /* Create the socket */
399 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
401 if (m_fd
== INVALID_SOCKET
)
403 m_error
= GSOCK_IOERR
;
407 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
408 gs_gui_functions
->Enable_Events(this);
410 /* allow a socket to re-bind if the socket is in the TIME_WAIT
411 state after being previously closed.
415 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
418 /* Bind to the local address,
419 * retrieve the actual address bound,
420 * and listen up to 5 connections.
422 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
425 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
426 (listen(m_fd
, 5) != 0))
429 m_error
= GSOCK_IOERR
;
433 return GSOCK_NOERROR
;
436 /* GSocket_WaitConnection:
437 * Waits for an incoming client connection. Returns a pointer to
438 * a GSocket object, or NULL if there was an error, in which case
439 * the last error field will be updated for the calling GSocket.
441 * Error codes (set in the calling GSocket)
442 * GSOCK_INVSOCK - the socket is not valid or not a server.
443 * GSOCK_TIMEDOUT - timeout, no incoming connections.
444 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
445 * GSOCK_MEMERR - couldn't allocate memory.
446 * GSOCK_IOERR - low-level error.
448 GSocket
*GSocket::WaitConnection()
452 WX_SOCKLEN_T fromlen
= sizeof(from
);
458 /* Reenable CONNECTION events */
459 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
461 /* If the socket has already been created, we exit immediately */
462 if (m_fd
== INVALID_SOCKET
|| !m_server
)
464 m_error
= GSOCK_INVSOCK
;
468 /* Create a GSocket object for the new connection */
469 connection
= GSocket_new();
473 m_error
= GSOCK_MEMERR
;
477 /* Wait for a connection (with timeout) */
478 if (Input_Timeout() == GSOCK_TIMEDOUT
)
481 /* m_error set by _GSocket_Input_Timeout */
485 connection
->m_fd
= accept(m_fd
, (sockaddr
*)&from
, &fromlen
);
487 if (connection
->m_fd
== INVALID_SOCKET
)
489 if (WSAGetLastError() == WSAEWOULDBLOCK
)
490 m_error
= GSOCK_WOULDBLOCK
;
492 m_error
= GSOCK_IOERR
;
498 /* Initialize all fields */
499 connection
->m_server
= false;
500 connection
->m_stream
= true;
502 /* Setup the peer address field */
503 connection
->m_peer
= GAddress_new();
504 if (!connection
->m_peer
)
507 m_error
= GSOCK_MEMERR
;
510 err
= _GAddress_translate_from(connection
->m_peer
, (sockaddr
*)&from
, fromlen
);
511 if (err
!= GSOCK_NOERROR
)
513 GAddress_destroy(connection
->m_peer
);
519 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
520 gs_gui_functions
->Enable_Events(connection
);
525 /* GSocket_SetReusable:
526 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
527 * make the appropriate setsockopt() call.
528 * Implemented as a GSocket function because clients (ie, wxSocketServer)
529 * don't have access to the GSocket struct information.
530 * Returns true if the flag was set correctly, false if an error occurred
531 * (ie, if the parameter was NULL)
533 bool GSocket::SetReusable()
535 /* socket must not be null, and must not be in use/already bound */
536 if (this && m_fd
== INVALID_SOCKET
) {
543 /* GSocket_SetBroadcast:
544 * Simply sets the m_broadcast flag on the socket. GSocket_SetServer will
545 * make the appropriate setsockopt() call.
546 * Implemented as a GSocket function because clients (ie, wxSocketServer)
547 * don't have access to the GSocket struct information.
548 * Returns true if the flag was set correctly, false if an error occurred
549 * (ie, if the parameter was NULL)
551 bool GSocket::SetBroadcast()
553 /* socket must not be in use/already bound */
554 if (m_fd
== INVALID_SOCKET
) {
561 bool GSocket::DontDoBind()
563 /* socket must not be in use/already bound */
564 if (m_fd
== INVALID_SOCKET
) {
571 /* Client specific parts */
574 * For stream (connection oriented) sockets, GSocket_Connect() tries
575 * to establish a client connection to a server using the peer address
576 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
577 * connection has been successfully established, or one of the error
578 * codes listed below. Note that for nonblocking sockets, a return
579 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
580 * request can be completed later; you should use GSocket_Select()
581 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
582 * corresponding asynchronous events.
584 * For datagram (non connection oriented) sockets, GSocket_Connect()
585 * just sets the peer address established with GSocket_SetPeer() as
586 * default destination.
589 * GSOCK_INVSOCK - the socket is in use or not valid.
590 * GSOCK_INVADDR - the peer address has not been established.
591 * GSOCK_TIMEDOUT - timeout, the connection failed.
592 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
593 * GSOCK_MEMERR - couldn't allocate memory.
594 * GSOCK_IOERR - low-level error.
596 GSocketError
GSocket::Connect(GSocketStream stream
)
603 /* Enable CONNECTION events (needed for nonblocking connections) */
604 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
606 if (m_fd
!= INVALID_SOCKET
)
608 m_error
= GSOCK_INVSOCK
;
609 return GSOCK_INVSOCK
;
614 m_error
= GSOCK_INVADDR
;
615 return GSOCK_INVADDR
;
618 /* Streamed or dgram socket? */
619 m_stream
= (stream
== GSOCK_STREAMED
);
621 m_establishing
= false;
623 /* Create the socket */
624 m_fd
= socket(m_peer
->m_realfamily
,
625 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
627 if (m_fd
== INVALID_SOCKET
)
629 m_error
= GSOCK_IOERR
;
633 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
634 gs_gui_functions
->Enable_Events(this);
636 // If the reuse flag is set, use the applicable socket reuse flag
639 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
642 if (m_initialRecvBufferSize
>= 0)
643 setsockopt(m_fd
, SOL_SOCKET
, SO_RCVBUF
, (const char*)&m_initialRecvBufferSize
, sizeof(m_initialRecvBufferSize
));
644 if (m_initialSendBufferSize
>= 0)
645 setsockopt(m_fd
, SOL_SOCKET
, SO_SNDBUF
, (const char*)&m_initialSendBufferSize
, sizeof(m_initialSendBufferSize
));
647 // If a local address has been set, then we need to bind to it before calling connect
648 if (m_local
&& m_local
->m_addr
)
650 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
653 /* Connect it to the peer address, with a timeout (see below) */
654 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
656 if (ret
== SOCKET_ERROR
)
658 err
= WSAGetLastError();
660 /* If connect failed with EWOULDBLOCK and the GSocket object
661 * is in blocking mode, we select() for the specified timeout
662 * checking for writability to see if the connection request
665 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
667 err
= Connect_Timeout();
669 if (err
!= GSOCK_NOERROR
)
672 /* m_error is set in _GSocket_Connect_Timeout */
675 return (GSocketError
) err
;
678 /* If connect failed with EWOULDBLOCK and the GSocket object
679 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
680 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
681 * this way if the connection completes, a GSOCK_CONNECTION
682 * event will be generated, if enabled.
684 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
686 m_establishing
= true;
687 m_error
= GSOCK_WOULDBLOCK
;
688 return GSOCK_WOULDBLOCK
;
691 /* If connect failed with an error other than EWOULDBLOCK,
692 * then the call to GSocket_Connect() has failed.
695 m_error
= GSOCK_IOERR
;
699 return GSOCK_NOERROR
;
702 /* Datagram sockets */
704 /* GSocket_SetNonOriented:
705 * Sets up this socket as a non-connection oriented (datagram) socket.
706 * Before using this function, the local address must have been set
707 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
708 * on success, or one of the following otherwise.
711 * GSOCK_INVSOCK - the socket is in use.
712 * GSOCK_INVADDR - the local address has not been set.
713 * GSOCK_IOERR - low-level error.
715 GSocketError
GSocket::SetNonOriented()
721 if (m_fd
!= INVALID_SOCKET
)
723 m_error
= GSOCK_INVSOCK
;
724 return GSOCK_INVSOCK
;
729 m_error
= GSOCK_INVADDR
;
730 return GSOCK_INVADDR
;
733 /* Initialize all fields */
737 /* Create the socket */
738 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
740 if (m_fd
== INVALID_SOCKET
)
742 m_error
= GSOCK_IOERR
;
746 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
747 gs_gui_functions
->Enable_Events(this);
751 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
755 setsockopt(m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char*)&arg
, sizeof(arg
));
759 /* Bind to the local address,
760 * and retrieve the actual address bound.
762 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
765 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0))
768 m_error
= GSOCK_IOERR
;
773 return GSOCK_NOERROR
;
778 /* Like recv(), send(), ... */
779 int GSocket::Read(char *buffer
, int size
)
785 /* Reenable INPUT events */
786 m_detected
&= ~GSOCK_INPUT_FLAG
;
788 if (m_fd
== INVALID_SOCKET
|| m_server
)
790 m_error
= GSOCK_INVSOCK
;
794 /* If the socket is blocking, wait for data (with a timeout) */
795 if (Input_Timeout() == GSOCK_TIMEDOUT
)
797 m_error
= GSOCK_TIMEDOUT
;
803 ret
= Recv_Stream(buffer
, size
);
805 ret
= Recv_Dgram(buffer
, size
);
807 if (ret
== SOCKET_ERROR
)
809 if (WSAGetLastError() != WSAEWOULDBLOCK
)
810 m_error
= GSOCK_IOERR
;
812 m_error
= GSOCK_WOULDBLOCK
;
819 int GSocket::Write(const char *buffer
, int size
)
825 if (m_fd
== INVALID_SOCKET
|| m_server
)
827 m_error
= GSOCK_INVSOCK
;
831 /* If the socket is blocking, wait for writability (with a timeout) */
832 if (Output_Timeout() == GSOCK_TIMEDOUT
)
837 ret
= Send_Stream(buffer
, size
);
839 ret
= Send_Dgram(buffer
, size
);
841 if (ret
== SOCKET_ERROR
)
843 if (WSAGetLastError() != WSAEWOULDBLOCK
)
844 m_error
= GSOCK_IOERR
;
846 m_error
= GSOCK_WOULDBLOCK
;
848 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
849 * does). Once the first OUTPUT event is received, users can assume
850 * that the socket is writable until a read operation fails. Only then
851 * will further OUTPUT events be posted.
853 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
861 * Polls the socket to determine its status. This function will
862 * check for the events specified in the 'flags' parameter, and
863 * it will return a mask indicating which operations can be
864 * performed. This function won't block, regardless of the
865 * mode (blocking | nonblocking) of the socket.
867 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
869 if (!gs_gui_functions
->CanUseEventLoop())
871 GSocketEventFlags result
= 0;
881 FD_SET(m_fd
, &readfds
);
882 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
883 FD_SET(m_fd
, &writefds
);
884 FD_SET(m_fd
, &exceptfds
);
886 /* Check 'sticky' CONNECTION flag first */
887 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
889 /* If we have already detected a LOST event, then don't try
890 * to do any further processing.
892 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
894 m_establishing
= false;
896 return (GSOCK_LOST_FLAG
& flags
);
900 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
903 /* What to do here? */
904 return (result
& flags
);
907 /* Check for exceptions and errors */
908 if (FD_ISSET(m_fd
, &exceptfds
))
910 m_establishing
= false;
911 m_detected
= GSOCK_LOST_FLAG
;
913 /* LOST event: Abort any further processing */
914 return (GSOCK_LOST_FLAG
& flags
);
917 /* Check for readability */
918 if (FD_ISSET(m_fd
, &readfds
))
920 result
|= GSOCK_INPUT_FLAG
;
922 if (m_server
&& m_stream
)
924 /* This is a TCP server socket that detected a connection.
925 While the INPUT_FLAG is also set, it doesn't matter on
926 this kind of sockets, as we can only Accept() from them. */
927 result
|= GSOCK_CONNECTION_FLAG
;
928 m_detected
|= GSOCK_CONNECTION_FLAG
;
932 /* Check for writability */
933 if (FD_ISSET(m_fd
, &writefds
))
935 if (m_establishing
&& !m_server
)
938 WX_SOCKLEN_T len
= sizeof(error
);
940 m_establishing
= false;
942 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
946 m_detected
= GSOCK_LOST_FLAG
;
948 /* LOST event: Abort any further processing */
949 return (GSOCK_LOST_FLAG
& flags
);
953 result
|= GSOCK_CONNECTION_FLAG
;
954 m_detected
|= GSOCK_CONNECTION_FLAG
;
959 result
|= GSOCK_OUTPUT_FLAG
;
963 return (result
& flags
);
968 return flags
& m_detected
;
974 /* GSocket_SetNonBlocking:
975 * Sets the socket to non-blocking mode. All IO calls will return
978 void GSocket::SetNonBlocking(bool non_block
)
982 m_non_blocking
= non_block
;
985 /* GSocket_SetTimeout:
986 * Sets the timeout for blocking calls. Time is expressed in
989 void GSocket::SetTimeout(unsigned long millis
)
993 m_timeout
.tv_sec
= (millis
/ 1000);
994 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
998 * Returns the last error occurred for this socket. Note that successful
999 * operations do not clear this back to GSOCK_NOERROR, so use it only
1002 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1012 * There is data to be read in the input buffer. If, after a read
1013 * operation, there is still data available, the callback function will
1016 * The socket is available for writing. That is, the next write call
1017 * won't block. This event is generated only once, when the connection is
1018 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1019 * when the output buffer empties again. This means that the app should
1020 * assume that it can write since the first OUTPUT event, and no more
1021 * OUTPUT events will be generated unless an error occurs.
1023 * Connection successfully established, for client sockets, or incoming
1024 * client connection, for server sockets. Wait for this event (also watch
1025 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1027 * The connection is lost (or a connection request failed); this could
1028 * be due to a failure, or due to the peer closing it gracefully.
1031 /* GSocket_SetCallback:
1032 * Enables the callbacks specified by 'flags'. Note that 'flags'
1033 * may be a combination of flags OR'ed toghether, so the same
1034 * callback function can be made to accept different events.
1035 * The callback function must have the following prototype:
1037 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1039 void GSocket::SetCallback(GSocketEventFlags flags
,
1040 GSocketCallback callback
, char *cdata
)
1046 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1048 if ((flags
& (1 << count
)) != 0)
1050 m_cbacks
[count
] = callback
;
1051 m_data
[count
] = cdata
;
1056 /* GSocket_UnsetCallback:
1057 * Disables all callbacks specified by 'flags', which may be a
1058 * combination of flags OR'ed toghether.
1060 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1066 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1068 if ((flags
& (1 << count
)) != 0)
1070 m_cbacks
[count
] = NULL
;
1071 m_data
[count
] = NULL
;
1076 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1077 void *optval
, int *optlen
)
1079 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1081 return GSOCK_NOERROR
;
1083 return GSOCK_OPTERR
;
1086 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1087 const void *optval
, int optlen
)
1089 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1091 return GSOCK_NOERROR
;
1093 return GSOCK_OPTERR
;
1096 /* Internals (IO) */
1098 /* _GSocket_Input_Timeout:
1099 * For blocking sockets, wait until data is available or
1100 * until timeout ellapses.
1102 GSocketError
GSocket::Input_Timeout()
1106 if (!m_non_blocking
)
1109 FD_SET(m_fd
, &readfds
);
1110 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1112 m_error
= GSOCK_TIMEDOUT
;
1113 return GSOCK_TIMEDOUT
;
1116 return GSOCK_NOERROR
;
1119 /* _GSocket_Output_Timeout:
1120 * For blocking sockets, wait until data can be sent without
1121 * blocking or until timeout ellapses.
1123 GSocketError
GSocket::Output_Timeout()
1127 if (!m_non_blocking
)
1130 FD_SET(m_fd
, &writefds
);
1131 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1133 m_error
= GSOCK_TIMEDOUT
;
1134 return GSOCK_TIMEDOUT
;
1137 return GSOCK_NOERROR
;
1140 /* _GSocket_Connect_Timeout:
1141 * For blocking sockets, wait until the connection is
1142 * established or fails, or until timeout ellapses.
1144 GSocketError
GSocket::Connect_Timeout()
1150 FD_ZERO(&exceptfds
);
1151 FD_SET(m_fd
, &writefds
);
1152 FD_SET(m_fd
, &exceptfds
);
1153 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1155 m_error
= GSOCK_TIMEDOUT
;
1156 return GSOCK_TIMEDOUT
;
1158 if (!FD_ISSET(m_fd
, &writefds
))
1160 m_error
= GSOCK_IOERR
;
1164 return GSOCK_NOERROR
;
1167 int GSocket::Recv_Stream(char *buffer
, int size
)
1169 return recv(m_fd
, buffer
, size
, 0);
1172 int GSocket::Recv_Dgram(char *buffer
, int size
)
1175 WX_SOCKLEN_T fromlen
= sizeof(from
);
1179 ret
= recvfrom(m_fd
, buffer
, size
, 0, (sockaddr
*)&from
, &fromlen
);
1181 if (ret
== SOCKET_ERROR
)
1182 return SOCKET_ERROR
;
1184 /* Translate a system address into a GSocket address */
1187 m_peer
= GAddress_new();
1190 m_error
= GSOCK_MEMERR
;
1194 err
= _GAddress_translate_from(m_peer
, (sockaddr
*)&from
, fromlen
);
1195 if (err
!= GSOCK_NOERROR
)
1197 GAddress_destroy(m_peer
);
1206 int GSocket::Send_Stream(const char *buffer
, int size
)
1208 return send(m_fd
, buffer
, size
, 0);
1211 int GSocket::Send_Dgram(const char *buffer
, int size
)
1213 struct sockaddr
*addr
;
1219 m_error
= GSOCK_INVADDR
;
1223 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1224 if (err
!= GSOCK_NOERROR
)
1230 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1232 /* Frees memory allocated by _GAddress_translate_to */
1238 /* Compatibility functions for GSocket */
1239 GSocket
*GSocket_new(void)
1241 GSocket
*newsocket
= new GSocket();
1242 if(newsocket
->IsOk())
1250 * -------------------------------------------------------------------------
1252 * -------------------------------------------------------------------------
1255 /* CHECK_ADDRESS verifies that the current address family is either
1256 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1257 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1258 * an appropiate error code.
1260 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1262 #define CHECK_ADDRESS(address, family) \
1264 if (address->m_family == GSOCK_NOFAMILY) \
1265 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1266 return address->m_error; \
1267 if (address->m_family != GSOCK_##family) \
1269 address->m_error = GSOCK_INVADDR; \
1270 return GSOCK_INVADDR; \
1274 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1276 if (address->m_family == GSOCK_NOFAMILY) \
1277 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1279 if (address->m_family != GSOCK_##family) \
1281 address->m_error = GSOCK_INVADDR; \
1287 GAddress
*GAddress_new(void)
1291 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1294 address
->m_family
= GSOCK_NOFAMILY
;
1295 address
->m_addr
= NULL
;
1301 GAddress
*GAddress_copy(GAddress
*address
)
1305 assert(address
!= NULL
);
1307 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1310 memcpy(addr2
, address
, sizeof(GAddress
));
1312 if (address
->m_addr
)
1314 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1315 if (addr2
->m_addr
== NULL
)
1320 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1326 void GAddress_destroy(GAddress
*address
)
1328 assert(address
!= NULL
);
1330 if (address
->m_addr
)
1331 free(address
->m_addr
);
1336 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1338 assert(address
!= NULL
);
1340 address
->m_family
= type
;
1343 GAddressType
GAddress_GetFamily(GAddress
*address
)
1345 assert(address
!= NULL
);
1347 return address
->m_family
;
1350 GSocketError
_GAddress_translate_from(GAddress
*address
,
1351 struct sockaddr
*addr
, int len
)
1353 address
->m_realfamily
= addr
->sa_family
;
1354 switch (addr
->sa_family
)
1357 address
->m_family
= GSOCK_INET
;
1360 address
->m_family
= GSOCK_UNIX
;
1364 address
->m_family
= GSOCK_INET6
;
1369 address
->m_error
= GSOCK_INVOP
;
1374 if (address
->m_addr
)
1375 free(address
->m_addr
);
1377 address
->m_len
= len
;
1378 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1380 if (address
->m_addr
== NULL
)
1382 address
->m_error
= GSOCK_MEMERR
;
1383 return GSOCK_MEMERR
;
1385 memcpy(address
->m_addr
, addr
, len
);
1387 return GSOCK_NOERROR
;
1390 GSocketError
_GAddress_translate_to(GAddress
*address
,
1391 struct sockaddr
**addr
, int *len
)
1393 if (!address
->m_addr
)
1395 address
->m_error
= GSOCK_INVADDR
;
1396 return GSOCK_INVADDR
;
1399 *len
= address
->m_len
;
1400 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1403 address
->m_error
= GSOCK_MEMERR
;
1404 return GSOCK_MEMERR
;
1407 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1408 return GSOCK_NOERROR
;
1412 * -------------------------------------------------------------------------
1413 * Internet address family
1414 * -------------------------------------------------------------------------
1417 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1419 address
->m_len
= sizeof(struct sockaddr_in
);
1420 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1421 if (address
->m_addr
== NULL
)
1423 address
->m_error
= GSOCK_MEMERR
;
1424 return GSOCK_MEMERR
;
1427 address
->m_family
= GSOCK_INET
;
1428 address
->m_realfamily
= AF_INET
;
1429 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1430 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1432 return GSOCK_NOERROR
;
1435 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1438 struct in_addr
*addr
;
1440 assert(address
!= NULL
);
1442 CHECK_ADDRESS(address
, INET
);
1444 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1446 addr
->s_addr
= inet_addr(hostname
);
1448 /* If it is a numeric host name, convert it now */
1449 if (addr
->s_addr
== INADDR_NONE
)
1451 struct in_addr
*array_addr
;
1453 /* It is a real name, we solve it */
1454 if ((he
= gethostbyname(hostname
)) == NULL
)
1456 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1457 address
->m_error
= GSOCK_NOHOST
;
1458 return GSOCK_NOHOST
;
1460 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1461 addr
->s_addr
= array_addr
[0].s_addr
;
1463 return GSOCK_NOERROR
;
1466 GSocketError
GAddress_INET_SetBroadcastAddress(GAddress
*address
)
1468 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1471 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1473 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1476 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1477 unsigned long hostaddr
)
1479 struct in_addr
*addr
;
1481 assert(address
!= NULL
);
1483 CHECK_ADDRESS(address
, INET
);
1485 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1486 addr
->s_addr
= htonl(hostaddr
);
1488 return GSOCK_NOERROR
;
1491 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1492 const char *protocol
)
1495 struct sockaddr_in
*addr
;
1497 assert(address
!= NULL
);
1498 CHECK_ADDRESS(address
, INET
);
1502 address
->m_error
= GSOCK_INVPORT
;
1503 return GSOCK_INVPORT
;
1506 se
= getservbyname(port
, protocol
);
1509 if (isdigit(port
[0]))
1513 port_int
= atoi(port
);
1514 addr
= (struct sockaddr_in
*)address
->m_addr
;
1515 addr
->sin_port
= htons((u_short
) port_int
);
1516 return GSOCK_NOERROR
;
1519 address
->m_error
= GSOCK_INVPORT
;
1520 return GSOCK_INVPORT
;
1523 addr
= (struct sockaddr_in
*)address
->m_addr
;
1524 addr
->sin_port
= se
->s_port
;
1526 return GSOCK_NOERROR
;
1529 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1531 struct sockaddr_in
*addr
;
1533 assert(address
!= NULL
);
1534 CHECK_ADDRESS(address
, INET
);
1536 addr
= (struct sockaddr_in
*)address
->m_addr
;
1537 addr
->sin_port
= htons(port
);
1539 return GSOCK_NOERROR
;
1542 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1546 struct sockaddr_in
*addr
;
1548 assert(address
!= NULL
);
1549 CHECK_ADDRESS(address
, INET
);
1551 addr
= (struct sockaddr_in
*)address
->m_addr
;
1552 addr_buf
= (char *)&(addr
->sin_addr
);
1554 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1557 address
->m_error
= GSOCK_NOHOST
;
1558 return GSOCK_NOHOST
;
1561 strncpy(hostname
, he
->h_name
, sbuf
);
1563 return GSOCK_NOERROR
;
1566 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1568 struct sockaddr_in
*addr
;
1570 assert(address
!= NULL
);
1571 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1573 addr
= (struct sockaddr_in
*)address
->m_addr
;
1575 return ntohl(addr
->sin_addr
.s_addr
);
1578 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1580 struct sockaddr_in
*addr
;
1582 assert(address
!= NULL
);
1583 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1585 addr
= (struct sockaddr_in
*)address
->m_addr
;
1586 return ntohs(addr
->sin_port
);
1592 * -------------------------------------------------------------------------
1593 * Internet IPv6 address family
1594 * -------------------------------------------------------------------------
1596 #include "ws2tcpip.h"
1599 #pragma comment(lib,"ws2_32")
1600 #endif // __VISUALC__
1602 GSocketError
_GAddress_Init_INET6(GAddress
*address
)
1604 struct in6_addr any_address
= IN6ADDR_ANY_INIT
;
1605 address
->m_len
= sizeof(struct sockaddr_in6
);
1606 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1607 if (address
->m_addr
== NULL
)
1609 address
->m_error
= GSOCK_MEMERR
;
1610 return GSOCK_MEMERR
;
1612 memset(address
->m_addr
,0,address
->m_len
);
1614 address
->m_family
= GSOCK_INET6
;
1615 address
->m_realfamily
= AF_INET6
;
1616 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_family
= AF_INET6
;
1617 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= any_address
;
1619 return GSOCK_NOERROR
;
1622 GSocketError
GAddress_INET6_SetHostName(GAddress
*address
, const char *hostname
)
1624 assert(address
!= NULL
);
1625 CHECK_ADDRESS(address
, INET6
);
1628 memset( & hints
, 0, sizeof( hints
) );
1629 hints
.ai_family
= AF_INET6
;
1630 addrinfo
* info
= 0;
1631 if ( getaddrinfo( hostname
, "0", & hints
, & info
) || ! info
)
1633 address
->m_error
= GSOCK_NOHOST
;
1634 return GSOCK_NOHOST
;
1637 memcpy( address
->m_addr
, info
->ai_addr
, info
->ai_addrlen
);
1638 freeaddrinfo( info
);
1639 return GSOCK_NOERROR
;
1642 GSocketError
GAddress_INET6_SetAnyAddress(GAddress
*address
)
1644 assert(address
!= NULL
);
1646 CHECK_ADDRESS(address
, INET6
);
1648 struct in6_addr addr
;
1649 memset( & addr
, 0, sizeof( addr
) );
1650 return GAddress_INET6_SetHostAddress(address
, addr
);
1652 GSocketError
GAddress_INET6_SetHostAddress(GAddress
*address
,
1653 struct in6_addr hostaddr
)
1655 assert(address
!= NULL
);
1657 CHECK_ADDRESS(address
, INET6
);
1659 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= hostaddr
;
1661 return GSOCK_NOERROR
;
1664 GSocketError
GAddress_INET6_SetPortName(GAddress
*address
, const char *port
,
1665 const char *protocol
)
1668 struct sockaddr_in6
*addr
;
1670 assert(address
!= NULL
);
1671 CHECK_ADDRESS(address
, INET6
);
1675 address
->m_error
= GSOCK_INVPORT
;
1676 return GSOCK_INVPORT
;
1679 se
= getservbyname(port
, protocol
);
1682 if (isdigit(port
[0]))
1686 port_int
= atoi(port
);
1687 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1688 addr
->sin6_port
= htons((u_short
) port_int
);
1689 return GSOCK_NOERROR
;
1692 address
->m_error
= GSOCK_INVPORT
;
1693 return GSOCK_INVPORT
;
1696 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1697 addr
->sin6_port
= se
->s_port
;
1699 return GSOCK_NOERROR
;
1702 GSocketError
GAddress_INET6_SetPort(GAddress
*address
, unsigned short port
)
1704 struct sockaddr_in6
*addr
;
1706 assert(address
!= NULL
);
1707 CHECK_ADDRESS(address
, INET6
);
1709 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1710 addr
->sin6_port
= htons(port
);
1712 return GSOCK_NOERROR
;
1715 GSocketError
GAddress_INET6_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1719 struct sockaddr_in6
*addr
;
1721 assert(address
!= NULL
);
1722 CHECK_ADDRESS(address
, INET6
);
1724 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1725 addr_buf
= (char *)&(addr
->sin6_addr
);
1727 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin6_addr
), AF_INET6
);
1730 address
->m_error
= GSOCK_NOHOST
;
1731 return GSOCK_NOHOST
;
1734 strncpy(hostname
, he
->h_name
, sbuf
);
1736 return GSOCK_NOERROR
;
1739 GSocketError
GAddress_INET6_GetHostAddress(GAddress
*address
,struct in6_addr
*hostaddr
)
1741 assert(address
!= NULL
);
1742 assert(hostaddr
!= NULL
);
1743 CHECK_ADDRESS_RETVAL(address
, INET6
, GSOCK_INVADDR
);
1744 *hostaddr
= ( (struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
;
1745 return GSOCK_NOERROR
;
1748 unsigned short GAddress_INET6_GetPort(GAddress
*address
)
1750 assert(address
!= NULL
);
1751 CHECK_ADDRESS_RETVAL(address
, INET6
, 0);
1753 return ntohs( ((struct sockaddr_in6
*)address
->m_addr
)->sin6_port
);
1756 #endif // wxUSE_IPV6
1759 * -------------------------------------------------------------------------
1760 * Unix address family
1761 * -------------------------------------------------------------------------
1764 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1766 assert (address
!= NULL
);
1767 address
->m_error
= GSOCK_INVADDR
;
1768 return GSOCK_INVADDR
;
1771 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1773 assert (address
!= NULL
);
1774 address
->m_error
= GSOCK_INVADDR
;
1775 return GSOCK_INVADDR
;
1778 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1780 assert (address
!= NULL
);
1781 address
->m_error
= GSOCK_INVADDR
;
1782 return GSOCK_INVADDR
;
1785 #else /* !wxUSE_SOCKETS */
1788 * Translation unit shouldn't be empty, so include this typedef to make the
1789 * compiler (VC++ 6.0, for example) happy
1791 typedef void (*wxDummy
)();
1793 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */