1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket)
3 * Name: src/msw/gsocket.cpp
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Author: Guillermo Rodriguez Garcia <guille@iies.es>
7 * Purpose: GSocket main MSW file
8 * Licence: The wxWindows licence
10 * -------------------------------------------------------------------------
13 // For compilers that support precompilation, includes "wx.h".
14 #include "wx/wxprec.h"
21 /* RPCNOTIFICATION_ROUTINE in rasasync.h (included from winsock.h),
22 * warning: conditional expression is constant.
24 # pragma warning(disable:4115)
26 * warning: named type definition in parentheses.
28 # pragma warning(disable:4127)
29 /* GAddress_UNIX_GetPath,
30 * warning: unreferenced formal parameter.
32 # pragma warning(disable:4100)
35 /* windows.h results in tons of warnings at max warning level */
37 # pragma warning(push, 1)
42 # pragma warning(disable:4514)
48 #if defined(__CYGWIN__)
49 //CYGWIN gives annoying warning about runtime stuff if we don't do this
50 # define USE_SYS_TYPES_FD_SET
51 # include <sys/types.h>
56 #include "wx/platform.h"
60 #include "wx/gsocket.h"
63 wxFORCE_LINK_MODULE(gsockmsw
)
67 #define isdigit(x) (x > 47 && x < 58)
69 #include "wx/msw/wince/net.h"
78 /* if we use configure for MSW WX_SOCKLEN_T will be already defined */
80 # define WX_SOCKLEN_T int
84 typedef struct sockaddr_storage wxSockAddr
;
86 typedef struct sockaddr wxSockAddr
;
93 GSocketManager
* const manager
= GSocketManager::Get();
94 if ( !manager
|| !manager
->OnInit() )
97 /* Initialize WinSocket */
98 return WSAStartup((1 << 8) | 1, &wsaData
) == 0;
101 void GSocket_Cleanup()
103 GSocketManager
* const manager
= GSocketManager::Get();
107 /* Cleanup WinSocket */
111 /* Constructors / Destructors for GSocket */
117 m_fd
= INVALID_SOCKET
;
118 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
125 m_error
= GSOCK_NOERROR
;
128 m_non_blocking
= false;
129 m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
130 m_timeout
.tv_usec
= 0;
131 m_establishing
= false;
135 m_initialRecvBufferSize
= -1;
136 m_initialSendBufferSize
= -1;
138 m_ok
= GSocketManager::Get()->Init_Socket(this);
141 void GSocket::Close()
143 GSocketManager::Get()->Disable_Events(this);
145 m_fd
= INVALID_SOCKET
;
150 GSocketManager::Get()->Destroy_Socket(this);
152 /* Check that the socket is really shutdowned */
153 if (m_fd
!= INVALID_SOCKET
)
156 /* Destroy private addresses */
158 GAddress_destroy(m_local
);
161 GAddress_destroy(m_peer
);
165 * Disallow further read/write operations on this socket, close
166 * the fd and disable all callbacks.
168 void GSocket::Shutdown()
172 /* If socket has been created, shutdown it */
173 if (m_fd
!= INVALID_SOCKET
)
175 shutdown(m_fd
, 1 /* SD_SEND */);
179 /* Disable GUI callbacks */
180 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
181 m_cbacks
[evt
] = NULL
;
183 m_detected
= GSOCK_LOST_FLAG
;
186 /* Address handling */
192 * Set or get the local or peer address for this socket. The 'set'
193 * functions return GSOCK_NOERROR on success, an error code otherwise.
194 * The 'get' functions return a pointer to a GAddress object on success,
195 * or NULL otherwise, in which case they set the error code of the
196 * corresponding GSocket.
199 * GSOCK_INVSOCK - the socket is not valid.
200 * GSOCK_INVADDR - the address is not valid.
202 GSocketError
GSocket::SetLocal(GAddress
*address
)
204 /* the socket must be initialized, or it must be a server */
205 if (m_fd
!= INVALID_SOCKET
&& !m_server
)
207 m_error
= GSOCK_INVSOCK
;
208 return GSOCK_INVSOCK
;
212 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
214 m_error
= GSOCK_INVADDR
;
215 return GSOCK_INVADDR
;
219 GAddress_destroy(m_local
);
221 m_local
= GAddress_copy(address
);
223 return GSOCK_NOERROR
;
226 GSocketError
GSocket::SetPeer(GAddress
*address
)
229 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
231 m_error
= GSOCK_INVADDR
;
232 return GSOCK_INVADDR
;
236 GAddress_destroy(m_peer
);
238 m_peer
= GAddress_copy(address
);
240 return GSOCK_NOERROR
;
243 GAddress
*GSocket::GetLocal()
247 WX_SOCKLEN_T size
= sizeof(addr
);
250 /* try to get it from the m_local var first */
252 return GAddress_copy(m_local
);
254 /* else, if the socket is initialized, try getsockname */
255 if (m_fd
== INVALID_SOCKET
)
257 m_error
= GSOCK_INVSOCK
;
261 if (getsockname(m_fd
, (sockaddr
*)&addr
, &size
) == SOCKET_ERROR
)
263 m_error
= GSOCK_IOERR
;
267 /* got a valid address from getsockname, create a GAddress object */
268 if ((address
= GAddress_new()) == NULL
)
270 m_error
= GSOCK_MEMERR
;
274 if ((err
= _GAddress_translate_from(address
, (sockaddr
*)&addr
, size
)) != GSOCK_NOERROR
)
276 GAddress_destroy(address
);
284 GAddress
*GSocket::GetPeer()
286 /* try to get it from the m_peer var */
288 return GAddress_copy(m_peer
);
293 /* Server specific parts */
295 /* GSocket_SetServer:
296 * Sets up this socket as a server. The local address must have been
297 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
298 * Returns GSOCK_NOERROR on success, one of the following otherwise:
301 * GSOCK_INVSOCK - the socket is in use.
302 * GSOCK_INVADDR - the local address has not been set.
303 * GSOCK_IOERR - low-level error.
305 GSocketError
GSocket::SetServer()
309 /* must not be in use */
310 if (m_fd
!= INVALID_SOCKET
)
312 m_error
= GSOCK_INVSOCK
;
313 return GSOCK_INVSOCK
;
316 /* the local addr must have been set */
319 m_error
= GSOCK_INVADDR
;
320 return GSOCK_INVADDR
;
323 /* Initialize all fields */
327 /* Create the socket */
328 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
330 if (m_fd
== INVALID_SOCKET
)
332 m_error
= GSOCK_IOERR
;
336 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
337 GSocketManager::Get()->Enable_Events(this);
339 /* allow a socket to re-bind if the socket is in the TIME_WAIT
340 state after being previously closed.
344 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
347 /* Bind to the local address,
348 * retrieve the actual address bound,
349 * and listen up to 5 connections.
351 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
354 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0) ||
355 (listen(m_fd
, 5) != 0))
358 m_error
= GSOCK_IOERR
;
362 return GSOCK_NOERROR
;
365 /* GSocket_WaitConnection:
366 * Waits for an incoming client connection. Returns a pointer to
367 * a GSocket object, or NULL if there was an error, in which case
368 * the last error field will be updated for the calling GSocket.
370 * Error codes (set in the calling GSocket)
371 * GSOCK_INVSOCK - the socket is not valid or not a server.
372 * GSOCK_TIMEDOUT - timeout, no incoming connections.
373 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
374 * GSOCK_MEMERR - couldn't allocate memory.
375 * GSOCK_IOERR - low-level error.
377 GSocket
*GSocket::WaitConnection()
381 WX_SOCKLEN_T fromlen
= sizeof(from
);
385 /* Reenable CONNECTION events */
386 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
388 /* If the socket has already been created, we exit immediately */
389 if (m_fd
== INVALID_SOCKET
|| !m_server
)
391 m_error
= GSOCK_INVSOCK
;
395 /* Create a GSocket object for the new connection */
396 connection
= GSocket_new();
400 m_error
= GSOCK_MEMERR
;
404 /* Wait for a connection (with timeout) */
405 if (Input_Timeout() == GSOCK_TIMEDOUT
)
408 /* m_error set by _GSocket_Input_Timeout */
412 connection
->m_fd
= accept(m_fd
, (sockaddr
*)&from
, &fromlen
);
414 if (connection
->m_fd
== INVALID_SOCKET
)
416 if (WSAGetLastError() == WSAEWOULDBLOCK
)
417 m_error
= GSOCK_WOULDBLOCK
;
419 m_error
= GSOCK_IOERR
;
425 /* Initialize all fields */
426 connection
->m_server
= false;
427 connection
->m_stream
= true;
429 /* Setup the peer address field */
430 connection
->m_peer
= GAddress_new();
431 if (!connection
->m_peer
)
434 m_error
= GSOCK_MEMERR
;
437 err
= _GAddress_translate_from(connection
->m_peer
, (sockaddr
*)&from
, fromlen
);
438 if (err
!= GSOCK_NOERROR
)
440 GAddress_destroy(connection
->m_peer
);
446 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
447 GSocketManager::Get()->Enable_Events(connection
);
452 /* GSocket_SetReusable:
453 * Simply sets the m_resuable flag on the socket. GSocket_SetServer will
454 * make the appropriate setsockopt() call.
455 * Implemented as a GSocket function because clients (ie, wxSocketServer)
456 * don't have access to the GSocket struct information.
457 * Returns true if the flag was set correctly, false if an error occurred
458 * (ie, if the parameter was NULL)
460 bool GSocket::SetReusable()
462 /* socket must not be null, and must not be in use/already bound */
463 if (this && m_fd
== INVALID_SOCKET
) {
470 /* GSocket_SetBroadcast:
471 * Simply sets the m_broadcast flag on the socket. GSocket_SetServer will
472 * make the appropriate setsockopt() call.
473 * Implemented as a GSocket function because clients (ie, wxSocketServer)
474 * don't have access to the GSocket struct information.
475 * Returns true if the flag was set correctly, false if an error occurred
476 * (ie, if the parameter was NULL)
478 bool GSocket::SetBroadcast()
480 /* socket must not be in use/already bound */
481 if (m_fd
== INVALID_SOCKET
) {
488 bool GSocket::DontDoBind()
490 /* socket must not be in use/already bound */
491 if (m_fd
== INVALID_SOCKET
) {
498 /* Client specific parts */
501 * For stream (connection oriented) sockets, GSocket_Connect() tries
502 * to establish a client connection to a server using the peer address
503 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
504 * connection has been successfully established, or one of the error
505 * codes listed below. Note that for nonblocking sockets, a return
506 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
507 * request can be completed later; you should use GSocket_Select()
508 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
509 * corresponding asynchronous events.
511 * For datagram (non connection oriented) sockets, GSocket_Connect()
512 * just sets the peer address established with GSocket_SetPeer() as
513 * default destination.
516 * GSOCK_INVSOCK - the socket is in use or not valid.
517 * GSOCK_INVADDR - the peer address has not been established.
518 * GSOCK_TIMEDOUT - timeout, the connection failed.
519 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
520 * GSOCK_MEMERR - couldn't allocate memory.
521 * GSOCK_IOERR - low-level error.
523 GSocketError
GSocket::Connect(GSocketStream stream
)
528 /* Enable CONNECTION events (needed for nonblocking connections) */
529 m_detected
&= ~GSOCK_CONNECTION_FLAG
;
531 if (m_fd
!= INVALID_SOCKET
)
533 m_error
= GSOCK_INVSOCK
;
534 return GSOCK_INVSOCK
;
539 m_error
= GSOCK_INVADDR
;
540 return GSOCK_INVADDR
;
543 /* Streamed or dgram socket? */
544 m_stream
= (stream
== GSOCK_STREAMED
);
546 m_establishing
= false;
548 /* Create the socket */
549 m_fd
= socket(m_peer
->m_realfamily
,
550 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
552 if (m_fd
== INVALID_SOCKET
)
554 m_error
= GSOCK_IOERR
;
558 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
559 GSocketManager::Get()->Enable_Events(this);
561 // If the reuse flag is set, use the applicable socket reuse flag
564 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
567 if (m_initialRecvBufferSize
>= 0)
568 setsockopt(m_fd
, SOL_SOCKET
, SO_RCVBUF
, (const char*)&m_initialRecvBufferSize
, sizeof(m_initialRecvBufferSize
));
569 if (m_initialSendBufferSize
>= 0)
570 setsockopt(m_fd
, SOL_SOCKET
, SO_SNDBUF
, (const char*)&m_initialSendBufferSize
, sizeof(m_initialSendBufferSize
));
572 // If a local address has been set, then we need to bind to it before calling connect
573 if (m_local
&& m_local
->m_addr
)
575 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
578 /* Connect it to the peer address, with a timeout (see below) */
579 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
581 if (ret
== SOCKET_ERROR
)
583 err
= WSAGetLastError();
585 /* If connect failed with EWOULDBLOCK and the GSocket object
586 * is in blocking mode, we select() for the specified timeout
587 * checking for writability to see if the connection request
590 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
592 err
= Connect_Timeout();
594 if (err
!= GSOCK_NOERROR
)
597 /* m_error is set in _GSocket_Connect_Timeout */
600 return (GSocketError
) err
;
603 /* If connect failed with EWOULDBLOCK and the GSocket object
604 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
605 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
606 * this way if the connection completes, a GSOCK_CONNECTION
607 * event will be generated, if enabled.
609 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
611 m_establishing
= true;
612 m_error
= GSOCK_WOULDBLOCK
;
613 return GSOCK_WOULDBLOCK
;
616 /* If connect failed with an error other than EWOULDBLOCK,
617 * then the call to GSocket_Connect() has failed.
620 m_error
= GSOCK_IOERR
;
624 return GSOCK_NOERROR
;
627 /* Datagram sockets */
629 /* GSocket_SetNonOriented:
630 * Sets up this socket as a non-connection oriented (datagram) socket.
631 * Before using this function, the local address must have been set
632 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
633 * on success, or one of the following otherwise.
636 * GSOCK_INVSOCK - the socket is in use.
637 * GSOCK_INVADDR - the local address has not been set.
638 * GSOCK_IOERR - low-level error.
640 GSocketError
GSocket::SetNonOriented()
644 if (m_fd
!= INVALID_SOCKET
)
646 m_error
= GSOCK_INVSOCK
;
647 return GSOCK_INVSOCK
;
652 m_error
= GSOCK_INVADDR
;
653 return GSOCK_INVADDR
;
656 /* Initialize all fields */
660 /* Create the socket */
661 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
663 if (m_fd
== INVALID_SOCKET
)
665 m_error
= GSOCK_IOERR
;
669 ioctlsocket(m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
670 GSocketManager::Get()->Enable_Events(this);
674 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
678 setsockopt(m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char*)&arg
, sizeof(arg
));
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 (WX_SOCKLEN_T
*)&m_local
->m_len
) != 0))
691 m_error
= GSOCK_IOERR
;
696 return GSOCK_NOERROR
;
701 /* Like recv(), send(), ... */
702 int GSocket::Read(char *buffer
, int size
)
706 /* Reenable INPUT events */
707 m_detected
&= ~GSOCK_INPUT_FLAG
;
709 if (m_fd
== INVALID_SOCKET
|| m_server
)
711 m_error
= GSOCK_INVSOCK
;
715 /* If the socket is blocking, wait for data (with a timeout) */
716 if (Input_Timeout() == GSOCK_TIMEDOUT
)
718 m_error
= GSOCK_TIMEDOUT
;
724 ret
= Recv_Stream(buffer
, size
);
726 ret
= Recv_Dgram(buffer
, size
);
728 if (ret
== SOCKET_ERROR
)
730 if (WSAGetLastError() != WSAEWOULDBLOCK
)
731 m_error
= GSOCK_IOERR
;
733 m_error
= GSOCK_WOULDBLOCK
;
740 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 return flags
& m_detected
;
793 /* GSocket_SetNonBlocking:
794 * Sets the socket to non-blocking mode. All IO calls will return
797 void GSocket::SetNonBlocking(bool non_block
)
799 m_non_blocking
= non_block
;
802 /* GSocket_SetTimeout:
803 * Sets the timeout for blocking calls. Time is expressed in
806 void GSocket::SetTimeout(unsigned long millis
)
808 m_timeout
.tv_sec
= (millis
/ 1000);
809 m_timeout
.tv_usec
= (millis
% 1000) * 1000;
813 * Returns the last error occurred for this socket. Note that successful
814 * operations do not clear this back to GSOCK_NOERROR, so use it only
817 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
825 * There is data to be read in the input buffer. If, after a read
826 * operation, there is still data available, the callback function will
829 * The socket is available for writing. That is, the next write call
830 * won't block. This event is generated only once, when the connection is
831 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
832 * when the output buffer empties again. This means that the app should
833 * assume that it can write since the first OUTPUT event, and no more
834 * OUTPUT events will be generated unless an error occurs.
836 * Connection successfully established, for client sockets, or incoming
837 * client connection, for server sockets. Wait for this event (also watch
838 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
840 * The connection is lost (or a connection request failed); this could
841 * be due to a failure, or due to the peer closing it gracefully.
844 /* GSocket_SetCallback:
845 * Enables the callbacks specified by 'flags'. Note that 'flags'
846 * may be a combination of flags OR'ed toghether, so the same
847 * callback function can be made to accept different events.
848 * The callback function must have the following prototype:
850 * void function(GSocket *socket, GSocketEvent event, char *cdata)
852 void GSocket::SetCallback(GSocketEventFlags flags
,
853 GSocketCallback callback
, char *cdata
)
857 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
859 if ((flags
& (1 << count
)) != 0)
861 m_cbacks
[count
] = callback
;
862 m_data
[count
] = cdata
;
867 /* GSocket_UnsetCallback:
868 * Disables all callbacks specified by 'flags', which may be a
869 * combination of flags OR'ed toghether.
871 void GSocket::UnsetCallback(GSocketEventFlags flags
)
875 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
877 if ((flags
& (1 << count
)) != 0)
879 m_cbacks
[count
] = NULL
;
880 m_data
[count
] = NULL
;
885 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
886 void *optval
, int *optlen
)
888 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
890 return GSOCK_NOERROR
;
895 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
896 const void *optval
, int optlen
)
898 if (setsockopt(m_fd
, level
, optname
, (char*)optval
, optlen
) == 0)
900 return GSOCK_NOERROR
;
907 /* _GSocket_Input_Timeout:
908 * For blocking sockets, wait until data is available or
909 * until timeout ellapses.
911 GSocketError
GSocket::Input_Timeout()
918 FD_SET(m_fd
, &readfds
);
919 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
921 m_error
= GSOCK_TIMEDOUT
;
922 return GSOCK_TIMEDOUT
;
925 return GSOCK_NOERROR
;
928 /* _GSocket_Output_Timeout:
929 * For blocking sockets, wait until data can be sent without
930 * blocking or until timeout ellapses.
932 GSocketError
GSocket::Output_Timeout()
939 FD_SET(m_fd
, &writefds
);
940 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
942 m_error
= GSOCK_TIMEDOUT
;
943 return GSOCK_TIMEDOUT
;
946 return GSOCK_NOERROR
;
949 /* _GSocket_Connect_Timeout:
950 * For blocking sockets, wait until the connection is
951 * established or fails, or until timeout ellapses.
953 GSocketError
GSocket::Connect_Timeout()
960 FD_SET(m_fd
, &writefds
);
961 FD_SET(m_fd
, &exceptfds
);
962 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
964 m_error
= GSOCK_TIMEDOUT
;
965 return GSOCK_TIMEDOUT
;
967 if (!FD_ISSET(m_fd
, &writefds
))
969 m_error
= GSOCK_IOERR
;
973 return GSOCK_NOERROR
;
976 int GSocket::Recv_Stream(char *buffer
, int size
)
978 return recv(m_fd
, buffer
, size
, 0);
981 int GSocket::Recv_Dgram(char *buffer
, int size
)
984 WX_SOCKLEN_T fromlen
= sizeof(from
);
988 ret
= recvfrom(m_fd
, buffer
, size
, 0, (sockaddr
*)&from
, &fromlen
);
990 if (ret
== SOCKET_ERROR
)
993 /* Translate a system address into a GSocket address */
996 m_peer
= GAddress_new();
999 m_error
= GSOCK_MEMERR
;
1003 err
= _GAddress_translate_from(m_peer
, (sockaddr
*)&from
, fromlen
);
1004 if (err
!= GSOCK_NOERROR
)
1006 GAddress_destroy(m_peer
);
1015 int GSocket::Send_Stream(const char *buffer
, int size
)
1017 return send(m_fd
, buffer
, size
, 0);
1020 int GSocket::Send_Dgram(const char *buffer
, int size
)
1022 struct sockaddr
*addr
;
1028 m_error
= GSOCK_INVADDR
;
1032 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1033 if (err
!= GSOCK_NOERROR
)
1039 ret
= sendto(m_fd
, buffer
, size
, 0, addr
, len
);
1041 /* Frees memory allocated by _GAddress_translate_to */
1047 /* Compatibility functions for GSocket */
1048 GSocket
*GSocket_new()
1050 GSocket
*newsocket
= new GSocket();
1051 if(newsocket
->IsOk())
1059 * -------------------------------------------------------------------------
1061 * -------------------------------------------------------------------------
1064 /* CHECK_ADDRESS verifies that the current address family is either
1065 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1066 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1067 * an appropiate error code.
1069 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1071 #define CHECK_ADDRESS(address, family) \
1073 if (address->m_family == GSOCK_NOFAMILY) \
1074 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1075 return address->m_error; \
1076 if (address->m_family != GSOCK_##family) \
1078 address->m_error = GSOCK_INVADDR; \
1079 return GSOCK_INVADDR; \
1083 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1085 if (address->m_family == GSOCK_NOFAMILY) \
1086 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1088 if (address->m_family != GSOCK_##family) \
1090 address->m_error = GSOCK_INVADDR; \
1096 GAddress
*GAddress_new()
1100 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1103 address
->m_family
= GSOCK_NOFAMILY
;
1104 address
->m_addr
= NULL
;
1110 GAddress
*GAddress_copy(GAddress
*address
)
1114 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1117 memcpy(addr2
, address
, sizeof(GAddress
));
1119 if (address
->m_addr
)
1121 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1122 if (addr2
->m_addr
== NULL
)
1127 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1133 void GAddress_destroy(GAddress
*address
)
1135 if (address
->m_addr
)
1136 free(address
->m_addr
);
1141 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1143 address
->m_family
= type
;
1146 GAddressType
GAddress_GetFamily(GAddress
*address
)
1148 return address
->m_family
;
1151 GSocketError
_GAddress_translate_from(GAddress
*address
,
1152 struct sockaddr
*addr
, int len
)
1154 address
->m_realfamily
= addr
->sa_family
;
1155 switch (addr
->sa_family
)
1158 address
->m_family
= GSOCK_INET
;
1161 address
->m_family
= GSOCK_UNIX
;
1165 address
->m_family
= GSOCK_INET6
;
1170 address
->m_error
= GSOCK_INVOP
;
1175 if (address
->m_addr
)
1176 free(address
->m_addr
);
1178 address
->m_len
= len
;
1179 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1181 if (address
->m_addr
== NULL
)
1183 address
->m_error
= GSOCK_MEMERR
;
1184 return GSOCK_MEMERR
;
1186 memcpy(address
->m_addr
, addr
, len
);
1188 return GSOCK_NOERROR
;
1191 GSocketError
_GAddress_translate_to(GAddress
*address
,
1192 struct sockaddr
**addr
, int *len
)
1194 if (!address
->m_addr
)
1196 address
->m_error
= GSOCK_INVADDR
;
1197 return GSOCK_INVADDR
;
1200 *len
= address
->m_len
;
1201 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1204 address
->m_error
= GSOCK_MEMERR
;
1205 return GSOCK_MEMERR
;
1208 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1209 return GSOCK_NOERROR
;
1213 * -------------------------------------------------------------------------
1214 * Internet address family
1215 * -------------------------------------------------------------------------
1218 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1220 address
->m_len
= sizeof(struct sockaddr_in
);
1221 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1222 if (address
->m_addr
== NULL
)
1224 address
->m_error
= GSOCK_MEMERR
;
1225 return GSOCK_MEMERR
;
1228 address
->m_family
= GSOCK_INET
;
1229 address
->m_realfamily
= AF_INET
;
1230 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1231 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1233 return GSOCK_NOERROR
;
1236 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1239 struct in_addr
*addr
;
1241 CHECK_ADDRESS(address
, INET
);
1243 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1245 addr
->s_addr
= inet_addr(hostname
);
1247 /* If it is a numeric host name, convert it now */
1248 if (addr
->s_addr
== INADDR_NONE
)
1250 struct in_addr
*array_addr
;
1252 /* It is a real name, we solve it */
1253 if ((he
= gethostbyname(hostname
)) == NULL
)
1255 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1256 address
->m_error
= GSOCK_NOHOST
;
1257 return GSOCK_NOHOST
;
1259 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1260 addr
->s_addr
= array_addr
[0].s_addr
;
1262 return GSOCK_NOERROR
;
1265 GSocketError
GAddress_INET_SetBroadcastAddress(GAddress
*address
)
1267 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1270 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1272 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1275 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1276 unsigned long hostaddr
)
1278 struct in_addr
*addr
;
1280 CHECK_ADDRESS(address
, INET
);
1282 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1283 addr
->s_addr
= htonl(hostaddr
);
1285 return GSOCK_NOERROR
;
1288 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1289 const char *protocol
)
1292 struct sockaddr_in
*addr
;
1294 CHECK_ADDRESS(address
, INET
);
1298 address
->m_error
= GSOCK_INVPORT
;
1299 return GSOCK_INVPORT
;
1302 se
= getservbyname(port
, protocol
);
1305 if (isdigit(port
[0]))
1309 port_int
= atoi(port
);
1310 addr
= (struct sockaddr_in
*)address
->m_addr
;
1311 addr
->sin_port
= htons((u_short
) port_int
);
1312 return GSOCK_NOERROR
;
1315 address
->m_error
= GSOCK_INVPORT
;
1316 return GSOCK_INVPORT
;
1319 addr
= (struct sockaddr_in
*)address
->m_addr
;
1320 addr
->sin_port
= se
->s_port
;
1322 return GSOCK_NOERROR
;
1325 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1327 struct sockaddr_in
*addr
;
1329 CHECK_ADDRESS(address
, INET
);
1331 addr
= (struct sockaddr_in
*)address
->m_addr
;
1332 addr
->sin_port
= htons(port
);
1334 return GSOCK_NOERROR
;
1337 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1341 struct sockaddr_in
*addr
;
1343 CHECK_ADDRESS(address
, INET
);
1345 addr
= (struct sockaddr_in
*)address
->m_addr
;
1346 addr_buf
= (char *)&(addr
->sin_addr
);
1348 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1351 address
->m_error
= GSOCK_NOHOST
;
1352 return GSOCK_NOHOST
;
1355 strncpy(hostname
, he
->h_name
, sbuf
);
1357 return GSOCK_NOERROR
;
1360 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1362 struct sockaddr_in
*addr
;
1364 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1366 addr
= (struct sockaddr_in
*)address
->m_addr
;
1368 return ntohl(addr
->sin_addr
.s_addr
);
1371 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1373 struct sockaddr_in
*addr
;
1375 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1377 addr
= (struct sockaddr_in
*)address
->m_addr
;
1378 return ntohs(addr
->sin_port
);
1384 * -------------------------------------------------------------------------
1385 * Internet IPv6 address family
1386 * -------------------------------------------------------------------------
1388 #include "ws2tcpip.h"
1391 #pragma comment(lib,"ws2_32")
1392 #endif // __VISUALC__
1394 GSocketError
_GAddress_Init_INET6(GAddress
*address
)
1396 struct in6_addr any_address
= IN6ADDR_ANY_INIT
;
1397 address
->m_len
= sizeof(struct sockaddr_in6
);
1398 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1399 if (address
->m_addr
== NULL
)
1401 address
->m_error
= GSOCK_MEMERR
;
1402 return GSOCK_MEMERR
;
1404 memset(address
->m_addr
,0,address
->m_len
);
1406 address
->m_family
= GSOCK_INET6
;
1407 address
->m_realfamily
= AF_INET6
;
1408 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_family
= AF_INET6
;
1409 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= any_address
;
1411 return GSOCK_NOERROR
;
1414 GSocketError
GAddress_INET6_SetHostName(GAddress
*address
, const char *hostname
)
1416 CHECK_ADDRESS(address
, INET6
);
1419 memset( & hints
, 0, sizeof( hints
) );
1420 hints
.ai_family
= AF_INET6
;
1421 addrinfo
* info
= 0;
1422 if ( getaddrinfo( hostname
, "0", & hints
, & info
) || ! info
)
1424 address
->m_error
= GSOCK_NOHOST
;
1425 return GSOCK_NOHOST
;
1428 memcpy( address
->m_addr
, info
->ai_addr
, info
->ai_addrlen
);
1429 freeaddrinfo( info
);
1430 return GSOCK_NOERROR
;
1433 GSocketError
GAddress_INET6_SetAnyAddress(GAddress
*address
)
1435 CHECK_ADDRESS(address
, INET6
);
1437 struct in6_addr addr
;
1438 memset( & addr
, 0, sizeof( addr
) );
1439 return GAddress_INET6_SetHostAddress(address
, addr
);
1441 GSocketError
GAddress_INET6_SetHostAddress(GAddress
*address
,
1442 struct in6_addr hostaddr
)
1444 CHECK_ADDRESS(address
, INET6
);
1446 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= hostaddr
;
1448 return GSOCK_NOERROR
;
1451 GSocketError
GAddress_INET6_SetPortName(GAddress
*address
, const char *port
,
1452 const char *protocol
)
1455 struct sockaddr_in6
*addr
;
1457 CHECK_ADDRESS(address
, INET6
);
1461 address
->m_error
= GSOCK_INVPORT
;
1462 return GSOCK_INVPORT
;
1465 se
= getservbyname(port
, protocol
);
1468 if (isdigit((unsigned char) port
[0]))
1472 port_int
= atoi(port
);
1473 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1474 addr
->sin6_port
= htons((u_short
) port_int
);
1475 return GSOCK_NOERROR
;
1478 address
->m_error
= GSOCK_INVPORT
;
1479 return GSOCK_INVPORT
;
1482 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1483 addr
->sin6_port
= se
->s_port
;
1485 return GSOCK_NOERROR
;
1488 GSocketError
GAddress_INET6_SetPort(GAddress
*address
, unsigned short port
)
1490 struct sockaddr_in6
*addr
;
1492 CHECK_ADDRESS(address
, INET6
);
1494 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1495 addr
->sin6_port
= htons(port
);
1497 return GSOCK_NOERROR
;
1500 GSocketError
GAddress_INET6_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1504 struct sockaddr_in6
*addr
;
1506 CHECK_ADDRESS(address
, INET6
);
1508 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1509 addr_buf
= (char *)&(addr
->sin6_addr
);
1511 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin6_addr
), AF_INET6
);
1514 address
->m_error
= GSOCK_NOHOST
;
1515 return GSOCK_NOHOST
;
1518 strncpy(hostname
, he
->h_name
, sbuf
);
1520 return GSOCK_NOERROR
;
1523 GSocketError
GAddress_INET6_GetHostAddress(GAddress
*address
,struct in6_addr
*hostaddr
)
1525 CHECK_ADDRESS_RETVAL(address
, INET6
, GSOCK_INVADDR
);
1526 *hostaddr
= ( (struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
;
1527 return GSOCK_NOERROR
;
1530 unsigned short GAddress_INET6_GetPort(GAddress
*address
)
1532 CHECK_ADDRESS_RETVAL(address
, INET6
, 0);
1534 return ntohs( ((struct sockaddr_in6
*)address
->m_addr
)->sin6_port
);
1537 #endif // wxUSE_IPV6
1540 * -------------------------------------------------------------------------
1541 * Unix address family
1542 * -------------------------------------------------------------------------
1545 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1547 address
->m_error
= GSOCK_INVADDR
;
1548 return GSOCK_INVADDR
;
1551 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1553 address
->m_error
= GSOCK_INVADDR
;
1554 return GSOCK_INVADDR
;
1557 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1559 address
->m_error
= GSOCK_INVADDR
;
1560 return GSOCK_INVADDR
;
1563 #endif // wxUSE_SOCKETS