1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
4 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
5 * Purpose: GSocket main MSW file
6 * Licence: The wxWindows licence
8 * -------------------------------------------------------------------------
11 // For compilers that support precompilation, includes "wx.h".
12 #include "wx/wxprec.h"
19 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
20 * warning: conditional expression is constant.
22 # pragma warning(disable:4115)
24 * warning: named type definition in parentheses.
26 # pragma warning(disable:4127)
27 /* GAddress_UNIX_GetPath,
28 * warning: unreferenced formal parameter.
30 # pragma warning(disable:4100)
33 /* windows.h results in tons of warnings at max warning level */
35 # pragma warning(push, 1)
40 # pragma warning(disable:4514)
46 #if defined(__CYGWIN__)
47 //CYGWIN gives annoying warning about runtime stuff if we don't do this
48 # define USE_SYS_TYPES_FD_SET
49 # include <sys/types.h>
54 #ifndef __GSOCKET_STANDALONE__
55 # include "wx/platform.h"
56 # include "wx/setup.h"
59 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
61 #ifndef __GSOCKET_STANDALONE__
62 # include "wx/msw/gsockmsw.h"
63 # include "wx/gsocket.h"
65 # include "gsockmsw.h"
67 #endif /* __GSOCKET_STANDALONE__ */
74 #define isdigit(x) (x > 47 && x < 58)
76 #include "wx/msw/wince/net.h"
85 /* if we use configure for MSW SOCKLEN_T will be already defined */
87 # define SOCKLEN_T int
90 /* Table of GUI-related functions. We must call them indirectly because
91 * of wxBase and GUI separation: */
93 static GSocketGUIFunctionsTable
*gs_gui_functions
;
95 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
98 virtual bool OnInit();
99 virtual void OnExit();
100 virtual bool CanUseEventLoop();
101 virtual bool Init_Socket(GSocket
*socket
);
102 virtual void Destroy_Socket(GSocket
*socket
);
103 virtual void Enable_Events(GSocket
*socket
);
104 virtual void Disable_Events(GSocket
*socket
);
107 bool GSocketGUIFunctionsTableNull::OnInit()
109 void GSocketGUIFunctionsTableNull::OnExit()
111 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
113 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
115 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
117 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
119 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
121 /* Global initialisers */
123 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
125 gs_gui_functions
= guifunc
;
128 int GSocket_Init(void)
132 if (!gs_gui_functions
)
134 static GSocketGUIFunctionsTableNull table
;
135 gs_gui_functions
= &table
;
137 if ( !gs_gui_functions
->OnInit() )
142 /* Initialize WinSocket */
143 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
146 void GSocket_Cleanup(void)
148 if (gs_gui_functions
)
150 gs_gui_functions
->OnExit();
153 /* Cleanup WinSocket */
157 /* Constructors / Destructors for GSocket */
163 m_fd
= INVALID_SOCKET
;
164 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
171 m_error
= GSOCK_NOERROR
;
174 m_non_blocking
= false;
175 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
176 m_timeout
.tv_usec
= 0;
177 m_establishing
= false;
180 assert(gs_gui_functions
);
181 /* Per-socket GUI-specific initialization */
182 m_ok
= gs_gui_functions
->Init_Socket(this);
185 void GSocket::Close()
187 gs_gui_functions
->Disable_Events(this);
189 m_fd
= INVALID_SOCKET
;
196 /* Per-socket GUI-specific cleanup */
197 gs_gui_functions
->Destroy_Socket(this);
199 /* Check that the socket is really shutdowned */
200 if (m_fd
!= INVALID_SOCKET
)
203 /* Destroy private addresses */
205 GAddress_destroy(m_local
);
208 GAddress_destroy(m_peer
);
212 * Disallow further read/write operations on this socket, close
213 * the fd and disable all callbacks.
215 void GSocket::Shutdown()
221 /* If socket has been created, shutdown it */
222 if (m_fd
!= INVALID_SOCKET
)
228 /* Disable GUI callbacks */
229 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
230 m_cbacks
[evt
] = NULL
;
232 m_detected
= GSOCK_LOST_FLAG
;
235 /* Address handling */
241 * Set or get the local or peer address for this socket. The 'set'
242 * functions return GSOCK_NOERROR on success, an error code otherwise.
243 * The 'get' functions return a pointer to a GAddress object on success,
244 * or NULL otherwise, in which case they set the error code of the
245 * corresponding GSocket.
248 * GSOCK_INVSOCK - the socket is not valid.
249 * GSOCK_INVADDR - the address is not valid.
251 GSocketError
GSocket::SetLocal(GAddress
*address
)
255 /* the socket must be initialized, or it must be a server */
256 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
258 m_error
= GSOCK_INVSOCK
;
259 return GSOCK_INVSOCK
;
263 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
265 m_error
= GSOCK_INVADDR
;
266 return GSOCK_INVADDR
;
270 GAddress_destroy(m_local
);
272 m_local
= GAddress_copy(address
);
274 return GSOCK_NOERROR
;
277 GSocketError
GSocket::SetPeer(GAddress
*address
)
282 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
284 m_error
= GSOCK_INVADDR
;
285 return GSOCK_INVADDR
;
289 GAddress_destroy(m_peer
);
291 m_peer
= GAddress_copy(address
);
293 return GSOCK_NOERROR
;
296 GAddress
*GSocket::GetLocal()
299 struct sockaddr addr
;
300 SOCKLEN_T size
= sizeof(addr
);
305 /* try to get it from the m_local var first */
307 return GAddress_copy(m_local
);
309 /* else, if the socket is initialized, try getsockname */
310 if (m_fd
== INVALID_SOCKET
)
312 m_error
= GSOCK_INVSOCK
;
316 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
318 m_error
= GSOCK_IOERR
;
322 /* got a valid address from getsockname, create a GAddress object */
323 if ((address
= GAddress_new()) == NULL
)
325 m_error
= GSOCK_MEMERR
;
329 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
331 GAddress_destroy(address
);
339 GAddress
*GSocket::GetPeer()
343 /* try to get it from the m_peer var */
345 return GAddress_copy(m_peer
);
350 /* Server specific parts */
352 /* GSocket_SetServer:
353 * Sets up this socket as a server. The local address must have been
354 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
355 * Returns GSOCK_NOERROR on success, one of the following otherwise:
358 * GSOCK_INVSOCK - the socket is in use.
359 * GSOCK_INVADDR - the local address has not been set.
360 * GSOCK_IOERR - low-level error.
362 GSocketError
GSocket::SetServer()
368 /* must not be in use */
369 if (m_fd
!= INVALID_SOCKET
)
371 m_error
= GSOCK_INVSOCK
;
372 return GSOCK_INVSOCK
;
375 /* the local addr must have been set */
378 m_error
= GSOCK_INVADDR
;
379 return GSOCK_INVADDR
;
382 /* Initialize all fields */
386 /* Create the socket */
387 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
389 if (m_fd
== INVALID_SOCKET
)
391 m_error
= GSOCK_IOERR
;
395 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
396 gs_gui_functions
->Enable_Events(this);
398 /* allow a socket to re-bind if the socket is in the TIME_WAIT
399 state after being previously closed.
402 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
405 /* Bind to the local address,
406 * retrieve the actual address bound,
407 * and listen up to 5 connections.
409 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
412 (SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
413 (listen(m_fd
, 5) != 0))
416 m_error
= GSOCK_IOERR
;
420 return GSOCK_NOERROR
;
423 /* GSocket_WaitConnection:
424 * Waits for an incoming client connection. Returns a pointer to
425 * a GSocket object, or NULL if there was an error, in which case
426 * the last error field will be updated for the calling GSocket.
428 * Error codes (set in the calling GSocket)
429 * GSOCK_INVSOCK - the socket is not valid or not a server.
430 * GSOCK_TIMEDOUT - timeout, no incoming connections.
431 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
432 * GSOCK_MEMERR - couldn't allocate memory.
433 * GSOCK_IOERR - low-level error.
435 GSocket
*GSocket::WaitConnection()
438 struct sockaddr from
;
439 SOCKLEN_T fromlen
= sizeof(from
);
445 /* Reenable CONNECTION events */
446 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
448 /* If the socket has already been created, we exit immediately */
449 if (m_fd
== INVALID_SOCKET
|| !m_server
)
451 m_error
= GSOCK_INVSOCK
;
455 /* Create a GSocket object for the new connection */
456 connection
= GSocket_new();
460 m_error
= GSOCK_MEMERR
;
464 /* Wait for a connection (with timeout) */
465 if (Input_Timeout() == GSOCK_TIMEDOUT
)
468 /* m_error set by _GSocket_Input_Timeout */
472 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
474 if (connection
->m_fd
== INVALID_SOCKET
)
476 if (WSAGetLastError() == WSAEWOULDBLOCK
)
477 m_error
= GSOCK_WOULDBLOCK
;
479 m_error
= GSOCK_IOERR
;
485 /* Initialize all fields */
486 connection
->m_server
= false;
487 connection
->m_stream
= true;
489 /* Setup the peer address field */
490 connection
->m_peer
= GAddress_new();
491 if (!connection
->m_peer
)
494 m_error
= GSOCK_MEMERR
;
497 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
498 if (err
!= GSOCK_NOERROR
)
500 GAddress_destroy(connection
->m_peer
);
506 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
507 gs_gui_functions
->Enable_Events(connection
);
512 /* GSocket_SetReusable:
513 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
514 * make the appropriate setsockopt() call.
515 * Implemented as a GSocket function because clients (ie, wxSocketServer)
516 * don't have access to the GSocket struct information.
517 * Returns true if the flag was set correctly, false if an error occured
518 * (ie, if the parameter was NULL)
520 bool GSocket::SetReusable()
522 /* socket must not be null, and must not be in use/already bound */
523 if (this && m_fd
== INVALID_SOCKET
) {
530 /* Client specific parts */
533 * For stream (connection oriented) sockets, GSocket_Connect() tries
534 * to establish a client connection to a server using the peer address
535 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
536 * connection has been succesfully established, or one of the error
537 * codes listed below. Note that for nonblocking sockets, a return
538 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
539 * request can be completed later; you should use GSocket_Select()
540 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
541 * corresponding asynchronous events.
543 * For datagram (non connection oriented) sockets, GSocket_Connect()
544 * just sets the peer address established with GSocket_SetPeer() as
545 * default destination.
548 * GSOCK_INVSOCK - the socket is in use or not valid.
549 * GSOCK_INVADDR - the peer address has not been established.
550 * GSOCK_TIMEDOUT - timeout, the connection failed.
551 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
552 * GSOCK_MEMERR - couldn't allocate memory.
553 * GSOCK_IOERR - low-level error.
555 GSocketError
GSocket::Connect(GSocketStream stream
)
562 /* Enable CONNECTION events (needed for nonblocking connections) */
563 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
565 if (m_fd
!= INVALID_SOCKET
)
567 m_error
= GSOCK_INVSOCK
;
568 return GSOCK_INVSOCK
;
573 m_error
= GSOCK_INVADDR
;
574 return GSOCK_INVADDR
;
577 /* Streamed or dgram socket? */
578 m_stream
= (stream
== GSOCK_STREAMED
);
580 m_establishing
= false;
582 /* Create the socket */
583 m_fd
= socket(m_peer
->m_realfamily
,
584 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
586 if (m_fd
== INVALID_SOCKET
)
588 m_error
= GSOCK_IOERR
;
592 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
593 gs_gui_functions
->Enable_Events(this);
595 /* Connect it to the peer address, with a timeout (see below) */
596 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
598 if (ret
== SOCKET_ERROR
)
600 err
= WSAGetLastError();
602 /* If connect failed with EWOULDBLOCK and the GSocket object
603 * is in blocking mode, we select() for the specified timeout
604 * checking for writability to see if the connection request
607 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
609 err
= Connect_Timeout();
611 if (err
!= GSOCK_NOERROR
)
614 /* m_error is set in _GSocket_Connect_Timeout */
617 return (GSocketError
) err
;
620 /* If connect failed with EWOULDBLOCK and the GSocket object
621 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
622 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
623 * this way if the connection completes, a GSOCK_CONNECTION
624 * event will be generated, if enabled.
626 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
628 m_establishing
= true;
629 m_error
= GSOCK_WOULDBLOCK
;
630 return GSOCK_WOULDBLOCK
;
633 /* If connect failed with an error other than EWOULDBLOCK,
634 * then the call to GSocket_Connect() has failed.
637 m_error
= GSOCK_IOERR
;
641 return GSOCK_NOERROR
;
644 /* Datagram sockets */
646 /* GSocket_SetNonOriented:
647 * Sets up this socket as a non-connection oriented (datagram) socket.
648 * Before using this function, the local address must have been set
649 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
650 * on success, or one of the following otherwise.
653 * GSOCK_INVSOCK - the socket is in use.
654 * GSOCK_INVADDR - the local address has not been set.
655 * GSOCK_IOERR - low-level error.
657 GSocketError
GSocket::SetNonOriented()
663 if (m_fd
!= INVALID_SOCKET
)
665 m_error
= GSOCK_INVSOCK
;
666 return GSOCK_INVSOCK
;
671 m_error
= GSOCK_INVADDR
;
672 return GSOCK_INVADDR
;
675 /* Initialize all fields */
679 /* Create the socket */
680 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
682 if (m_fd
== INVALID_SOCKET
)
684 m_error
= GSOCK_IOERR
;
688 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
689 gs_gui_functions
->Enable_Events(this);
691 /* Bind to the local address,
692 * and retrieve the actual address bound.
694 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
697 (SOCKLEN_T
*)&m_local
->m_len
) != 0))
700 m_error
= GSOCK_IOERR
;
704 return GSOCK_NOERROR
;
709 /* Like recv(), send(), ... */
710 int GSocket::Read(char *buffer
, int size
)
716 /* Reenable INPUT events */
717 m_detected
&= ~GSOCK_INPUT_FLAG
;
719 if (m_fd
== INVALID_SOCKET
|| m_server
)
721 m_error
= GSOCK_INVSOCK
;
725 /* If the socket is blocking, wait for data (with a timeout) */
726 if (Input_Timeout() == GSOCK_TIMEDOUT
)
731 ret
= Recv_Stream(buffer
, size
);
733 ret
= Recv_Dgram(buffer
, size
);
735 if (ret
== SOCKET_ERROR
)
737 if (WSAGetLastError() != WSAEWOULDBLOCK
)
738 m_error
= GSOCK_IOERR
;
740 m_error
= GSOCK_WOULDBLOCK
;
747 int GSocket::Write(const char *buffer
, int size
)
753 if (m_fd
== INVALID_SOCKET
|| m_server
)
755 m_error
= GSOCK_INVSOCK
;
759 /* If the socket is blocking, wait for writability (with a timeout) */
760 if (Output_Timeout() == GSOCK_TIMEDOUT
)
765 ret
= Send_Stream(buffer
, size
);
767 ret
= Send_Dgram(buffer
, size
);
769 if (ret
== SOCKET_ERROR
)
771 if (WSAGetLastError() != WSAEWOULDBLOCK
)
772 m_error
= GSOCK_IOERR
;
774 m_error
= GSOCK_WOULDBLOCK
;
776 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
777 * does). Once the first OUTPUT event is received, users can assume
778 * that the socket is writable until a read operation fails. Only then
779 * will further OUTPUT events be posted.
781 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
789 * Polls the socket to determine its status. This function will
790 * check for the events specified in the 'flags' parameter, and
791 * it will return a mask indicating which operations can be
792 * performed. This function won't block, regardless of the
793 * mode (blocking | nonblocking) of the socket.
795 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
797 if (!gs_gui_functions
->CanUseEventLoop())
799 GSocketEventFlags result
= 0;
809 FD_SET(m_fd
, &readfds
);
810 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
811 FD_SET(m_fd
, &writefds
);
812 FD_SET(m_fd
, &exceptfds
);
814 /* Check 'sticky' CONNECTION flag first */
815 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
817 /* If we have already detected a LOST event, then don't try
818 * to do any further processing.
820 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
822 m_establishing
= false;
824 return (GSOCK_LOST_FLAG
& flags
);
828 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
831 /* What to do here? */
832 return (result
& flags
);
835 /* Check for readability */
836 if (FD_ISSET(m_fd
, &readfds
))
840 if (!m_stream
|| recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
842 result
|= GSOCK_INPUT_FLAG
;
846 if (m_server
&& m_stream
)
848 result
|= GSOCK_CONNECTION_FLAG
;
849 m_detected
|= GSOCK_CONNECTION_FLAG
;
853 m_detected
= GSOCK_LOST_FLAG
;
854 m_establishing
= false;
856 /* LOST event: Abort any further processing */
857 return (GSOCK_LOST_FLAG
& flags
);
862 /* Check for writability */
863 if (FD_ISSET(m_fd
, &writefds
))
865 if (m_establishing
&& !m_server
)
868 SOCKLEN_T len
= sizeof(error
);
870 m_establishing
= false;
872 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
876 m_detected
= GSOCK_LOST_FLAG
;
878 /* LOST event: Abort any further processing */
879 return (GSOCK_LOST_FLAG
& flags
);
883 result
|= GSOCK_CONNECTION_FLAG
;
884 m_detected
|= GSOCK_CONNECTION_FLAG
;
889 result
|= GSOCK_OUTPUT_FLAG
;
893 /* Check for exceptions and errors (is this useful in Unices?) */
894 if (FD_ISSET(m_fd
, &exceptfds
))
896 m_establishing
= false;
897 m_detected
= GSOCK_LOST_FLAG
;
899 /* LOST event: Abort any further processing */
900 return (GSOCK_LOST_FLAG
& flags
);
903 return (result
& flags
);
908 return flags
& m_detected
;
914 /* GSocket_SetNonBlocking:
915 * Sets the socket to non-blocking mode. All IO calls will return
918 void GSocket::SetNonBlocking(bool non_block
)
922 m_non_blocking
= non_block
;
925 /* GSocket_SetTimeout:
926 * Sets the timeout for blocking calls. Time is expressed in
929 void GSocket::SetTimeout(unsigned long millis
)
933 m_timeout
.tv_sec
= (millis
/ 1000);
934 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
938 * Returns the last error occured for this socket. Note that successful
939 * operations do not clear this back to GSOCK_NOERROR, so use it only
942 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
952 * There is data to be read in the input buffer. If, after a read
953 * operation, there is still data available, the callback function will
956 * The socket is available for writing. That is, the next write call
957 * won't block. This event is generated only once, when the connection is
958 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
959 * when the output buffer empties again. This means that the app should
960 * assume that it can write since the first OUTPUT event, and no more
961 * OUTPUT events will be generated unless an error occurs.
963 * Connection succesfully established, for client sockets, or incoming
964 * client connection, for server sockets. Wait for this event (also watch
965 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
967 * The connection is lost (or a connection request failed); this could
968 * be due to a failure, or due to the peer closing it gracefully.
971 /* GSocket_SetCallback:
972 * Enables the callbacks specified by 'flags'. Note that 'flags'
973 * may be a combination of flags OR'ed toghether, so the same
974 * callback function can be made to accept different events.
975 * The callback function must have the following prototype:
977 * void function(GSocket *socket, GSocketEvent event, char *cdata)
979 void GSocket::SetCallback(GSocketEventFlags flags
,
980 GSocketCallback callback
, char *cdata
)
986 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
988 if ((flags
& (1 << count
)) != 0)
990 m_cbacks
[count
] = callback
;
991 m_data
[count
] = cdata
;
996 /* GSocket_UnsetCallback:
997 * Disables all callbacks specified by 'flags', which may be a
998 * combination of flags OR'ed toghether.
1000 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1006 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1008 if ((flags
& (1 << count
)) != 0)
1010 m_cbacks
[count
] = NULL
;
1011 m_data
[count
] = NULL
;
1016 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1017 void *optval
, int *optlen
)
1019 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1021 return GSOCK_NOERROR
;
1023 return GSOCK_OPTERR
;
1026 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1027 const void *optval
, int optlen
)
1029 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1031 return GSOCK_NOERROR
;
1033 return GSOCK_OPTERR
;
1036 /* Internals (IO) */
1038 /* _GSocket_Input_Timeout:
1039 * For blocking sockets, wait until data is available or
1040 * until timeout ellapses.
1042 GSocketError
GSocket::Input_Timeout()
1046 if (!m_non_blocking
)
1049 FD_SET(m_fd
, &readfds
);
1050 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1052 m_error
= GSOCK_TIMEDOUT
;
1053 return GSOCK_TIMEDOUT
;
1056 return GSOCK_NOERROR
;
1059 /* _GSocket_Output_Timeout:
1060 * For blocking sockets, wait until data can be sent without
1061 * blocking or until timeout ellapses.
1063 GSocketError
GSocket::Output_Timeout()
1067 if (!m_non_blocking
)
1070 FD_SET(m_fd
, &writefds
);
1071 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1073 m_error
= GSOCK_TIMEDOUT
;
1074 return GSOCK_TIMEDOUT
;
1077 return GSOCK_NOERROR
;
1080 /* _GSocket_Connect_Timeout:
1081 * For blocking sockets, wait until the connection is
1082 * established or fails, or until timeout ellapses.
1084 GSocketError
GSocket::Connect_Timeout()
1090 FD_ZERO(&exceptfds
);
1091 FD_SET(m_fd
, &writefds
);
1092 FD_SET(m_fd
, &exceptfds
);
1093 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1095 m_error
= GSOCK_TIMEDOUT
;
1096 return GSOCK_TIMEDOUT
;
1098 if (!FD_ISSET(m_fd
, &writefds
))
1100 m_error
= GSOCK_IOERR
;
1104 return GSOCK_NOERROR
;
1107 int GSocket::Recv_Stream(char *buffer
, int size
)
1109 return recv(m_fd
, buffer
, size
, 0);
1112 int GSocket::Recv_Dgram(char *buffer
, int size
)
1114 struct sockaddr from
;
1115 SOCKLEN_T fromlen
= sizeof(from
);
1119 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1121 if (ret
== SOCKET_ERROR
)
1122 return SOCKET_ERROR
;
1124 /* Translate a system address into a GSocket address */
1127 m_peer
= GAddress_new();
1130 m_error
= GSOCK_MEMERR
;
1134 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1135 if (err
!= GSOCK_NOERROR
)
1137 GAddress_destroy(m_peer
);
1146 int GSocket::Send_Stream(const char *buffer
, int size
)
1148 return send(m_fd
, buffer
, size
, 0);
1151 int GSocket::Send_Dgram(const char *buffer
, int size
)
1153 struct sockaddr
*addr
;
1159 m_error
= GSOCK_INVADDR
;
1163 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1164 if (err
!= GSOCK_NOERROR
)
1170 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1172 /* Frees memory allocated by _GAddress_translate_to */
1178 /* Compatibility functions for GSocket */
1179 GSocket
*GSocket_new(void)
1181 GSocket
*newsocket
= new GSocket();
1182 if(newsocket
->IsOk())
1190 * -------------------------------------------------------------------------
1192 * -------------------------------------------------------------------------
1195 /* CHECK_ADDRESS verifies that the current address family is either
1196 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1197 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1198 * an appropiate error code.
1200 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1202 #define CHECK_ADDRESS(address, family) \
1204 if (address->m_family == GSOCK_NOFAMILY) \
1205 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1206 return address->m_error; \
1207 if (address->m_family != GSOCK_##family) \
1209 address->m_error = GSOCK_INVADDR; \
1210 return GSOCK_INVADDR; \
1214 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1216 if (address->m_family == GSOCK_NOFAMILY) \
1217 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1219 if (address->m_family != GSOCK_##family) \
1221 address->m_error = GSOCK_INVADDR; \
1227 GAddress
*GAddress_new(void)
1231 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1234 address
->m_family
= GSOCK_NOFAMILY
;
1235 address
->m_addr
= NULL
;
1241 GAddress
*GAddress_copy(GAddress
*address
)
1245 assert(address
!= NULL
);
1247 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1250 memcpy(addr2
, address
, sizeof(GAddress
));
1252 if (address
->m_addr
)
1254 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1255 if (addr2
->m_addr
== NULL
)
1260 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1266 void GAddress_destroy(GAddress
*address
)
1268 assert(address
!= NULL
);
1270 if (address
->m_addr
)
1271 free(address
->m_addr
);
1276 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1278 assert(address
!= NULL
);
1280 address
->m_family
= type
;
1283 GAddressType
GAddress_GetFamily(GAddress
*address
)
1285 assert(address
!= NULL
);
1287 return address
->m_family
;
1290 GSocketError
_GAddress_translate_from(GAddress
*address
,
1291 struct sockaddr
*addr
, int len
)
1293 address
->m_realfamily
= addr
->sa_family
;
1294 switch (addr
->sa_family
)
1297 address
->m_family
= GSOCK_INET
;
1300 address
->m_family
= GSOCK_UNIX
;
1304 address
->m_family
= GSOCK_INET6
;
1309 address
->m_error
= GSOCK_INVOP
;
1314 if (address
->m_addr
)
1315 free(address
->m_addr
);
1317 address
->m_len
= len
;
1318 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1320 if (address
->m_addr
== NULL
)
1322 address
->m_error
= GSOCK_MEMERR
;
1323 return GSOCK_MEMERR
;
1325 memcpy(address
->m_addr
, addr
, len
);
1327 return GSOCK_NOERROR
;
1330 GSocketError
_GAddress_translate_to(GAddress
*address
,
1331 struct sockaddr
**addr
, int *len
)
1333 if (!address
->m_addr
)
1335 address
->m_error
= GSOCK_INVADDR
;
1336 return GSOCK_INVADDR
;
1339 *len
= address
->m_len
;
1340 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1343 address
->m_error
= GSOCK_MEMERR
;
1344 return GSOCK_MEMERR
;
1347 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1348 return GSOCK_NOERROR
;
1352 * -------------------------------------------------------------------------
1353 * Internet address family
1354 * -------------------------------------------------------------------------
1357 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1359 address
->m_len
= sizeof(struct sockaddr_in
);
1360 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1361 if (address
->m_addr
== NULL
)
1363 address
->m_error
= GSOCK_MEMERR
;
1364 return GSOCK_MEMERR
;
1367 address
->m_family
= GSOCK_INET
;
1368 address
->m_realfamily
= AF_INET
;
1369 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1370 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1372 return GSOCK_NOERROR
;
1375 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1378 struct in_addr
*addr
;
1380 assert(address
!= NULL
);
1382 CHECK_ADDRESS(address
, INET
);
1384 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1386 addr
->s_addr
= inet_addr(hostname
);
1388 /* If it is a numeric host name, convert it now */
1389 if (addr
->s_addr
== INADDR_NONE
)
1391 struct in_addr
*array_addr
;
1393 /* It is a real name, we solve it */
1394 if ((he
= gethostbyname(hostname
)) == NULL
)
1396 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1397 address
->m_error
= GSOCK_NOHOST
;
1398 return GSOCK_NOHOST
;
1400 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1401 addr
->s_addr
= array_addr
[0].s_addr
;
1403 return GSOCK_NOERROR
;
1406 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1408 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1411 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1412 unsigned long hostaddr
)
1414 struct in_addr
*addr
;
1416 assert(address
!= NULL
);
1418 CHECK_ADDRESS(address
, INET
);
1420 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1421 addr
->s_addr
= htonl(hostaddr
);;
1423 return GSOCK_NOERROR
;
1426 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1427 const char *protocol
)
1430 struct sockaddr_in
*addr
;
1432 assert(address
!= NULL
);
1433 CHECK_ADDRESS(address
, INET
);
1437 address
->m_error
= GSOCK_INVPORT
;
1438 return GSOCK_INVPORT
;
1441 se
= getservbyname(port
, protocol
);
1444 if (isdigit(port
[0]))
1448 port_int
= atoi(port
);
1449 addr
= (struct sockaddr_in
*)address
->m_addr
;
1450 addr
->sin_port
= htons((u_short
) port_int
);
1451 return GSOCK_NOERROR
;
1454 address
->m_error
= GSOCK_INVPORT
;
1455 return GSOCK_INVPORT
;
1458 addr
= (struct sockaddr_in
*)address
->m_addr
;
1459 addr
->sin_port
= se
->s_port
;
1461 return GSOCK_NOERROR
;
1464 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1466 struct sockaddr_in
*addr
;
1468 assert(address
!= NULL
);
1469 CHECK_ADDRESS(address
, INET
);
1471 addr
= (struct sockaddr_in
*)address
->m_addr
;
1472 addr
->sin_port
= htons(port
);
1474 return GSOCK_NOERROR
;
1477 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1481 struct sockaddr_in
*addr
;
1483 assert(address
!= NULL
);
1484 CHECK_ADDRESS(address
, INET
);
1486 addr
= (struct sockaddr_in
*)address
->m_addr
;
1487 addr_buf
= (char *)&(addr
->sin_addr
);
1489 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1492 address
->m_error
= GSOCK_NOHOST
;
1493 return GSOCK_NOHOST
;
1496 strncpy(hostname
, he
->h_name
, sbuf
);
1498 return GSOCK_NOERROR
;
1501 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1503 struct sockaddr_in
*addr
;
1505 assert(address
!= NULL
);
1506 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1508 addr
= (struct sockaddr_in
*)address
->m_addr
;
1510 return ntohl(addr
->sin_addr
.s_addr
);
1513 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1515 struct sockaddr_in
*addr
;
1517 assert(address
!= NULL
);
1518 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1520 addr
= (struct sockaddr_in
*)address
->m_addr
;
1521 return ntohs(addr
->sin_port
);
1525 * -------------------------------------------------------------------------
1526 * Unix address family
1527 * -------------------------------------------------------------------------
1530 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1532 assert (address
!= NULL
);
1533 address
->m_error
= GSOCK_INVADDR
;
1534 return GSOCK_INVADDR
;
1537 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1539 assert (address
!= NULL
);
1540 address
->m_error
= GSOCK_INVADDR
;
1541 return GSOCK_INVADDR
;
1544 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1546 assert (address
!= NULL
);
1547 address
->m_error
= GSOCK_INVADDR
;
1548 return GSOCK_INVADDR
;
1551 #else /* !wxUSE_SOCKETS */
1554 * Translation unit shouldn't be empty, so include this typedef to make the
1555 * compiler (VC++ 6.0, for example) happy
1557 typedef void (*wxDummy
)();
1559 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */