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 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
13 * warning: conditional expression is constant.
15 # pragma warning(disable:4115)
17 * warning: named type definition in parentheses.
19 # pragma warning(disable:4127)
20 /* GAddress_UNIX_GetPath,
21 * warning: unreferenced formal parameter.
23 # pragma warning(disable:4100)
26 /* windows.h results in tons of warnings at max warning level */
28 # pragma warning(push, 1)
33 # pragma warning(disable:4514)
41 #ifndef __GSOCKET_STANDALONE__
42 # include "wx/platform.h"
43 # include "wx/setup.h"
46 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
48 #ifndef __GSOCKET_STANDALONE__
49 # include "wx/msw/gsockmsw.h"
50 # include "wx/gsocket.h"
52 # include "gsockmsw.h"
54 #endif /* __GSOCKET_STANDALONE__ */
61 #define isdigit(x) (x > 47 && x < 58)
63 #include "wx/msw/wince/net.h"
72 /* if we use configure for MSW SOCKLEN_T will be already defined */
74 # define SOCKLEN_T int
77 /* Table of GUI-related functions. We must call them indirectly because
78 * of wxBase and GUI separation: */
80 static GSocketGUIFunctionsTable
*gs_gui_functions
;
82 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
85 virtual bool OnInit();
86 virtual void OnExit();
87 virtual bool CanUseEventLoop();
88 virtual bool Init_Socket(GSocket
*socket
);
89 virtual void Destroy_Socket(GSocket
*socket
);
90 virtual void Enable_Events(GSocket
*socket
);
91 virtual void Disable_Events(GSocket
*socket
);
94 bool GSocketGUIFunctionsTableNull::OnInit()
96 void GSocketGUIFunctionsTableNull::OnExit()
98 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
100 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
102 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
104 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
106 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
108 /* Global initialisers */
110 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
112 gs_gui_functions
= guifunc
;
115 int GSocket_Init(void)
119 if (!gs_gui_functions
)
121 static GSocketGUIFunctionsTableNull table
;
122 gs_gui_functions
= &table
;
124 if ( !gs_gui_functions
->OnInit() )
129 /* Initialize WinSocket */
130 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
133 void GSocket_Cleanup(void)
135 if (gs_gui_functions
)
137 gs_gui_functions
->OnExit();
140 /* Cleanup WinSocket */
144 /* Constructors / Destructors for GSocket */
150 m_fd
= INVALID_SOCKET
;
151 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
158 m_error
= GSOCK_NOERROR
;
161 m_non_blocking
= false;
162 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
163 m_timeout
.tv_usec
= 0;
164 m_establishing
= false;
167 assert(gs_gui_functions
);
168 /* Per-socket GUI-specific initialization */
169 m_ok
= gs_gui_functions
->Init_Socket(this);
172 void GSocket::Close()
174 gs_gui_functions
->Disable_Events(this);
176 m_fd
= INVALID_SOCKET
;
183 /* Per-socket GUI-specific cleanup */
184 gs_gui_functions
->Destroy_Socket(this);
186 /* Check that the socket is really shutdowned */
187 if (m_fd
!= INVALID_SOCKET
)
190 /* Destroy private addresses */
192 GAddress_destroy(m_local
);
195 GAddress_destroy(m_peer
);
199 * Disallow further read/write operations on this socket, close
200 * the fd and disable all callbacks.
202 void GSocket::Shutdown()
208 /* If socket has been created, shutdown it */
209 if (m_fd
!= INVALID_SOCKET
)
215 /* Disable GUI callbacks */
216 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
217 m_cbacks
[evt
] = NULL
;
219 m_detected
= GSOCK_LOST_FLAG
;
222 /* Address handling */
228 * Set or get the local or peer address for this socket. The 'set'
229 * functions return GSOCK_NOERROR on success, an error code otherwise.
230 * The 'get' functions return a pointer to a GAddress object on success,
231 * or NULL otherwise, in which case they set the error code of the
232 * corresponding GSocket.
235 * GSOCK_INVSOCK - the socket is not valid.
236 * GSOCK_INVADDR - the address is not valid.
238 GSocketError
GSocket::SetLocal(GAddress
*address
)
242 /* the socket must be initialized, or it must be a server */
243 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
245 m_error
= GSOCK_INVSOCK
;
246 return GSOCK_INVSOCK
;
250 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
252 m_error
= GSOCK_INVADDR
;
253 return GSOCK_INVADDR
;
257 GAddress_destroy(m_local
);
259 m_local
= GAddress_copy(address
);
261 return GSOCK_NOERROR
;
264 GSocketError
GSocket::SetPeer(GAddress
*address
)
269 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
271 m_error
= GSOCK_INVADDR
;
272 return GSOCK_INVADDR
;
276 GAddress_destroy(m_peer
);
278 m_peer
= GAddress_copy(address
);
280 return GSOCK_NOERROR
;
283 GAddress
*GSocket::GetLocal()
286 struct sockaddr addr
;
287 SOCKLEN_T size
= sizeof(addr
);
292 /* try to get it from the m_local var first */
294 return GAddress_copy(m_local
);
296 /* else, if the socket is initialized, try getsockname */
297 if (m_fd
== INVALID_SOCKET
)
299 m_error
= GSOCK_INVSOCK
;
303 if (getsockname(m_fd
, &addr
, &size
) == SOCKET_ERROR
)
305 m_error
= GSOCK_IOERR
;
309 /* got a valid address from getsockname, create a GAddress object */
310 if ((address
= GAddress_new()) == NULL
)
312 m_error
= GSOCK_MEMERR
;
316 if ((err
= _GAddress_translate_from(address
, &addr
, size
)) != GSOCK_NOERROR
)
318 GAddress_destroy(address
);
326 GAddress
*GSocket::GetPeer()
330 /* try to get it from the m_peer var */
332 return GAddress_copy(m_peer
);
337 /* Server specific parts */
339 /* GSocket_SetServer:
340 * Sets up this socket as a server. The local address must have been
341 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
342 * Returns GSOCK_NOERROR on success, one of the following otherwise:
345 * GSOCK_INVSOCK - the socket is in use.
346 * GSOCK_INVADDR - the local address has not been set.
347 * GSOCK_IOERR - low-level error.
349 GSocketError
GSocket::SetServer()
355 /* must not be in use */
356 if (m_fd
!= INVALID_SOCKET
)
358 m_error
= GSOCK_INVSOCK
;
359 return GSOCK_INVSOCK
;
362 /* the local addr must have been set */
365 m_error
= GSOCK_INVADDR
;
366 return GSOCK_INVADDR
;
369 /* Initialize all fields */
373 /* Create the socket */
374 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
376 if (m_fd
== INVALID_SOCKET
)
378 m_error
= GSOCK_IOERR
;
382 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
383 gs_gui_functions
->Enable_Events(this);
385 /* allow a socket to re-bind if the socket is in the TIME_WAIT
386 state after being previously closed.
389 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
392 /* Bind to the local address,
393 * retrieve the actual address bound,
394 * and listen up to 5 connections.
396 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
399 (SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
400 (listen(m_fd
, 5) != 0))
403 m_error
= GSOCK_IOERR
;
407 return GSOCK_NOERROR
;
410 /* GSocket_WaitConnection:
411 * Waits for an incoming client connection. Returns a pointer to
412 * a GSocket object, or NULL if there was an error, in which case
413 * the last error field will be updated for the calling GSocket.
415 * Error codes (set in the calling GSocket)
416 * GSOCK_INVSOCK - the socket is not valid or not a server.
417 * GSOCK_TIMEDOUT - timeout, no incoming connections.
418 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
419 * GSOCK_MEMERR - couldn't allocate memory.
420 * GSOCK_IOERR - low-level error.
422 GSocket
*GSocket::WaitConnection()
425 struct sockaddr from
;
426 SOCKLEN_T fromlen
= sizeof(from
);
432 /* Reenable CONNECTION events */
433 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
435 /* If the socket has already been created, we exit immediately */
436 if (m_fd
== INVALID_SOCKET
|| !m_server
)
438 m_error
= GSOCK_INVSOCK
;
442 /* Create a GSocket object for the new connection */
443 connection
= GSocket_new();
447 m_error
= GSOCK_MEMERR
;
451 /* Wait for a connection (with timeout) */
452 if (Input_Timeout() == GSOCK_TIMEDOUT
)
455 /* m_error set by _GSocket_Input_Timeout */
459 connection
->m_fd
= accept(m_fd
, &from
, &fromlen
);
461 if (connection
->m_fd
== INVALID_SOCKET
)
463 if (WSAGetLastError() == WSAEWOULDBLOCK
)
464 m_error
= GSOCK_WOULDBLOCK
;
466 m_error
= GSOCK_IOERR
;
472 /* Initialize all fields */
473 connection
->m_server
= false;
474 connection
->m_stream
= true;
476 /* Setup the peer address field */
477 connection
->m_peer
= GAddress_new();
478 if (!connection
->m_peer
)
481 m_error
= GSOCK_MEMERR
;
484 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
485 if (err
!= GSOCK_NOERROR
)
487 GAddress_destroy(connection
->m_peer
);
493 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
494 gs_gui_functions
->Enable_Events(connection
);
499 /* GSocket_SetReusable:
500 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
501 * make the appropriate setsockopt() call.
502 * Implemented as a GSocket function because clients (ie, wxSocketServer)
503 * don't have access to the GSocket struct information.
504 * Returns TRUE if the flag was set correctly, FALSE if an error occured
505 * (ie, if the parameter was NULL)
507 bool GSocket::SetReusable()
509 /* socket must not be null, and must not be in use/already bound */
510 if (this && m_fd
== INVALID_SOCKET
) {
517 /* Client specific parts */
520 * For stream (connection oriented) sockets, GSocket_Connect() tries
521 * to establish a client connection to a server using the peer address
522 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
523 * connection has been succesfully established, or one of the error
524 * codes listed below. Note that for nonblocking sockets, a return
525 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
526 * request can be completed later; you should use GSocket_Select()
527 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
528 * corresponding asynchronous events.
530 * For datagram (non connection oriented) sockets, GSocket_Connect()
531 * just sets the peer address established with GSocket_SetPeer() as
532 * default destination.
535 * GSOCK_INVSOCK - the socket is in use or not valid.
536 * GSOCK_INVADDR - the peer address has not been established.
537 * GSOCK_TIMEDOUT - timeout, the connection failed.
538 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
539 * GSOCK_MEMERR - couldn't allocate memory.
540 * GSOCK_IOERR - low-level error.
542 GSocketError
GSocket::Connect(GSocketStream stream
)
549 /* Enable CONNECTION events (needed for nonblocking connections) */
550 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
552 if (m_fd
!= INVALID_SOCKET
)
554 m_error
= GSOCK_INVSOCK
;
555 return GSOCK_INVSOCK
;
560 m_error
= GSOCK_INVADDR
;
561 return GSOCK_INVADDR
;
564 /* Streamed or dgram socket? */
565 m_stream
= (stream
== GSOCK_STREAMED
);
567 m_establishing
= false;
569 /* Create the socket */
570 m_fd
= socket(m_peer
->m_realfamily
,
571 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
573 if (m_fd
== INVALID_SOCKET
)
575 m_error
= GSOCK_IOERR
;
579 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
580 gs_gui_functions
->Enable_Events(this);
582 /* Connect it to the peer address, with a timeout (see below) */
583 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
585 if (ret
== SOCKET_ERROR
)
587 err
= WSAGetLastError();
589 /* If connect failed with EWOULDBLOCK and the GSocket object
590 * is in blocking mode, we select() for the specified timeout
591 * checking for writability to see if the connection request
594 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
596 err
= Connect_Timeout();
598 if (err
!= GSOCK_NOERROR
)
601 /* m_error is set in _GSocket_Connect_Timeout */
604 return (GSocketError
) err
;
607 /* If connect failed with EWOULDBLOCK and the GSocket object
608 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
609 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
610 * this way if the connection completes, a GSOCK_CONNECTION
611 * event will be generated, if enabled.
613 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
615 m_establishing
= true;
616 m_error
= GSOCK_WOULDBLOCK
;
617 return GSOCK_WOULDBLOCK
;
620 /* If connect failed with an error other than EWOULDBLOCK,
621 * then the call to GSocket_Connect() has failed.
624 m_error
= GSOCK_IOERR
;
628 return GSOCK_NOERROR
;
631 /* Datagram sockets */
633 /* GSocket_SetNonOriented:
634 * Sets up this socket as a non-connection oriented (datagram) socket.
635 * Before using this function, the local address must have been set
636 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
637 * on success, or one of the following otherwise.
640 * GSOCK_INVSOCK - the socket is in use.
641 * GSOCK_INVADDR - the local address has not been set.
642 * GSOCK_IOERR - low-level error.
644 GSocketError
GSocket::SetNonOriented()
650 if (m_fd
!= INVALID_SOCKET
)
652 m_error
= GSOCK_INVSOCK
;
653 return GSOCK_INVSOCK
;
658 m_error
= GSOCK_INVADDR
;
659 return GSOCK_INVADDR
;
662 /* Initialize all fields */
666 /* Create the socket */
667 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
669 if (m_fd
== INVALID_SOCKET
)
671 m_error
= GSOCK_IOERR
;
675 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
676 gs_gui_functions
->Enable_Events(this);
678 /* Bind to the local address,
679 * and retrieve the actual address bound.
681 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
684 (SOCKLEN_T
*)&m_local
->m_len
) != 0))
687 m_error
= GSOCK_IOERR
;
691 return GSOCK_NOERROR
;
696 /* Like recv(), send(), ... */
697 int GSocket::Read(char *buffer
, int size
)
703 /* Reenable INPUT events */
704 m_detected
&= ~GSOCK_INPUT_FLAG
;
706 if (m_fd
== INVALID_SOCKET
|| m_server
)
708 m_error
= GSOCK_INVSOCK
;
712 /* If the socket is blocking, wait for data (with a timeout) */
713 if (Input_Timeout() == GSOCK_TIMEDOUT
)
718 ret
= Recv_Stream(buffer
, size
);
720 ret
= Recv_Dgram(buffer
, size
);
722 if (ret
== SOCKET_ERROR
)
724 if (WSAGetLastError() != WSAEWOULDBLOCK
)
725 m_error
= GSOCK_IOERR
;
727 m_error
= GSOCK_WOULDBLOCK
;
734 int GSocket::Write(const char *buffer
, int size
)
740 if (m_fd
== INVALID_SOCKET
|| m_server
)
742 m_error
= GSOCK_INVSOCK
;
746 /* If the socket is blocking, wait for writability (with a timeout) */
747 if (Output_Timeout() == GSOCK_TIMEDOUT
)
752 ret
= Send_Stream(buffer
, size
);
754 ret
= Send_Dgram(buffer
, size
);
756 if (ret
== SOCKET_ERROR
)
758 if (WSAGetLastError() != WSAEWOULDBLOCK
)
759 m_error
= GSOCK_IOERR
;
761 m_error
= GSOCK_WOULDBLOCK
;
763 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
764 * does). Once the first OUTPUT event is received, users can assume
765 * that the socket is writable until a read operation fails. Only then
766 * will further OUTPUT events be posted.
768 m_detected
&= ~GSOCK_OUTPUT_FLAG
;
776 * Polls the socket to determine its status. This function will
777 * check for the events specified in the 'flags' parameter, and
778 * it will return a mask indicating which operations can be
779 * performed. This function won't block, regardless of the
780 * mode (blocking | nonblocking) of the socket.
782 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
784 if (!gs_gui_functions
->CanUseEventLoop())
786 GSocketEventFlags result
= 0;
796 FD_SET(m_fd
, &readfds
);
797 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
798 FD_SET(m_fd
, &writefds
);
799 FD_SET(m_fd
, &exceptfds
);
801 /* Check 'sticky' CONNECTION flag first */
802 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
804 /* If we have already detected a LOST event, then don't try
805 * to do any further processing.
807 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
809 m_establishing
= false;
811 return (GSOCK_LOST_FLAG
& flags
);
815 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
,
818 /* What to do here? */
819 return (result
& flags
);
822 /* Check for readability */
823 if (FD_ISSET(m_fd
, &readfds
))
827 if (!m_stream
|| recv(m_fd
, &c
, 1, MSG_PEEK
) > 0)
829 result
|= GSOCK_INPUT_FLAG
;
833 if (m_server
&& m_stream
)
835 result
|= GSOCK_CONNECTION_FLAG
;
836 m_detected
|= GSOCK_CONNECTION_FLAG
;
840 m_detected
= GSOCK_LOST_FLAG
;
841 m_establishing
= false;
843 /* LOST event: Abort any further processing */
844 return (GSOCK_LOST_FLAG
& flags
);
849 /* Check for writability */
850 if (FD_ISSET(m_fd
, &writefds
))
852 if (m_establishing
&& !m_server
)
855 SOCKLEN_T len
= sizeof(error
);
857 m_establishing
= false;
859 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
863 m_detected
= GSOCK_LOST_FLAG
;
865 /* LOST event: Abort any further processing */
866 return (GSOCK_LOST_FLAG
& flags
);
870 result
|= GSOCK_CONNECTION_FLAG
;
871 m_detected
|= GSOCK_CONNECTION_FLAG
;
876 result
|= GSOCK_OUTPUT_FLAG
;
880 /* Check for exceptions and errors (is this useful in Unices?) */
881 if (FD_ISSET(m_fd
, &exceptfds
))
883 m_establishing
= false;
884 m_detected
= GSOCK_LOST_FLAG
;
886 /* LOST event: Abort any further processing */
887 return (GSOCK_LOST_FLAG
& flags
);
890 return (result
& flags
);
895 return flags
& m_detected
;
901 /* GSocket_SetNonBlocking:
902 * Sets the socket to non-blocking mode. All IO calls will return
905 void GSocket::SetNonBlocking(bool non_block
)
909 m_non_blocking
= non_block
;
912 /* GSocket_SetTimeout:
913 * Sets the timeout for blocking calls. Time is expressed in
916 void GSocket::SetTimeout(unsigned long millis
)
920 m_timeout
.tv_sec
= (millis
/ 1000);
921 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
925 * Returns the last error occured for this socket. Note that successful
926 * operations do not clear this back to GSOCK_NOERROR, so use it only
929 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
939 * There is data to be read in the input buffer. If, after a read
940 * operation, there is still data available, the callback function will
943 * The socket is available for writing. That is, the next write call
944 * won't block. This event is generated only once, when the connection is
945 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
946 * when the output buffer empties again. This means that the app should
947 * assume that it can write since the first OUTPUT event, and no more
948 * OUTPUT events will be generated unless an error occurs.
950 * Connection succesfully established, for client sockets, or incoming
951 * client connection, for server sockets. Wait for this event (also watch
952 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
954 * The connection is lost (or a connection request failed); this could
955 * be due to a failure, or due to the peer closing it gracefully.
958 /* GSocket_SetCallback:
959 * Enables the callbacks specified by 'flags'. Note that 'flags'
960 * may be a combination of flags OR'ed toghether, so the same
961 * callback function can be made to accept different events.
962 * The callback function must have the following prototype:
964 * void function(GSocket *socket, GSocketEvent event, char *cdata)
966 void GSocket::SetCallback(GSocketEventFlags flags
,
967 GSocketCallback callback
, char *cdata
)
973 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
975 if ((flags
& (1 << count
)) != 0)
977 m_cbacks
[count
] = callback
;
978 m_data
[count
] = cdata
;
983 /* GSocket_UnsetCallback:
984 * Disables all callbacks specified by 'flags', which may be a
985 * combination of flags OR'ed toghether.
987 void GSocket::UnsetCallback(GSocketEventFlags flags
)
993 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
995 if ((flags
& (1 << count
)) != 0)
997 m_cbacks
[count
] = NULL
;
998 m_data
[count
] = NULL
;
1003 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1004 void *optval
, int *optlen
)
1006 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1008 return GSOCK_NOERROR
;
1010 return GSOCK_OPTERR
;
1013 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1014 const void *optval
, int optlen
)
1016 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
1018 return GSOCK_NOERROR
;
1020 return GSOCK_OPTERR
;
1023 /* Internals (IO) */
1025 /* _GSocket_Input_Timeout:
1026 * For blocking sockets, wait until data is available or
1027 * until timeout ellapses.
1029 GSocketError
GSocket::Input_Timeout()
1033 if (!m_non_blocking
)
1036 FD_SET(m_fd
, &readfds
);
1037 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
1039 m_error
= GSOCK_TIMEDOUT
;
1040 return GSOCK_TIMEDOUT
;
1043 return GSOCK_NOERROR
;
1046 /* _GSocket_Output_Timeout:
1047 * For blocking sockets, wait until data can be sent without
1048 * blocking or until timeout ellapses.
1050 GSocketError
GSocket::Output_Timeout()
1054 if (!m_non_blocking
)
1057 FD_SET(m_fd
, &writefds
);
1058 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
1060 m_error
= GSOCK_TIMEDOUT
;
1061 return GSOCK_TIMEDOUT
;
1064 return GSOCK_NOERROR
;
1067 /* _GSocket_Connect_Timeout:
1068 * For blocking sockets, wait until the connection is
1069 * established or fails, or until timeout ellapses.
1071 GSocketError
GSocket::Connect_Timeout()
1077 FD_ZERO(&exceptfds
);
1078 FD_SET(m_fd
, &writefds
);
1079 FD_SET(m_fd
, &exceptfds
);
1080 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
1082 m_error
= GSOCK_TIMEDOUT
;
1083 return GSOCK_TIMEDOUT
;
1085 if (!FD_ISSET(m_fd
, &writefds
))
1087 m_error
= GSOCK_IOERR
;
1091 return GSOCK_NOERROR
;
1094 int GSocket::Recv_Stream(char *buffer
, int size
)
1096 return recv(m_fd
, buffer
, size
, 0);
1099 int GSocket::Recv_Dgram(char *buffer
, int size
)
1101 struct sockaddr from
;
1102 SOCKLEN_T fromlen
= sizeof(from
);
1106 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, &fromlen
);
1108 if (ret
== SOCKET_ERROR
)
1109 return SOCKET_ERROR
;
1111 /* Translate a system address into a GSocket address */
1114 m_peer
= GAddress_new();
1117 m_error
= GSOCK_MEMERR
;
1121 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1122 if (err
!= GSOCK_NOERROR
)
1124 GAddress_destroy(m_peer
);
1133 int GSocket::Send_Stream(const char *buffer
, int size
)
1135 return send(m_fd
, buffer
, size
, 0);
1138 int GSocket::Send_Dgram(const char *buffer
, int size
)
1140 struct sockaddr
*addr
;
1146 m_error
= GSOCK_INVADDR
;
1150 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1151 if (err
!= GSOCK_NOERROR
)
1157 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1159 /* Frees memory allocated by _GAddress_translate_to */
1165 /* Compatibility functions for GSocket */
1166 GSocket
*GSocket_new(void)
1168 GSocket
*newsocket
= new GSocket();
1169 if(newsocket
->IsOk())
1177 * -------------------------------------------------------------------------
1179 * -------------------------------------------------------------------------
1182 /* CHECK_ADDRESS verifies that the current address family is either
1183 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1184 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1185 * an appropiate error code.
1187 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1189 #define CHECK_ADDRESS(address, family) \
1191 if (address->m_family == GSOCK_NOFAMILY) \
1192 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1193 return address->m_error; \
1194 if (address->m_family != GSOCK_##family) \
1196 address->m_error = GSOCK_INVADDR; \
1197 return GSOCK_INVADDR; \
1201 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1203 if (address->m_family == GSOCK_NOFAMILY) \
1204 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1206 if (address->m_family != GSOCK_##family) \
1208 address->m_error = GSOCK_INVADDR; \
1214 GAddress
*GAddress_new(void)
1218 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1221 address
->m_family
= GSOCK_NOFAMILY
;
1222 address
->m_addr
= NULL
;
1228 GAddress
*GAddress_copy(GAddress
*address
)
1232 assert(address
!= NULL
);
1234 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1237 memcpy(addr2
, address
, sizeof(GAddress
));
1239 if (address
->m_addr
)
1241 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1242 if (addr2
->m_addr
== NULL
)
1247 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1253 void GAddress_destroy(GAddress
*address
)
1255 assert(address
!= NULL
);
1257 if (address
->m_addr
)
1258 free(address
->m_addr
);
1263 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1265 assert(address
!= NULL
);
1267 address
->m_family
= type
;
1270 GAddressType
GAddress_GetFamily(GAddress
*address
)
1272 assert(address
!= NULL
);
1274 return address
->m_family
;
1277 GSocketError
_GAddress_translate_from(GAddress
*address
,
1278 struct sockaddr
*addr
, int len
)
1280 address
->m_realfamily
= addr
->sa_family
;
1281 switch (addr
->sa_family
)
1284 address
->m_family
= GSOCK_INET
;
1287 address
->m_family
= GSOCK_UNIX
;
1291 address
->m_family
= GSOCK_INET6
;
1296 address
->m_error
= GSOCK_INVOP
;
1301 if (address
->m_addr
)
1302 free(address
->m_addr
);
1304 address
->m_len
= len
;
1305 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1307 if (address
->m_addr
== NULL
)
1309 address
->m_error
= GSOCK_MEMERR
;
1310 return GSOCK_MEMERR
;
1312 memcpy(address
->m_addr
, addr
, len
);
1314 return GSOCK_NOERROR
;
1317 GSocketError
_GAddress_translate_to(GAddress
*address
,
1318 struct sockaddr
**addr
, int *len
)
1320 if (!address
->m_addr
)
1322 address
->m_error
= GSOCK_INVADDR
;
1323 return GSOCK_INVADDR
;
1326 *len
= address
->m_len
;
1327 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1330 address
->m_error
= GSOCK_MEMERR
;
1331 return GSOCK_MEMERR
;
1334 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1335 return GSOCK_NOERROR
;
1339 * -------------------------------------------------------------------------
1340 * Internet address family
1341 * -------------------------------------------------------------------------
1344 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1346 address
->m_len
= sizeof(struct sockaddr_in
);
1347 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1348 if (address
->m_addr
== NULL
)
1350 address
->m_error
= GSOCK_MEMERR
;
1351 return GSOCK_MEMERR
;
1354 address
->m_family
= GSOCK_INET
;
1355 address
->m_realfamily
= AF_INET
;
1356 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1357 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1359 return GSOCK_NOERROR
;
1362 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1365 struct in_addr
*addr
;
1367 assert(address
!= NULL
);
1369 CHECK_ADDRESS(address
, INET
);
1371 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1373 addr
->s_addr
= inet_addr(hostname
);
1375 /* If it is a numeric host name, convert it now */
1376 if (addr
->s_addr
== INADDR_NONE
)
1378 struct in_addr
*array_addr
;
1380 /* It is a real name, we solve it */
1381 if ((he
= gethostbyname(hostname
)) == NULL
)
1383 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1384 address
->m_error
= GSOCK_NOHOST
;
1385 return GSOCK_NOHOST
;
1387 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1388 addr
->s_addr
= array_addr
[0].s_addr
;
1390 return GSOCK_NOERROR
;
1393 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1395 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1398 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1399 unsigned long hostaddr
)
1401 struct in_addr
*addr
;
1403 assert(address
!= NULL
);
1405 CHECK_ADDRESS(address
, INET
);
1407 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1408 addr
->s_addr
= htonl(hostaddr
);;
1410 return GSOCK_NOERROR
;
1413 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1414 const char *protocol
)
1417 struct sockaddr_in
*addr
;
1419 assert(address
!= NULL
);
1420 CHECK_ADDRESS(address
, INET
);
1424 address
->m_error
= GSOCK_INVPORT
;
1425 return GSOCK_INVPORT
;
1428 se
= getservbyname(port
, protocol
);
1431 if (isdigit(port
[0]))
1435 port_int
= atoi(port
);
1436 addr
= (struct sockaddr_in
*)address
->m_addr
;
1437 addr
->sin_port
= htons((u_short
) port_int
);
1438 return GSOCK_NOERROR
;
1441 address
->m_error
= GSOCK_INVPORT
;
1442 return GSOCK_INVPORT
;
1445 addr
= (struct sockaddr_in
*)address
->m_addr
;
1446 addr
->sin_port
= se
->s_port
;
1448 return GSOCK_NOERROR
;
1451 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1453 struct sockaddr_in
*addr
;
1455 assert(address
!= NULL
);
1456 CHECK_ADDRESS(address
, INET
);
1458 addr
= (struct sockaddr_in
*)address
->m_addr
;
1459 addr
->sin_port
= htons(port
);
1461 return GSOCK_NOERROR
;
1464 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1468 struct sockaddr_in
*addr
;
1470 assert(address
!= NULL
);
1471 CHECK_ADDRESS(address
, INET
);
1473 addr
= (struct sockaddr_in
*)address
->m_addr
;
1474 addr_buf
= (char *)&(addr
->sin_addr
);
1476 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1479 address
->m_error
= GSOCK_NOHOST
;
1480 return GSOCK_NOHOST
;
1483 strncpy(hostname
, he
->h_name
, sbuf
);
1485 return GSOCK_NOERROR
;
1488 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1490 struct sockaddr_in
*addr
;
1492 assert(address
!= NULL
);
1493 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1495 addr
= (struct sockaddr_in
*)address
->m_addr
;
1497 return ntohl(addr
->sin_addr
.s_addr
);
1500 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1502 struct sockaddr_in
*addr
;
1504 assert(address
!= NULL
);
1505 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1507 addr
= (struct sockaddr_in
*)address
->m_addr
;
1508 return ntohs(addr
->sin_port
);
1512 * -------------------------------------------------------------------------
1513 * Unix address family
1514 * -------------------------------------------------------------------------
1517 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1519 assert (address
!= NULL
);
1520 address
->m_error
= GSOCK_INVADDR
;
1521 return GSOCK_INVADDR
;
1524 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1526 #if defined(__BORLANDC__)
1527 /* prevents unused variable message in Borland */
1530 assert (address
!= NULL
);
1531 address
->m_error
= GSOCK_INVADDR
;
1532 return GSOCK_INVADDR
;
1535 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1537 #if defined(__BORLANDC__)
1538 /* prevents unused variable message in Borland */
1542 assert (address
!= NULL
);
1543 address
->m_error
= GSOCK_INVADDR
;
1544 return GSOCK_INVADDR
;
1547 #else /* !wxUSE_SOCKETS */
1550 * Translation unit shouldn't be empty, so include this typedef to make the
1551 * compiler (VC++ 6.0, for example) happy
1553 typedef void (*wxDummy
)();
1555 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */