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 * -------------------------------------------------------------------------
12 * PLEASE don't put C++ comments here - this is a C source file.
16 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
17 * warning: conditional expression is constant.
19 # pragma warning(disable:4115)
21 * warning: named type definition in parentheses.
23 # pragma warning(disable:4127)
24 /* GAddress_UNIX_GetPath,
25 * warning: unreferenced formal parameter.
27 # pragma warning(disable:4100)
30 /* windows.h results in tons of warnings at max warning level */
32 # pragma warning(push, 1)
37 # pragma warning(disable:4514)
45 #ifndef __GSOCKET_STANDALONE__
46 # include "wx/platform.h"
47 # include "wx/setup.h"
50 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
52 #ifndef __GSOCKET_STANDALONE__
53 # include "wx/msw/gsockmsw.h"
54 # include "wx/gsocket.h"
56 # include "gsockmsw.h"
58 #endif /* __GSOCKET_STANDALONE__ */
65 #define isdigit(x) (x > 47 && x < 58)
67 #include "wx/msw/wince/net.h"
76 /* if we use configure for MSW SOCKLEN_T will be already defined */
78 # define SOCKLEN_T int
81 /* Table of GUI-related functions. We must call them indirectly because
82 * of wxBase and GUI separation: */
84 static class GSocketGUIFunctionsTable
*gs_gui_functions
;
86 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
89 virtual bool OnInit();
90 virtual void OnExit();
91 virtual bool CanUseEventLoop();
92 virtual bool Init_Socket(GSocket
*socket
);
93 virtual void Destroy_Socket(GSocket
*socket
);
94 virtual void Enable_Events(GSocket
*socket
);
95 virtual void Disable_Events(GSocket
*socket
);
98 bool GSocketGUIFunctionsTableNull::OnInit()
100 void GSocketGUIFunctionsTableNull::OnExit()
102 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
104 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*socket
)
106 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*socket
)
108 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*socket
)
110 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*socket
)
112 /* Global initialisers */
114 void GSocket_SetGUIFunctions(struct GSocketGUIFunctionsTable
*guifunc
)
116 gs_gui_functions
= guifunc
;
119 int GSocket_Init(void)
123 if (!gs_gui_functions
)
125 static class GSocketGUIFunctionsTableNull table
;
126 gs_gui_functions
= &table
;
128 if ( !gs_gui_functions
->OnInit() )
133 /* Initialize WinSocket */
134 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
137 void GSocket_Cleanup(void)
139 if (gs_gui_functions
)
141 gs_gui_functions
->OnExit();
144 /* Cleanup WinSocket */
148 /* Constructors / Destructors for GSocket */
154 m_fd
= INVALID_SOCKET
;
155 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
162 m_error
= GSOCK_NOERROR
;
165 m_non_blocking
= false;
166 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
167 m_timeout
.tv_usec
= 0;
168 m_establishing
= FALSE
;
171 assert(gs_gui_functions
);
172 /* Per-socket GUI-specific initialization */
173 m_ok
= gs_gui_functions
->Init_Socket(this);
176 void GSocket::Close()
178 gs_gui_functions
->Disable_Events(this);
180 m_fd
= INVALID_SOCKET
;
187 /* Per-socket GUI-specific cleanup */
188 gs_gui_functions
->Destroy_Socket(this);
190 /* Check that the socket is really shutdowned */
191 if (m_fd
!= INVALID_SOCKET
)
194 /* Destroy private addresses */
196 GAddress_destroy(m_local
);
199 GAddress_destroy(m_peer
);
203 * Disallow further read/write operations on this socket, close
204 * the fd and disable all callbacks.
206 void GSocket::Shutdown()
212 /* If socket has been created, shutdown it */
213 if (m_fd
!= INVALID_SOCKET
)
219 /* Disable GUI callbacks */
220 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
221 m_cbacks
[evt
] = NULL
;
223 m_detected
= GSOCK_LOST_FLAG
;
226 /* Address handling */
232 * Set or get the local or peer address for this socket. The 'set'
233 * functions return GSOCK_NOERROR on success, an error code otherwise.
234 * The 'get' functions return a pointer to a GAddress object on success,
235 * or NULL otherwise, in which case they set the error code of the
236 * corresponding GSocket.
239 * GSOCK_INVSOCK - the socket is not valid.
240 * GSOCK_INVADDR - the address is not valid.
242 GSocketError
GSocket::SetLocal(GAddress
*address
)
246 /* the socket must be initialized, or it must be a server */
247 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
249 m_error
= GSOCK_INVSOCK
;
250 return GSOCK_INVSOCK
;
254 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
256 m_error
= GSOCK_INVADDR
;
257 return GSOCK_INVADDR
;
261 GAddress_destroy(m_local
);
263 m_local
= GAddress_copy(address
);
265 return GSOCK_NOERROR
;
268 GSocketError
GSocket::SetPeer(GAddress
*address
)
273 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
275 m_error
= GSOCK_INVADDR
;
276 return GSOCK_INVADDR
;
280 GAddress_destroy(m_peer
);
282 m_peer
= GAddress_copy(address
);
284 return GSOCK_NOERROR
;
287 GAddress
*GSocket::GetLocal()
290 struct sockaddr addr
;
291 SOCKLEN_T size
= sizeof(addr
);
296 /* try to get it from the m_local var first */
298 return GAddress_copy(m_local
);
300 /* else, if the socket is initialized, try getsockname */
301 if (m_fd
== INVALID_SOCKET
)
303 m_error
= GSOCK_INVSOCK
;
307 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
309 m_error
= GSOCK_IOERR
;
313 /* got a valid address from getsockname, create a GAddress object */
314 if ((address
= GAddress_new()) == NULL
)
316 m_error
= GSOCK_MEMERR
;
320 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
322 GAddress_destroy(address
);
330 GAddress
*GSocket::GetPeer()
334 /* try to get it from the m_peer var */
336 return GAddress_copy(m_peer
);
341 /* Server specific parts */
343 /* GSocket_SetServer:
344 * Sets up this socket as a server. The local address must have been
345 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
346 * Returns GSOCK_NOERROR on success, one of the following otherwise:
349 * GSOCK_INVSOCK - the socket is in use.
350 * GSOCK_INVADDR - the local address has not been set.
351 * GSOCK_IOERR - low-level error.
353 GSocketError
GSocket::SetServer()
359 /* must not be in use */
360 if (m_fd
!= INVALID_SOCKET
)
362 m_error
= GSOCK_INVSOCK
;
363 return GSOCK_INVSOCK
;
366 /* the local addr must have been set */
369 m_error
= GSOCK_INVADDR
;
370 return GSOCK_INVADDR
;
373 /* Initialize all fields */
377 /* Create the socket */
378 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
380 if (m_fd
== INVALID_SOCKET
)
382 m_error
= GSOCK_IOERR
;
386 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
387 gs_gui_functions
->Enable_Events(this);
389 /* allow a socket to re-bind if the socket is in the TIME_WAIT
390 state after being previously closed.
393 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
396 /* Bind to the local address,
397 * retrieve the actual address bound,
398 * and listen up to 5 connections.
400 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
403 (SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
404 (listen(m_fd
, 5) != 0))
407 m_error
= GSOCK_IOERR
;
411 return GSOCK_NOERROR
;
414 /* GSocket_WaitConnection:
415 * Waits for an incoming client connection. Returns a pointer to
416 * a GSocket object, or NULL if there was an error, in which case
417 * the last error field will be updated for the calling GSocket.
419 * Error codes (set in the calling GSocket)
420 * GSOCK_INVSOCK - the socket is not valid or not a server.
421 * GSOCK_TIMEDOUT - timeout, no incoming connections.
422 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
423 * GSOCK_MEMERR - couldn't allocate memory.
424 * GSOCK_IOERR - low-level error.
426 GSocket
*GSocket::WaitConnection()
429 struct sockaddr from
;
430 SOCKLEN_T fromlen
= sizeof(from
);
436 /* Reenable CONNECTION events */
437 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
439 /* If the socket has already been created, we exit immediately */
440 if (m_fd
== INVALID_SOCKET
|| !m_server
)
442 m_error
= GSOCK_INVSOCK
;
446 /* Create a GSocket object for the new connection */
447 connection
= GSocket_new();
451 m_error
= GSOCK_MEMERR
;
455 /* Wait for a connection (with timeout) */
456 if (Input_Timeout() == GSOCK_TIMEDOUT
)
458 GSocket_destroy(connection
);
459 /* m_error set by _GSocket_Input_Timeout */
463 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
465 if (connection
->m_fd
== INVALID_SOCKET
)
467 if (WSAGetLastError() == WSAEWOULDBLOCK
)
468 m_error
= GSOCK_WOULDBLOCK
;
470 m_error
= GSOCK_IOERR
;
472 GSocket_destroy(connection
);
476 /* Initialize all fields */
477 connection
->m_server
= FALSE
;
478 connection
->m_stream
= TRUE
;
480 /* Setup the peer address field */
481 connection
->m_peer
= GAddress_new();
482 if (!connection
->m_peer
)
484 GSocket_destroy(connection
);
485 m_error
= GSOCK_MEMERR
;
488 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
489 if (err
!= GSOCK_NOERROR
)
491 GAddress_destroy(connection
->m_peer
);
492 GSocket_destroy(connection
);
497 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
498 gs_gui_functions
->Enable_Events(connection
);
503 /* GSocket_SetReusable:
504 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
505 * make the appropriate setsockopt() call.
506 * Implemented as a GSocket function because clients (ie, wxSocketServer)
507 * don't have access to the GSocket struct information.
508 * Returns TRUE if the flag was set correctly, FALSE if an error occured
509 * (ie, if the parameter was NULL)
511 int GSocket::SetReusable()
513 /* socket must not be null, and must not be in use/already bound */
514 if (this && m_fd
== INVALID_SOCKET
) {
521 /* Client specific parts */
524 * For stream (connection oriented) sockets, GSocket_Connect() tries
525 * to establish a client connection to a server using the peer address
526 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
527 * connection has been succesfully established, or one of the error
528 * codes listed below. Note that for nonblocking sockets, a return
529 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
530 * request can be completed later; you should use GSocket_Select()
531 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
532 * corresponding asynchronous events.
534 * For datagram (non connection oriented) sockets, GSocket_Connect()
535 * just sets the peer address established with GSocket_SetPeer() as
536 * default destination.
539 * GSOCK_INVSOCK - the socket is in use or not valid.
540 * GSOCK_INVADDR - the peer address has not been established.
541 * GSOCK_TIMEDOUT - timeout, the connection failed.
542 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
543 * GSOCK_MEMERR - couldn't allocate memory.
544 * GSOCK_IOERR - low-level error.
546 GSocketError
GSocket::Connect(GSocketStream stream
)
553 /* Enable CONNECTION events (needed for nonblocking connections) */
554 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
556 if (m_fd
!= INVALID_SOCKET
)
558 m_error
= GSOCK_INVSOCK
;
559 return GSOCK_INVSOCK
;
564 m_error
= GSOCK_INVADDR
;
565 return GSOCK_INVADDR
;
568 /* Streamed or dgram socket? */
569 m_stream
= (stream
== GSOCK_STREAMED
);
571 m_establishing
= FALSE
;
573 /* Create the socket */
574 m_fd
= socket(m_peer
->m_realfamily
,
575 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
577 if (m_fd
== INVALID_SOCKET
)
579 m_error
= GSOCK_IOERR
;
583 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
584 gs_gui_functions
->Enable_Events(this);
586 /* Connect it to the peer address, with a timeout (see below) */
587 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
589 if (ret
== SOCKET_ERROR
)
591 err
= WSAGetLastError();
593 /* If connect failed with EWOULDBLOCK and the GSocket object
594 * is in blocking mode, we select() for the specified timeout
595 * checking for writability to see if the connection request
598 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
600 err
= Connect_Timeout();
602 if (err
!= GSOCK_NOERROR
)
605 /* m_error is set in _GSocket_Connect_Timeout */
608 return (GSocketError
) err
;
611 /* If connect failed with EWOULDBLOCK and the GSocket object
612 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
613 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
614 * this way if the connection completes, a GSOCK_CONNECTION
615 * event will be generated, if enabled.
617 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
619 m_establishing
= TRUE
;
620 m_error
= GSOCK_WOULDBLOCK
;
621 return GSOCK_WOULDBLOCK
;
624 /* If connect failed with an error other than EWOULDBLOCK,
625 * then the call to GSocket_Connect() has failed.
628 m_error
= GSOCK_IOERR
;
632 return GSOCK_NOERROR
;
635 /* Datagram sockets */
637 /* GSocket_SetNonOriented:
638 * Sets up this socket as a non-connection oriented (datagram) socket.
639 * Before using this function, the local address must have been set
640 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
641 * on success, or one of the following otherwise.
644 * GSOCK_INVSOCK - the socket is in use.
645 * GSOCK_INVADDR - the local address has not been set.
646 * GSOCK_IOERR - low-level error.
648 GSocketError
GSocket::SetNonOriented()
654 if (m_fd
!= INVALID_SOCKET
)
656 m_error
= GSOCK_INVSOCK
;
657 return GSOCK_INVSOCK
;
662 m_error
= GSOCK_INVADDR
;
663 return GSOCK_INVADDR
;
666 /* Initialize all fields */
670 /* Create the socket */
671 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
673 if (m_fd
== INVALID_SOCKET
)
675 m_error
= GSOCK_IOERR
;
679 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
680 gs_gui_functions
->Enable_Events(this);
682 /* Bind to the local address,
683 * and retrieve the actual address bound.
685 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
688 (SOCKLEN_T
*)&m_local
->m_len
) != 0))
691 m_error
= GSOCK_IOERR
;
695 return GSOCK_NOERROR
;
700 /* Like recv(), send(), ... */
701 int GSocket::Read(char *buffer
, int size
)
707 /* Reenable INPUT events */
708 m_detected
&= ~GSOCK_INPUT_FLAG
;
710 if (m_fd
== INVALID_SOCKET
|| m_server
)
712 m_error
= GSOCK_INVSOCK
;
716 /* If the socket is blocking, wait for data (with a timeout) */
717 if (Input_Timeout() == GSOCK_TIMEDOUT
)
722 ret
= Recv_Stream(buffer
, size
);
724 ret
= Recv_Dgram(buffer
, size
);
726 if (ret
== SOCKET_ERROR
)
728 if (WSAGetLastError() != WSAEWOULDBLOCK
)
729 m_error
= GSOCK_IOERR
;
731 m_error
= GSOCK_WOULDBLOCK
;
738 int GSocket::Write(const char *buffer
, int size
)
744 if (m_fd
== INVALID_SOCKET
|| m_server
)
746 m_error
= GSOCK_INVSOCK
;
750 /* If the socket is blocking, wait for writability (with a timeout) */
751 if (Output_Timeout() == GSOCK_TIMEDOUT
)
756 ret
= Send_Stream(buffer
, size
);
758 ret
= Send_Dgram(buffer
, size
);
760 if (ret
== SOCKET_ERROR
)
762 if (WSAGetLastError() != WSAEWOULDBLOCK
)
763 m_error
= GSOCK_IOERR
;
765 m_error
= GSOCK_WOULDBLOCK
;
767 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
768 * does). Once the first OUTPUT event is received, users can assume
769 * that the socket is writable until a read operation fails. Only then
770 * will further OUTPUT events be posted.
772 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
780 * Polls the socket to determine its status. This function will
781 * check for the events specified in the 'flags' parameter, and
782 * it will return a mask indicating which operations can be
783 * performed. This function won't block, regardless of the
784 * mode (blocking | nonblocking) of the socket.
786 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
788 if (!gs_gui_functions
->CanUseEventLoop())
790 GSocketEventFlags result
= 0;
800 FD_SET(m_fd
, &readfds
);
801 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
802 FD_SET(m_fd
, &writefds
);
803 FD_SET(m_fd
, &exceptfds
);
805 /* Check 'sticky' CONNECTION flag first */
806 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
808 /* If we have already detected a LOST event, then don't try
809 * to do any further processing.
811 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
813 m_establishing
= FALSE
;
815 return (GSOCK_LOST_FLAG
& flags
);
819 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
822 /* What to do here? */
823 return (result
& flags
);
826 /* Check for readability */
827 if (FD_ISSET(m_fd
, &readfds
))
831 if (!m_stream
|| recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
833 result
|= GSOCK_INPUT_FLAG
;
837 if (m_server
&& m_stream
)
839 result
|= GSOCK_CONNECTION_FLAG
;
840 m_detected
|= GSOCK_CONNECTION_FLAG
;
844 m_detected
= GSOCK_LOST_FLAG
;
845 m_establishing
= FALSE
;
847 /* LOST event: Abort any further processing */
848 return (GSOCK_LOST_FLAG
& flags
);
853 /* Check for writability */
854 if (FD_ISSET(m_fd
, &writefds
))
856 if (m_establishing
&& !m_server
)
859 SOCKLEN_T len
= sizeof(error
);
861 m_establishing
= FALSE
;
863 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
867 m_detected
= GSOCK_LOST_FLAG
;
869 /* LOST event: Abort any further processing */
870 return (GSOCK_LOST_FLAG
& flags
);
874 result
|= GSOCK_CONNECTION_FLAG
;
875 m_detected
|= GSOCK_CONNECTION_FLAG
;
880 result
|= GSOCK_OUTPUT_FLAG
;
884 /* Check for exceptions and errors (is this useful in Unices?) */
885 if (FD_ISSET(m_fd
, &exceptfds
))
887 m_establishing
= FALSE
;
888 m_detected
= GSOCK_LOST_FLAG
;
890 /* LOST event: Abort any further processing */
891 return (GSOCK_LOST_FLAG
& flags
);
894 return (result
& flags
);
899 return flags
& m_detected
;
905 /* GSocket_SetNonBlocking:
906 * Sets the socket to non-blocking mode. All IO calls will return
909 void GSocket::SetNonBlocking(bool non_block
)
913 m_non_blocking
= non_block
;
916 /* GSocket_SetTimeout:
917 * Sets the timeout for blocking calls. Time is expressed in
920 void GSocket::SetTimeout(unsigned long millis
)
924 m_timeout
.tv_sec
= (millis
/ 1000);
925 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
929 * Returns the last error occured for this socket. Note that successful
930 * operations do not clear this back to GSOCK_NOERROR, so use it only
933 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
943 * There is data to be read in the input buffer. If, after a read
944 * operation, there is still data available, the callback function will
947 * The socket is available for writing. That is, the next write call
948 * won't block. This event is generated only once, when the connection is
949 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
950 * when the output buffer empties again. This means that the app should
951 * assume that it can write since the first OUTPUT event, and no more
952 * OUTPUT events will be generated unless an error occurs.
954 * Connection succesfully established, for client sockets, or incoming
955 * client connection, for server sockets. Wait for this event (also watch
956 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
958 * The connection is lost (or a connection request failed); this could
959 * be due to a failure, or due to the peer closing it gracefully.
962 /* GSocket_SetCallback:
963 * Enables the callbacks specified by 'flags'. Note that 'flags'
964 * may be a combination of flags OR'ed toghether, so the same
965 * callback function can be made to accept different events.
966 * The callback function must have the following prototype:
968 * void function(GSocket *socket, GSocketEvent event, char *cdata)
970 void GSocket::SetCallback(GSocketEventFlags flags
,
971 GSocketCallback callback
, char *cdata
)
977 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
979 if ((flags
& (1 << count
)) != 0)
981 m_cbacks
[count
] = callback
;
982 m_data
[count
] = cdata
;
987 /* GSocket_UnsetCallback:
988 * Disables all callbacks specified by 'flags', which may be a
989 * combination of flags OR'ed toghether.
991 void GSocket::UnsetCallback(GSocketEventFlags flags
)
997 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
999 if ((flags
& (1 << count
)) != 0)
1001 m_cbacks
[count
] = NULL
;
1002 m_data
[count
] = NULL
;
1007 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1008 void *optval
, int *optlen
)
1010 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1012 return GSOCK_NOERROR
;
1014 return GSOCK_OPTERR
;
1017 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1018 const void *optval
, int optlen
)
1020 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1022 return GSOCK_NOERROR
;
1024 return GSOCK_OPTERR
;
1027 /* Internals (IO) */
1029 /* _GSocket_Input_Timeout:
1030 * For blocking sockets, wait until data is available or
1031 * until timeout ellapses.
1033 GSocketError
GSocket::Input_Timeout()
1037 if (!m_non_blocking
)
1040 FD_SET(m_fd
, &readfds
);
1041 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1043 m_error
= GSOCK_TIMEDOUT
;
1044 return GSOCK_TIMEDOUT
;
1047 return GSOCK_NOERROR
;
1050 /* _GSocket_Output_Timeout:
1051 * For blocking sockets, wait until data can be sent without
1052 * blocking or until timeout ellapses.
1054 GSocketError
GSocket::Output_Timeout()
1058 if (!m_non_blocking
)
1061 FD_SET(m_fd
, &writefds
);
1062 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1064 m_error
= GSOCK_TIMEDOUT
;
1065 return GSOCK_TIMEDOUT
;
1068 return GSOCK_NOERROR
;
1071 /* _GSocket_Connect_Timeout:
1072 * For blocking sockets, wait until the connection is
1073 * established or fails, or until timeout ellapses.
1075 GSocketError
GSocket::Connect_Timeout()
1081 FD_ZERO(&exceptfds
);
1082 FD_SET(m_fd
, &writefds
);
1083 FD_SET(m_fd
, &exceptfds
);
1084 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1086 m_error
= GSOCK_TIMEDOUT
;
1087 return GSOCK_TIMEDOUT
;
1089 if (!FD_ISSET(m_fd
, &writefds
))
1091 m_error
= GSOCK_IOERR
;
1095 return GSOCK_NOERROR
;
1098 int GSocket::Recv_Stream(char *buffer
, int size
)
1100 return recv(m_fd
, buffer
, size
, 0);
1103 int GSocket::Recv_Dgram(char *buffer
, int size
)
1105 struct sockaddr from
;
1106 SOCKLEN_T fromlen
= sizeof(from
);
1110 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1112 if (ret
== SOCKET_ERROR
)
1113 return SOCKET_ERROR
;
1115 /* Translate a system address into a GSocket address */
1118 m_peer
= GAddress_new();
1121 m_error
= GSOCK_MEMERR
;
1125 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1126 if (err
!= GSOCK_NOERROR
)
1128 GAddress_destroy(m_peer
);
1137 int GSocket::Send_Stream(const char *buffer
, int size
)
1139 return send(m_fd
, buffer
, size
, 0);
1142 int GSocket::Send_Dgram(const char *buffer
, int size
)
1144 struct sockaddr
*addr
;
1150 m_error
= GSOCK_INVADDR
;
1154 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1155 if (err
!= GSOCK_NOERROR
)
1161 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1163 /* Frees memory allocated by _GAddress_translate_to */
1169 /* Compatibility functions for GSocket */
1170 GSocket
*GSocket_new(void)
1172 GSocket
*newsocket
= new GSocket();
1173 if(newsocket
->IsOk())
1181 * -------------------------------------------------------------------------
1183 * -------------------------------------------------------------------------
1186 /* CHECK_ADDRESS verifies that the current address family is either
1187 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1188 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1189 * an appropiate error code.
1191 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1193 #define CHECK_ADDRESS(address, family) \
1195 if (address->m_family == GSOCK_NOFAMILY) \
1196 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1197 return address->m_error; \
1198 if (address->m_family != GSOCK_##family) \
1200 address->m_error = GSOCK_INVADDR; \
1201 return GSOCK_INVADDR; \
1205 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1207 if (address->m_family == GSOCK_NOFAMILY) \
1208 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1210 if (address->m_family != GSOCK_##family) \
1212 address->m_error = GSOCK_INVADDR; \
1218 GAddress
*GAddress_new(void)
1222 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1225 address
->m_family
= GSOCK_NOFAMILY
;
1226 address
->m_addr
= NULL
;
1232 GAddress
*GAddress_copy(GAddress
*address
)
1236 assert(address
!= NULL
);
1238 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1241 memcpy(addr2
, address
, sizeof(GAddress
));
1243 if (address
->m_addr
)
1245 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1246 if (addr2
->m_addr
== NULL
)
1251 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1257 void GAddress_destroy(GAddress
*address
)
1259 assert(address
!= NULL
);
1261 if (address
->m_addr
)
1262 free(address
->m_addr
);
1267 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1269 assert(address
!= NULL
);
1271 address
->m_family
= type
;
1274 GAddressType
GAddress_GetFamily(GAddress
*address
)
1276 assert(address
!= NULL
);
1278 return address
->m_family
;
1281 GSocketError
_GAddress_translate_from(GAddress
*address
,
1282 struct sockaddr
*addr
, int len
)
1284 address
->m_realfamily
= addr
->sa_family
;
1285 switch (addr
->sa_family
)
1288 address
->m_family
= GSOCK_INET
;
1291 address
->m_family
= GSOCK_UNIX
;
1295 address
->m_family
= GSOCK_INET6
;
1300 address
->m_error
= GSOCK_INVOP
;
1305 if (address
->m_addr
)
1306 free(address
->m_addr
);
1308 address
->m_len
= len
;
1309 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1311 if (address
->m_addr
== NULL
)
1313 address
->m_error
= GSOCK_MEMERR
;
1314 return GSOCK_MEMERR
;
1316 memcpy(address
->m_addr
, addr
, len
);
1318 return GSOCK_NOERROR
;
1321 GSocketError
_GAddress_translate_to(GAddress
*address
,
1322 struct sockaddr
**addr
, int *len
)
1324 if (!address
->m_addr
)
1326 address
->m_error
= GSOCK_INVADDR
;
1327 return GSOCK_INVADDR
;
1330 *len
= address
->m_len
;
1331 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1334 address
->m_error
= GSOCK_MEMERR
;
1335 return GSOCK_MEMERR
;
1338 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1339 return GSOCK_NOERROR
;
1343 * -------------------------------------------------------------------------
1344 * Internet address family
1345 * -------------------------------------------------------------------------
1348 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1350 address
->m_len
= sizeof(struct sockaddr_in
);
1351 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1352 if (address
->m_addr
== NULL
)
1354 address
->m_error
= GSOCK_MEMERR
;
1355 return GSOCK_MEMERR
;
1358 address
->m_family
= GSOCK_INET
;
1359 address
->m_realfamily
= AF_INET
;
1360 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1361 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1363 return GSOCK_NOERROR
;
1366 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1369 struct in_addr
*addr
;
1371 assert(address
!= NULL
);
1373 CHECK_ADDRESS(address
, INET
);
1375 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1377 addr
->s_addr
= inet_addr(hostname
);
1379 /* If it is a numeric host name, convert it now */
1380 if (addr
->s_addr
== INADDR_NONE
)
1382 struct in_addr
*array_addr
;
1384 /* It is a real name, we solve it */
1385 if ((he
= gethostbyname(hostname
)) == NULL
)
1387 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1388 address
->m_error
= GSOCK_NOHOST
;
1389 return GSOCK_NOHOST
;
1391 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1392 addr
->s_addr
= array_addr
[0].s_addr
;
1394 return GSOCK_NOERROR
;
1397 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1399 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1402 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1403 unsigned long hostaddr
)
1405 struct in_addr
*addr
;
1407 assert(address
!= NULL
);
1409 CHECK_ADDRESS(address
, INET
);
1411 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1412 addr
->s_addr
= htonl(hostaddr
);;
1414 return GSOCK_NOERROR
;
1417 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1418 const char *protocol
)
1421 struct sockaddr_in
*addr
;
1423 assert(address
!= NULL
);
1424 CHECK_ADDRESS(address
, INET
);
1428 address
->m_error
= GSOCK_INVPORT
;
1429 return GSOCK_INVPORT
;
1432 se
= getservbyname(port
, protocol
);
1435 if (isdigit(port
[0]))
1439 port_int
= atoi(port
);
1440 addr
= (struct sockaddr_in
*)address
->m_addr
;
1441 addr
->sin_port
= htons((u_short
) port_int
);
1442 return GSOCK_NOERROR
;
1445 address
->m_error
= GSOCK_INVPORT
;
1446 return GSOCK_INVPORT
;
1449 addr
= (struct sockaddr_in
*)address
->m_addr
;
1450 addr
->sin_port
= se
->s_port
;
1452 return GSOCK_NOERROR
;
1455 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1457 struct sockaddr_in
*addr
;
1459 assert(address
!= NULL
);
1460 CHECK_ADDRESS(address
, INET
);
1462 addr
= (struct sockaddr_in
*)address
->m_addr
;
1463 addr
->sin_port
= htons(port
);
1465 return GSOCK_NOERROR
;
1468 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1472 struct sockaddr_in
*addr
;
1474 assert(address
!= NULL
);
1475 CHECK_ADDRESS(address
, INET
);
1477 addr
= (struct sockaddr_in
*)address
->m_addr
;
1478 addr_buf
= (char *)&(addr
->sin_addr
);
1480 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1483 address
->m_error
= GSOCK_NOHOST
;
1484 return GSOCK_NOHOST
;
1487 strncpy(hostname
, he
->h_name
, sbuf
);
1489 return GSOCK_NOERROR
;
1492 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1494 struct sockaddr_in
*addr
;
1496 assert(address
!= NULL
);
1497 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1499 addr
= (struct sockaddr_in
*)address
->m_addr
;
1501 return ntohl(addr
->sin_addr
.s_addr
);
1504 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1506 struct sockaddr_in
*addr
;
1508 assert(address
!= NULL
);
1509 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1511 addr
= (struct sockaddr_in
*)address
->m_addr
;
1512 return ntohs(addr
->sin_port
);
1516 * -------------------------------------------------------------------------
1517 * Unix address family
1518 * -------------------------------------------------------------------------
1521 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1523 assert (address
!= NULL
);
1524 address
->m_error
= GSOCK_INVADDR
;
1525 return GSOCK_INVADDR
;
1528 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1530 #if defined(__BORLANDC__)
1531 /* prevents unused variable message in Borland */
1534 assert (address
!= NULL
);
1535 address
->m_error
= GSOCK_INVADDR
;
1536 return GSOCK_INVADDR
;
1539 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1541 #if defined(__BORLANDC__)
1542 /* prevents unused variable message in Borland */
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__) */