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 // ============================================================================
13 // ============================================================================
15 // ----------------------------------------------------------------------------
17 // ----------------------------------------------------------------------------
19 // For compilers that support precompilation, includes "wx.h".
20 #include "wx/wxprec.h"
27 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
28 * warning: conditional expression is constant.
30 # pragma warning(disable:4115)
32 * warning: named type definition in parentheses.
34 # pragma warning(disable:4127)
35 /* GAddress_UNIX_GetPath,
36 * warning: unreferenced formal parameter.
38 # pragma warning(disable:4100)
41 /* windows.h results in tons of warnings at max warning level */
43 # pragma warning(push, 1)
48 # pragma warning(disable:4514)
56 #ifndef __GSOCKET_STANDALONE__
57 # include "wx/platform.h"
58 # include "wx/setup.h"
61 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
63 #ifndef __GSOCKET_STANDALONE__
64 # include "wx/msw/gsockmsw.h"
65 # include "wx/gsocket.h"
67 # include "gsockmsw.h"
69 #endif /* __GSOCKET_STANDALONE__ */
76 #define isdigit(x) (x > 47 && x < 58)
78 #include "wx/msw/wince/net.h"
87 /* if we use configure for MSW SOCKLEN_T will be already defined */
89 # define SOCKLEN_T int
92 /* Table of GUI-related functions. We must call them indirectly because
93 * of wxBase and GUI separation: */
95 static GSocketGUIFunctionsTable
*gs_gui_functions
;
97 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
100 virtual bool OnInit();
101 virtual void OnExit();
102 virtual bool CanUseEventLoop();
103 virtual bool Init_Socket(GSocket
*socket
);
104 virtual void Destroy_Socket(GSocket
*socket
);
105 virtual void Enable_Events(GSocket
*socket
);
106 virtual void Disable_Events(GSocket
*socket
);
109 bool GSocketGUIFunctionsTableNull::OnInit()
111 void GSocketGUIFunctionsTableNull::OnExit()
113 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
115 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
117 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
119 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
121 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
123 /* Global initialisers */
125 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
127 gs_gui_functions
= guifunc
;
130 int GSocket_Init(void)
134 if (!gs_gui_functions
)
136 static GSocketGUIFunctionsTableNull table
;
137 gs_gui_functions
= &table
;
139 if ( !gs_gui_functions
->OnInit() )
144 /* Initialize WinSocket */
145 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
148 void GSocket_Cleanup(void)
150 if (gs_gui_functions
)
152 gs_gui_functions
->OnExit();
155 /* Cleanup WinSocket */
159 /* Constructors / Destructors for GSocket */
165 m_fd
= INVALID_SOCKET
;
166 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
173 m_error
= GSOCK_NOERROR
;
176 m_non_blocking
= false;
177 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
178 m_timeout
.tv_usec
= 0;
179 m_establishing
= FALSE
;
182 assert(gs_gui_functions
);
183 /* Per-socket GUI-specific initialization */
184 m_ok
= gs_gui_functions
->Init_Socket(this);
187 void GSocket::Close()
189 gs_gui_functions
->Disable_Events(this);
191 m_fd
= INVALID_SOCKET
;
198 /* Per-socket GUI-specific cleanup */
199 gs_gui_functions
->Destroy_Socket(this);
201 /* Check that the socket is really shutdowned */
202 if (m_fd
!= INVALID_SOCKET
)
205 /* Destroy private addresses */
207 GAddress_destroy(m_local
);
210 GAddress_destroy(m_peer
);
214 * Disallow further read/write operations on this socket, close
215 * the fd and disable all callbacks.
217 void GSocket::Shutdown()
223 /* If socket has been created, shutdown it */
224 if (m_fd
!= INVALID_SOCKET
)
230 /* Disable GUI callbacks */
231 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
232 m_cbacks
[evt
] = NULL
;
234 m_detected
= GSOCK_LOST_FLAG
;
237 /* Address handling */
243 * Set or get the local or peer address for this socket. The 'set'
244 * functions return GSOCK_NOERROR on success, an error code otherwise.
245 * The 'get' functions return a pointer to a GAddress object on success,
246 * or NULL otherwise, in which case they set the error code of the
247 * corresponding GSocket.
250 * GSOCK_INVSOCK - the socket is not valid.
251 * GSOCK_INVADDR - the address is not valid.
253 GSocketError
GSocket::SetLocal(GAddress
*address
)
257 /* the socket must be initialized, or it must be a server */
258 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
260 m_error
= GSOCK_INVSOCK
;
261 return GSOCK_INVSOCK
;
265 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
267 m_error
= GSOCK_INVADDR
;
268 return GSOCK_INVADDR
;
272 GAddress_destroy(m_local
);
274 m_local
= GAddress_copy(address
);
276 return GSOCK_NOERROR
;
279 GSocketError
GSocket::SetPeer(GAddress
*address
)
284 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
286 m_error
= GSOCK_INVADDR
;
287 return GSOCK_INVADDR
;
291 GAddress_destroy(m_peer
);
293 m_peer
= GAddress_copy(address
);
295 return GSOCK_NOERROR
;
298 GAddress
*GSocket::GetLocal()
301 struct sockaddr addr
;
302 SOCKLEN_T size
= sizeof(addr
);
307 /* try to get it from the m_local var first */
309 return GAddress_copy(m_local
);
311 /* else, if the socket is initialized, try getsockname */
312 if (m_fd
== INVALID_SOCKET
)
314 m_error
= GSOCK_INVSOCK
;
318 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
320 m_error
= GSOCK_IOERR
;
324 /* got a valid address from getsockname, create a GAddress object */
325 if ((address
= GAddress_new()) == NULL
)
327 m_error
= GSOCK_MEMERR
;
331 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
333 GAddress_destroy(address
);
341 GAddress
*GSocket::GetPeer()
345 /* try to get it from the m_peer var */
347 return GAddress_copy(m_peer
);
352 /* Server specific parts */
354 /* GSocket_SetServer:
355 * Sets up this socket as a server. The local address must have been
356 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
357 * Returns GSOCK_NOERROR on success, one of the following otherwise:
360 * GSOCK_INVSOCK - the socket is in use.
361 * GSOCK_INVADDR - the local address has not been set.
362 * GSOCK_IOERR - low-level error.
364 GSocketError
GSocket::SetServer()
370 /* must not be in use */
371 if (m_fd
!= INVALID_SOCKET
)
373 m_error
= GSOCK_INVSOCK
;
374 return GSOCK_INVSOCK
;
377 /* the local addr must have been set */
380 m_error
= GSOCK_INVADDR
;
381 return GSOCK_INVADDR
;
384 /* Initialize all fields */
388 /* Create the socket */
389 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
391 if (m_fd
== INVALID_SOCKET
)
393 m_error
= GSOCK_IOERR
;
397 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
398 gs_gui_functions
->Enable_Events(this);
400 /* allow a socket to re-bind if the socket is in the TIME_WAIT
401 state after being previously closed.
404 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
407 /* Bind to the local address,
408 * retrieve the actual address bound,
409 * and listen up to 5 connections.
411 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
414 (SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
415 (listen(m_fd
, 5) != 0))
418 m_error
= GSOCK_IOERR
;
422 return GSOCK_NOERROR
;
425 /* GSocket_WaitConnection:
426 * Waits for an incoming client connection. Returns a pointer to
427 * a GSocket object, or NULL if there was an error, in which case
428 * the last error field will be updated for the calling GSocket.
430 * Error codes (set in the calling GSocket)
431 * GSOCK_INVSOCK - the socket is not valid or not a server.
432 * GSOCK_TIMEDOUT - timeout, no incoming connections.
433 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
434 * GSOCK_MEMERR - couldn't allocate memory.
435 * GSOCK_IOERR - low-level error.
437 GSocket
*GSocket::WaitConnection()
440 struct sockaddr from
;
441 SOCKLEN_T fromlen
= sizeof(from
);
447 /* Reenable CONNECTION events */
448 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
450 /* If the socket has already been created, we exit immediately */
451 if (m_fd
== INVALID_SOCKET
|| !m_server
)
453 m_error
= GSOCK_INVSOCK
;
457 /* Create a GSocket object for the new connection */
458 connection
= GSocket_new();
462 m_error
= GSOCK_MEMERR
;
466 /* Wait for a connection (with timeout) */
467 if (Input_Timeout() == GSOCK_TIMEDOUT
)
470 /* m_error set by _GSocket_Input_Timeout */
474 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
476 if (connection
->m_fd
== INVALID_SOCKET
)
478 if (WSAGetLastError() == WSAEWOULDBLOCK
)
479 m_error
= GSOCK_WOULDBLOCK
;
481 m_error
= GSOCK_IOERR
;
487 /* Initialize all fields */
488 connection
->m_server
= FALSE
;
489 connection
->m_stream
= TRUE
;
491 /* Setup the peer address field */
492 connection
->m_peer
= GAddress_new();
493 if (!connection
->m_peer
)
496 m_error
= GSOCK_MEMERR
;
499 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
500 if (err
!= GSOCK_NOERROR
)
502 GAddress_destroy(connection
->m_peer
);
508 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
509 gs_gui_functions
->Enable_Events(connection
);
514 /* GSocket_SetReusable:
515 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
516 * make the appropriate setsockopt() call.
517 * Implemented as a GSocket function because clients (ie, wxSocketServer)
518 * don't have access to the GSocket struct information.
519 * Returns TRUE if the flag was set correctly, FALSE if an error occured
520 * (ie, if the parameter was NULL)
522 int GSocket::SetReusable()
524 /* socket must not be null, and must not be in use/already bound */
525 if (this && m_fd
== INVALID_SOCKET
) {
532 /* Client specific parts */
535 * For stream (connection oriented) sockets, GSocket_Connect() tries
536 * to establish a client connection to a server using the peer address
537 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
538 * connection has been succesfully established, or one of the error
539 * codes listed below. Note that for nonblocking sockets, a return
540 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
541 * request can be completed later; you should use GSocket_Select()
542 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
543 * corresponding asynchronous events.
545 * For datagram (non connection oriented) sockets, GSocket_Connect()
546 * just sets the peer address established with GSocket_SetPeer() as
547 * default destination.
550 * GSOCK_INVSOCK - the socket is in use or not valid.
551 * GSOCK_INVADDR - the peer address has not been established.
552 * GSOCK_TIMEDOUT - timeout, the connection failed.
553 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
554 * GSOCK_MEMERR - couldn't allocate memory.
555 * GSOCK_IOERR - low-level error.
557 GSocketError
GSocket::Connect(GSocketStream stream
)
564 /* Enable CONNECTION events (needed for nonblocking connections) */
565 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
567 if (m_fd
!= INVALID_SOCKET
)
569 m_error
= GSOCK_INVSOCK
;
570 return GSOCK_INVSOCK
;
575 m_error
= GSOCK_INVADDR
;
576 return GSOCK_INVADDR
;
579 /* Streamed or dgram socket? */
580 m_stream
= (stream
== GSOCK_STREAMED
);
582 m_establishing
= FALSE
;
584 /* Create the socket */
585 m_fd
= socket(m_peer
->m_realfamily
,
586 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
588 if (m_fd
== INVALID_SOCKET
)
590 m_error
= GSOCK_IOERR
;
594 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
595 gs_gui_functions
->Enable_Events(this);
597 /* Connect it to the peer address, with a timeout (see below) */
598 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
600 if (ret
== SOCKET_ERROR
)
602 err
= WSAGetLastError();
604 /* If connect failed with EWOULDBLOCK and the GSocket object
605 * is in blocking mode, we select() for the specified timeout
606 * checking for writability to see if the connection request
609 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
611 err
= Connect_Timeout();
613 if (err
!= GSOCK_NOERROR
)
616 /* m_error is set in _GSocket_Connect_Timeout */
619 return (GSocketError
) err
;
622 /* If connect failed with EWOULDBLOCK and the GSocket object
623 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
624 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
625 * this way if the connection completes, a GSOCK_CONNECTION
626 * event will be generated, if enabled.
628 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
630 m_establishing
= TRUE
;
631 m_error
= GSOCK_WOULDBLOCK
;
632 return GSOCK_WOULDBLOCK
;
635 /* If connect failed with an error other than EWOULDBLOCK,
636 * then the call to GSocket_Connect() has failed.
639 m_error
= GSOCK_IOERR
;
643 return GSOCK_NOERROR
;
646 /* Datagram sockets */
648 /* GSocket_SetNonOriented:
649 * Sets up this socket as a non-connection oriented (datagram) socket.
650 * Before using this function, the local address must have been set
651 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
652 * on success, or one of the following otherwise.
655 * GSOCK_INVSOCK - the socket is in use.
656 * GSOCK_INVADDR - the local address has not been set.
657 * GSOCK_IOERR - low-level error.
659 GSocketError
GSocket::SetNonOriented()
665 if (m_fd
!= INVALID_SOCKET
)
667 m_error
= GSOCK_INVSOCK
;
668 return GSOCK_INVSOCK
;
673 m_error
= GSOCK_INVADDR
;
674 return GSOCK_INVADDR
;
677 /* Initialize all fields */
681 /* Create the socket */
682 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
684 if (m_fd
== INVALID_SOCKET
)
686 m_error
= GSOCK_IOERR
;
690 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
691 gs_gui_functions
->Enable_Events(this);
693 /* Bind to the local address,
694 * and retrieve the actual address bound.
696 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
699 (SOCKLEN_T
*)&m_local
->m_len
) != 0))
702 m_error
= GSOCK_IOERR
;
706 return GSOCK_NOERROR
;
711 /* Like recv(), send(), ... */
712 int GSocket::Read(char *buffer
, int size
)
718 /* Reenable INPUT events */
719 m_detected
&= ~GSOCK_INPUT_FLAG
;
721 if (m_fd
== INVALID_SOCKET
|| m_server
)
723 m_error
= GSOCK_INVSOCK
;
727 /* If the socket is blocking, wait for data (with a timeout) */
728 if (Input_Timeout() == GSOCK_TIMEDOUT
)
733 ret
= Recv_Stream(buffer
, size
);
735 ret
= Recv_Dgram(buffer
, size
);
737 if (ret
== SOCKET_ERROR
)
739 if (WSAGetLastError() != WSAEWOULDBLOCK
)
740 m_error
= GSOCK_IOERR
;
742 m_error
= GSOCK_WOULDBLOCK
;
749 int GSocket::Write(const char *buffer
, int size
)
755 if (m_fd
== INVALID_SOCKET
|| m_server
)
757 m_error
= GSOCK_INVSOCK
;
761 /* If the socket is blocking, wait for writability (with a timeout) */
762 if (Output_Timeout() == GSOCK_TIMEDOUT
)
767 ret
= Send_Stream(buffer
, size
);
769 ret
= Send_Dgram(buffer
, size
);
771 if (ret
== SOCKET_ERROR
)
773 if (WSAGetLastError() != WSAEWOULDBLOCK
)
774 m_error
= GSOCK_IOERR
;
776 m_error
= GSOCK_WOULDBLOCK
;
778 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
779 * does). Once the first OUTPUT event is received, users can assume
780 * that the socket is writable until a read operation fails. Only then
781 * will further OUTPUT events be posted.
783 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
791 * Polls the socket to determine its status. This function will
792 * check for the events specified in the 'flags' parameter, and
793 * it will return a mask indicating which operations can be
794 * performed. This function won't block, regardless of the
795 * mode (blocking | nonblocking) of the socket.
797 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
799 if (!gs_gui_functions
->CanUseEventLoop())
801 GSocketEventFlags result
= 0;
811 FD_SET(m_fd
, &readfds
);
812 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
813 FD_SET(m_fd
, &writefds
);
814 FD_SET(m_fd
, &exceptfds
);
816 /* Check 'sticky' CONNECTION flag first */
817 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
819 /* If we have already detected a LOST event, then don't try
820 * to do any further processing.
822 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
824 m_establishing
= FALSE
;
826 return (GSOCK_LOST_FLAG
& flags
);
830 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
833 /* What to do here? */
834 return (result
& flags
);
837 /* Check for readability */
838 if (FD_ISSET(m_fd
, &readfds
))
842 if (!m_stream
|| recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
844 result
|= GSOCK_INPUT_FLAG
;
848 if (m_server
&& m_stream
)
850 result
|= GSOCK_CONNECTION_FLAG
;
851 m_detected
|= GSOCK_CONNECTION_FLAG
;
855 m_detected
= GSOCK_LOST_FLAG
;
856 m_establishing
= FALSE
;
858 /* LOST event: Abort any further processing */
859 return (GSOCK_LOST_FLAG
& flags
);
864 /* Check for writability */
865 if (FD_ISSET(m_fd
, &writefds
))
867 if (m_establishing
&& !m_server
)
870 SOCKLEN_T len
= sizeof(error
);
872 m_establishing
= FALSE
;
874 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
878 m_detected
= GSOCK_LOST_FLAG
;
880 /* LOST event: Abort any further processing */
881 return (GSOCK_LOST_FLAG
& flags
);
885 result
|= GSOCK_CONNECTION_FLAG
;
886 m_detected
|= GSOCK_CONNECTION_FLAG
;
891 result
|= GSOCK_OUTPUT_FLAG
;
895 /* Check for exceptions and errors (is this useful in Unices?) */
896 if (FD_ISSET(m_fd
, &exceptfds
))
898 m_establishing
= FALSE
;
899 m_detected
= GSOCK_LOST_FLAG
;
901 /* LOST event: Abort any further processing */
902 return (GSOCK_LOST_FLAG
& flags
);
905 return (result
& flags
);
910 return flags
& m_detected
;
916 /* GSocket_SetNonBlocking:
917 * Sets the socket to non-blocking mode. All IO calls will return
920 void GSocket::SetNonBlocking(bool non_block
)
924 m_non_blocking
= non_block
;
927 /* GSocket_SetTimeout:
928 * Sets the timeout for blocking calls. Time is expressed in
931 void GSocket::SetTimeout(unsigned long millis
)
935 m_timeout
.tv_sec
= (millis
/ 1000);
936 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
940 * Returns the last error occured for this socket. Note that successful
941 * operations do not clear this back to GSOCK_NOERROR, so use it only
944 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
954 * There is data to be read in the input buffer. If, after a read
955 * operation, there is still data available, the callback function will
958 * The socket is available for writing. That is, the next write call
959 * won't block. This event is generated only once, when the connection is
960 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
961 * when the output buffer empties again. This means that the app should
962 * assume that it can write since the first OUTPUT event, and no more
963 * OUTPUT events will be generated unless an error occurs.
965 * Connection succesfully established, for client sockets, or incoming
966 * client connection, for server sockets. Wait for this event (also watch
967 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
969 * The connection is lost (or a connection request failed); this could
970 * be due to a failure, or due to the peer closing it gracefully.
973 /* GSocket_SetCallback:
974 * Enables the callbacks specified by 'flags'. Note that 'flags'
975 * may be a combination of flags OR'ed toghether, so the same
976 * callback function can be made to accept different events.
977 * The callback function must have the following prototype:
979 * void function(GSocket *socket, GSocketEvent event, char *cdata)
981 void GSocket::SetCallback(GSocketEventFlags flags
,
982 GSocketCallback callback
, char *cdata
)
988 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
990 if ((flags
& (1 << count
)) != 0)
992 m_cbacks
[count
] = callback
;
993 m_data
[count
] = cdata
;
998 /* GSocket_UnsetCallback:
999 * Disables all callbacks specified by 'flags', which may be a
1000 * combination of flags OR'ed toghether.
1002 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1008 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1010 if ((flags
& (1 << count
)) != 0)
1012 m_cbacks
[count
] = NULL
;
1013 m_data
[count
] = NULL
;
1018 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1019 void *optval
, int *optlen
)
1021 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1023 return GSOCK_NOERROR
;
1025 return GSOCK_OPTERR
;
1028 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1029 const void *optval
, int optlen
)
1031 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1033 return GSOCK_NOERROR
;
1035 return GSOCK_OPTERR
;
1038 /* Internals (IO) */
1040 /* _GSocket_Input_Timeout:
1041 * For blocking sockets, wait until data is available or
1042 * until timeout ellapses.
1044 GSocketError
GSocket::Input_Timeout()
1048 if (!m_non_blocking
)
1051 FD_SET(m_fd
, &readfds
);
1052 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1054 m_error
= GSOCK_TIMEDOUT
;
1055 return GSOCK_TIMEDOUT
;
1058 return GSOCK_NOERROR
;
1061 /* _GSocket_Output_Timeout:
1062 * For blocking sockets, wait until data can be sent without
1063 * blocking or until timeout ellapses.
1065 GSocketError
GSocket::Output_Timeout()
1069 if (!m_non_blocking
)
1072 FD_SET(m_fd
, &writefds
);
1073 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1075 m_error
= GSOCK_TIMEDOUT
;
1076 return GSOCK_TIMEDOUT
;
1079 return GSOCK_NOERROR
;
1082 /* _GSocket_Connect_Timeout:
1083 * For blocking sockets, wait until the connection is
1084 * established or fails, or until timeout ellapses.
1086 GSocketError
GSocket::Connect_Timeout()
1092 FD_ZERO(&exceptfds
);
1093 FD_SET(m_fd
, &writefds
);
1094 FD_SET(m_fd
, &exceptfds
);
1095 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1097 m_error
= GSOCK_TIMEDOUT
;
1098 return GSOCK_TIMEDOUT
;
1100 if (!FD_ISSET(m_fd
, &writefds
))
1102 m_error
= GSOCK_IOERR
;
1106 return GSOCK_NOERROR
;
1109 int GSocket::Recv_Stream(char *buffer
, int size
)
1111 return recv(m_fd
, buffer
, size
, 0);
1114 int GSocket::Recv_Dgram(char *buffer
, int size
)
1116 struct sockaddr from
;
1117 SOCKLEN_T fromlen
= sizeof(from
);
1121 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1123 if (ret
== SOCKET_ERROR
)
1124 return SOCKET_ERROR
;
1126 /* Translate a system address into a GSocket address */
1129 m_peer
= GAddress_new();
1132 m_error
= GSOCK_MEMERR
;
1136 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1137 if (err
!= GSOCK_NOERROR
)
1139 GAddress_destroy(m_peer
);
1148 int GSocket::Send_Stream(const char *buffer
, int size
)
1150 return send(m_fd
, buffer
, size
, 0);
1153 int GSocket::Send_Dgram(const char *buffer
, int size
)
1155 struct sockaddr
*addr
;
1161 m_error
= GSOCK_INVADDR
;
1165 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1166 if (err
!= GSOCK_NOERROR
)
1172 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1174 /* Frees memory allocated by _GAddress_translate_to */
1180 /* Compatibility functions for GSocket */
1181 GSocket
*GSocket_new(void)
1183 GSocket
*newsocket
= new GSocket();
1184 if(newsocket
->IsOk())
1192 * -------------------------------------------------------------------------
1194 * -------------------------------------------------------------------------
1197 /* CHECK_ADDRESS verifies that the current address family is either
1198 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1199 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1200 * an appropiate error code.
1202 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1204 #define CHECK_ADDRESS(address, family) \
1206 if (address->m_family == GSOCK_NOFAMILY) \
1207 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1208 return address->m_error; \
1209 if (address->m_family != GSOCK_##family) \
1211 address->m_error = GSOCK_INVADDR; \
1212 return GSOCK_INVADDR; \
1216 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1218 if (address->m_family == GSOCK_NOFAMILY) \
1219 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1221 if (address->m_family != GSOCK_##family) \
1223 address->m_error = GSOCK_INVADDR; \
1229 GAddress
*GAddress_new(void)
1233 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1236 address
->m_family
= GSOCK_NOFAMILY
;
1237 address
->m_addr
= NULL
;
1243 GAddress
*GAddress_copy(GAddress
*address
)
1247 assert(address
!= NULL
);
1249 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1252 memcpy(addr2
, address
, sizeof(GAddress
));
1254 if (address
->m_addr
)
1256 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1257 if (addr2
->m_addr
== NULL
)
1262 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1268 void GAddress_destroy(GAddress
*address
)
1270 assert(address
!= NULL
);
1272 if (address
->m_addr
)
1273 free(address
->m_addr
);
1278 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1280 assert(address
!= NULL
);
1282 address
->m_family
= type
;
1285 GAddressType
GAddress_GetFamily(GAddress
*address
)
1287 assert(address
!= NULL
);
1289 return address
->m_family
;
1292 GSocketError
_GAddress_translate_from(GAddress
*address
,
1293 struct sockaddr
*addr
, int len
)
1295 address
->m_realfamily
= addr
->sa_family
;
1296 switch (addr
->sa_family
)
1299 address
->m_family
= GSOCK_INET
;
1302 address
->m_family
= GSOCK_UNIX
;
1306 address
->m_family
= GSOCK_INET6
;
1311 address
->m_error
= GSOCK_INVOP
;
1316 if (address
->m_addr
)
1317 free(address
->m_addr
);
1319 address
->m_len
= len
;
1320 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1322 if (address
->m_addr
== NULL
)
1324 address
->m_error
= GSOCK_MEMERR
;
1325 return GSOCK_MEMERR
;
1327 memcpy(address
->m_addr
, addr
, len
);
1329 return GSOCK_NOERROR
;
1332 GSocketError
_GAddress_translate_to(GAddress
*address
,
1333 struct sockaddr
**addr
, int *len
)
1335 if (!address
->m_addr
)
1337 address
->m_error
= GSOCK_INVADDR
;
1338 return GSOCK_INVADDR
;
1341 *len
= address
->m_len
;
1342 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1345 address
->m_error
= GSOCK_MEMERR
;
1346 return GSOCK_MEMERR
;
1349 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1350 return GSOCK_NOERROR
;
1354 * -------------------------------------------------------------------------
1355 * Internet address family
1356 * -------------------------------------------------------------------------
1359 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1361 address
->m_len
= sizeof(struct sockaddr_in
);
1362 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1363 if (address
->m_addr
== NULL
)
1365 address
->m_error
= GSOCK_MEMERR
;
1366 return GSOCK_MEMERR
;
1369 address
->m_family
= GSOCK_INET
;
1370 address
->m_realfamily
= AF_INET
;
1371 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1372 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1374 return GSOCK_NOERROR
;
1377 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1380 struct in_addr
*addr
;
1382 assert(address
!= NULL
);
1384 CHECK_ADDRESS(address
, INET
);
1386 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1388 addr
->s_addr
= inet_addr(hostname
);
1390 /* If it is a numeric host name, convert it now */
1391 if (addr
->s_addr
== INADDR_NONE
)
1393 struct in_addr
*array_addr
;
1395 /* It is a real name, we solve it */
1396 if ((he
= gethostbyname(hostname
)) == NULL
)
1398 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1399 address
->m_error
= GSOCK_NOHOST
;
1400 return GSOCK_NOHOST
;
1402 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1403 addr
->s_addr
= array_addr
[0].s_addr
;
1405 return GSOCK_NOERROR
;
1408 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1410 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1413 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1414 unsigned long hostaddr
)
1416 struct in_addr
*addr
;
1418 assert(address
!= NULL
);
1420 CHECK_ADDRESS(address
, INET
);
1422 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1423 addr
->s_addr
= htonl(hostaddr
);;
1425 return GSOCK_NOERROR
;
1428 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1429 const char *protocol
)
1432 struct sockaddr_in
*addr
;
1434 assert(address
!= NULL
);
1435 CHECK_ADDRESS(address
, INET
);
1439 address
->m_error
= GSOCK_INVPORT
;
1440 return GSOCK_INVPORT
;
1443 se
= getservbyname(port
, protocol
);
1446 if (isdigit(port
[0]))
1450 port_int
= atoi(port
);
1451 addr
= (struct sockaddr_in
*)address
->m_addr
;
1452 addr
->sin_port
= htons((u_short
) port_int
);
1453 return GSOCK_NOERROR
;
1456 address
->m_error
= GSOCK_INVPORT
;
1457 return GSOCK_INVPORT
;
1460 addr
= (struct sockaddr_in
*)address
->m_addr
;
1461 addr
->sin_port
= se
->s_port
;
1463 return GSOCK_NOERROR
;
1466 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1468 struct sockaddr_in
*addr
;
1470 assert(address
!= NULL
);
1471 CHECK_ADDRESS(address
, INET
);
1473 addr
= (struct sockaddr_in
*)address
->m_addr
;
1474 addr
->sin_port
= htons(port
);
1476 return GSOCK_NOERROR
;
1479 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1483 struct sockaddr_in
*addr
;
1485 assert(address
!= NULL
);
1486 CHECK_ADDRESS(address
, INET
);
1488 addr
= (struct sockaddr_in
*)address
->m_addr
;
1489 addr_buf
= (char *)&(addr
->sin_addr
);
1491 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1494 address
->m_error
= GSOCK_NOHOST
;
1495 return GSOCK_NOHOST
;
1498 strncpy(hostname
, he
->h_name
, sbuf
);
1500 return GSOCK_NOERROR
;
1503 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1505 struct sockaddr_in
*addr
;
1507 assert(address
!= NULL
);
1508 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1510 addr
= (struct sockaddr_in
*)address
->m_addr
;
1512 return ntohl(addr
->sin_addr
.s_addr
);
1515 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1517 struct sockaddr_in
*addr
;
1519 assert(address
!= NULL
);
1520 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1522 addr
= (struct sockaddr_in
*)address
->m_addr
;
1523 return ntohs(addr
->sin_port
);
1527 * -------------------------------------------------------------------------
1528 * Unix address family
1529 * -------------------------------------------------------------------------
1532 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1534 assert (address
!= NULL
);
1535 address
->m_error
= GSOCK_INVADDR
;
1536 return GSOCK_INVADDR
;
1539 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1541 #if defined(__BORLANDC__)
1542 /* prevents unused variable message in Borland */
1545 assert (address
!= NULL
);
1546 address
->m_error
= GSOCK_INVADDR
;
1547 return GSOCK_INVADDR
;
1550 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1552 #if defined(__BORLANDC__)
1553 /* prevents unused variable message in Borland */
1557 assert (address
!= NULL
);
1558 address
->m_error
= GSOCK_INVADDR
;
1559 return GSOCK_INVADDR
;
1562 #else /* !wxUSE_SOCKETS */
1565 * Translation unit shouldn't be empty, so include this typedef to make the
1566 * compiler (VC++ 6.0, for example) happy
1568 typedef void (*wxDummy
)();
1570 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */