1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Copyright: (c) Guilhem Lavaux
5 * Licence: wxWindows Licence
6 * Authors: David Elliott (C++ conversion, maintainer)
8 * Guillermo Rodriguez Garcia <guille@iies.es>
9 * Purpose: GSocket main Unix and OS/2 file
10 * Licence: The wxWindows licence
12 * -------------------------------------------------------------------------
15 #if defined(__WATCOMC__)
16 #include "wx/wxprec.h"
21 #ifndef __GSOCKET_STANDALONE__
25 #if defined(__VISAGECPP__)
26 #define BSD_SELECT /* use Berkeley Sockets select */
29 #if wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__)
32 #include <sys/types.h>
37 #include <netinet/in.h>
40 #ifndef _NETBSD_SOURCE
41 #define _NETBSD_SOURCE
48 #include <sys/ioctl.h>
54 u_char sun_len
; /* sockaddr len including null */
55 u_char sun_family
; /* AF_UNIX */
56 char sun_path
[108]; /* path name (gag) */
59 #include <sys/socket.h>
65 #include <netinet/in.h>
66 #include <arpa/inet.h>
73 #include <machine/endian.h>
79 #define EBADF SOCEBADF
85 #include <sys/socket.h>
86 #include <sys/ioctl.h>
87 #include <sys/select.h>
89 #define close(a) soclose(a)
90 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
91 int _System
bsdselect(int,
96 int _System
soclose(int);
100 #include <sys/select.h>
108 # include <sys/filio.h>
111 # include <bstring.h>
114 # include <strings.h>
121 # define WX_SOCKLEN_T unsigned int
125 # define WX_SOCKLEN_T socklen_t
127 # elif defined(__WXMAC__)
128 # define WX_SOCKLEN_T socklen_t
130 # define WX_SOCKLEN_T int
134 #endif /* SOCKLEN_T */
137 #define SOCKOPTLEN_T WX_SOCKLEN_T
141 * MSW defines this, Unices don't.
143 #ifndef INVALID_SOCKET
144 #define INVALID_SOCKET -1
147 /* UnixWare reportedly needs this for FIONBIO definition */
149 #include <sys/filio.h>
153 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
154 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
157 #define INADDR_NONE INADDR_BROADCAST
160 #if defined(__VISAGECPP__) || defined(__WATCOMC__)
162 #define MASK_SIGNAL() {
163 #define UNMASK_SIGNAL() }
166 extern "C" { typedef void (*wxSigHandler
)(int); }
168 #define MASK_SIGNAL() \
170 wxSigHandler old_handler = signal(SIGPIPE, SIG_IGN);
172 #define UNMASK_SIGNAL() \
173 signal(SIGPIPE, old_handler); \
178 /* If a SIGPIPE is issued by a socket call on a remotely closed socket,
179 the program will "crash" unless it explicitly handles the SIGPIPE.
180 By using MSG_NOSIGNAL, the SIGPIPE is suppressed. Later, we will
181 use SO_NOSIGPIPE (if available), the BSD equivalent. */
183 # define GSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
184 #else /* MSG_NOSIGNAL not available (FreeBSD including OS X) */
185 # define GSOCKET_MSG_NOSIGNAL 0
186 #endif /* MSG_NOSIGNAL */
188 #ifndef __GSOCKET_STANDALONE__
189 # include "wx/unix/gsockunx.h"
190 # include "wx/unix/private.h"
191 # include "wx/gsocket.h"
192 #if wxUSE_THREADS && (defined(HAVE_GETHOSTBYNAME) || defined(HAVE_GETSERVBYNAME))
193 # include "wx/thread.h"
196 # include "gsockunx.h"
197 # include "gsocket.h"
201 #endif /* __GSOCKET_STANDALONE__ */
203 #if defined(HAVE_GETHOSTBYNAME)
204 static struct hostent
* deepCopyHostent(struct hostent
*h
,
205 const struct hostent
*he
,
206 char *buffer
, int size
, int *err
)
208 memcpy(h
, he
, sizeof(struct hostent
));
209 int len
= strlen(h
->h_name
);
212 memcpy(buffer
, h
->h_name
, len
);
218 for (char **p
= h
->h_addr_list
; *p
!= 0; p
++) {
223 memcpy(buffer
, *p
, len
);
228 for (char **q
= h
->h_aliases
; size
> 0 && *q
!= 0; q
++){
232 memcpy(buffer
, *q
, len
);
242 struct hostent
* wxGethostbyname_r(const char *hostname
, struct hostent
*h
,
243 void *buffer
, int size
, int *err
)
246 struct hostent
*he
= NULL
;
248 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
249 if (gethostbyname_r(hostname
, h
, (char*)buffer
, size
, &he
, err
))
251 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
252 he
= gethostbyname_r(hostname
, h
, (char*)buffer
, size
, err
);
253 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
254 if (gethostbyname_r(hostname
, h
, (struct hostent_data
*) buffer
))
261 #elif defined(HAVE_GETHOSTBYNAME)
263 static wxMutex nameLock
;
264 wxMutexLocker
locker(nameLock
);
266 he
= gethostbyname(hostname
);
270 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
275 struct hostent
* wxGethostbyaddr_r(const char *addr_buf
, int buf_size
,
276 int proto
, struct hostent
*h
,
277 void *buffer
, int size
, int *err
)
279 struct hostent
*he
= NULL
;
281 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
282 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
283 (char*)buffer
, size
, &he
, err
))
285 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
286 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, (char*)buffer
, size
, err
);
287 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
288 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
289 (struct hostent_data
*) buffer
))
296 #elif defined(HAVE_GETHOSTBYNAME)
298 static wxMutex addrLock
;
299 wxMutexLocker
locker(addrLock
);
301 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
305 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
310 #if defined(HAVE_GETHOSTBYNAME)
311 static struct servent
* deepCopyServent(struct servent
*s
,
312 const struct servent
*se
,
313 char *buffer
, int size
)
315 memcpy(s
, se
, sizeof(struct servent
));
316 int len
= strlen(s
->s_name
);
319 memcpy(buffer
, s
->s_name
, len
);
324 len
= strlen(s
->s_proto
);
327 memcpy(buffer
, s
->s_proto
, len
);
332 for (char **q
= s
->s_aliases
; size
> 0 && *q
!= 0; q
++){
336 memcpy(buffer
, *q
, len
);
346 struct servent
*wxGetservbyname_r(const char *port
, const char *protocol
,
347 struct servent
*serv
, void *buffer
, int size
)
349 struct servent
*se
= NULL
;
350 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
351 if (getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
, &se
))
353 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
354 se
= getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
);
355 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
356 if (getservbyname_r(port
, protocol
, serv
, (struct servent_data
*) buffer
))
360 #elif defined(HAVE_GETSERVBYNAME)
362 static wxMutex servLock
;
363 wxMutexLocker
locker(servLock
);
365 se
= getservbyname(port
, protocol
);
367 se
= deepCopyServent(serv
, se
, (char*)buffer
, size
);
372 /* debugging helpers */
373 #ifdef __GSOCKET_DEBUG__
374 # define GSocket_Debug(args) printf args
376 # define GSocket_Debug(args)
377 #endif /* __GSOCKET_DEBUG__ */
379 /* Table of GUI-related functions. We must call them indirectly because
380 * of wxBase and GUI separation: */
382 static GSocketGUIFunctionsTable
*gs_gui_functions
;
384 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
387 virtual bool OnInit();
388 virtual void OnExit();
389 virtual bool CanUseEventLoop();
390 virtual bool Init_Socket(GSocket
*socket
);
391 virtual void Destroy_Socket(GSocket
*socket
);
392 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
393 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
394 virtual void Enable_Events(GSocket
*socket
);
395 virtual void Disable_Events(GSocket
*socket
);
398 bool GSocketGUIFunctionsTableNull::OnInit()
400 void GSocketGUIFunctionsTableNull::OnExit()
402 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
404 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
406 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
408 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
410 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
412 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
414 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
416 /* Global initialisers */
418 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
420 gs_gui_functions
= guifunc
;
423 int GSocket_Init(void)
425 if (!gs_gui_functions
)
427 static GSocketGUIFunctionsTableNull table
;
428 gs_gui_functions
= &table
;
430 if ( !gs_gui_functions
->OnInit() )
435 void GSocket_Cleanup(void)
437 if (gs_gui_functions
)
439 gs_gui_functions
->OnExit();
443 /* Constructors / Destructors for GSocket */
449 m_fd
= INVALID_SOCKET
;
450 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
457 m_error
= GSOCK_NOERROR
;
460 m_gui_dependent
= NULL
;
461 m_non_blocking
= false;
463 m_timeout
= 10*60*1000;
464 /* 10 minutes * 60 sec * 1000 millisec */
465 m_establishing
= false;
467 assert(gs_gui_functions
);
468 /* Per-socket GUI-specific initialization */
469 m_ok
= gs_gui_functions
->Init_Socket(this);
472 void GSocket::Close()
474 gs_gui_functions
->Disable_Events(this);
475 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
476 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
479 m_fd
= INVALID_SOCKET
;
486 /* Check that the socket is really shutdowned */
487 if (m_fd
!= INVALID_SOCKET
)
490 /* Per-socket GUI-specific cleanup */
491 gs_gui_functions
->Destroy_Socket(this);
493 /* Destroy private addresses */
495 GAddress_destroy(m_local
);
498 GAddress_destroy(m_peer
);
502 * Disallow further read/write operations on this socket, close
503 * the fd and disable all callbacks.
505 void GSocket::Shutdown()
511 /* Don't allow events to fire after socket has been closed */
512 gs_gui_functions
->Disable_Events(this);
514 /* If socket has been created, shutdown it */
515 if (m_fd
!= INVALID_SOCKET
)
521 /* Disable GUI callbacks */
522 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
523 m_cbacks
[evt
] = NULL
;
525 m_detected
= GSOCK_LOST_FLAG
;
528 /* Address handling */
534 * Set or get the local or peer address for this socket. The 'set'
535 * functions return GSOCK_NOERROR on success, an error code otherwise.
536 * The 'get' functions return a pointer to a GAddress object on success,
537 * or NULL otherwise, in which case they set the error code of the
538 * corresponding GSocket.
541 * GSOCK_INVSOCK - the socket is not valid.
542 * GSOCK_INVADDR - the address is not valid.
544 GSocketError
GSocket::SetLocal(GAddress
*address
)
548 /* the socket must be initialized, or it must be a server */
549 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
551 m_error
= GSOCK_INVSOCK
;
552 return GSOCK_INVSOCK
;
556 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
558 m_error
= GSOCK_INVADDR
;
559 return GSOCK_INVADDR
;
563 GAddress_destroy(m_local
);
565 m_local
= GAddress_copy(address
);
567 return GSOCK_NOERROR
;
570 GSocketError
GSocket::SetPeer(GAddress
*address
)
575 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
577 m_error
= GSOCK_INVADDR
;
578 return GSOCK_INVADDR
;
582 GAddress_destroy(m_peer
);
584 m_peer
= GAddress_copy(address
);
586 return GSOCK_NOERROR
;
589 GAddress
*GSocket::GetLocal()
592 struct sockaddr addr
;
593 WX_SOCKLEN_T size
= sizeof(addr
);
598 /* try to get it from the m_local var first */
600 return GAddress_copy(m_local
);
602 /* else, if the socket is initialized, try getsockname */
603 if (m_fd
== INVALID_SOCKET
)
605 m_error
= GSOCK_INVSOCK
;
609 if (getsockname(m_fd
, &addr
, (WX_SOCKLEN_T
*) &size
) < 0)
611 m_error
= GSOCK_IOERR
;
615 /* got a valid address from getsockname, create a GAddress object */
616 address
= GAddress_new();
619 m_error
= GSOCK_MEMERR
;
623 err
= _GAddress_translate_from(address
, &addr
, size
);
624 if (err
!= GSOCK_NOERROR
)
626 GAddress_destroy(address
);
634 GAddress
*GSocket::GetPeer()
638 /* try to get it from the m_peer var */
640 return GAddress_copy(m_peer
);
645 /* Server specific parts */
647 /* GSocket_SetServer:
648 * Sets up this socket as a server. The local address must have been
649 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
650 * Returns GSOCK_NOERROR on success, one of the following otherwise:
653 * GSOCK_INVSOCK - the socket is in use.
654 * GSOCK_INVADDR - the local address has not been set.
655 * GSOCK_IOERR - low-level error.
657 GSocketError
GSocket::SetServer()
663 /* must not be in use */
664 if (m_fd
!= INVALID_SOCKET
)
666 m_error
= GSOCK_INVSOCK
;
667 return GSOCK_INVSOCK
;
670 /* the local addr must have been set */
673 m_error
= GSOCK_INVADDR
;
674 return GSOCK_INVADDR
;
677 /* Initialize all fields */
681 /* Create the socket */
682 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
684 if (m_fd
== INVALID_SOCKET
)
686 m_error
= GSOCK_IOERR
;
690 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
692 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
695 ioctl(m_fd
, FIONBIO
, &arg
);
696 gs_gui_functions
->Enable_Events(this);
698 /* allow a socket to re-bind if the socket is in the TIME_WAIT
699 state after being previously closed.
702 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
704 /* Bind to the local address,
705 * retrieve the actual address bound,
706 * and listen up to 5 connections.
708 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
711 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
712 (listen(m_fd
, 5) != 0))
715 m_error
= GSOCK_IOERR
;
719 return GSOCK_NOERROR
;
722 /* GSocket_WaitConnection:
723 * Waits for an incoming client connection. Returns a pointer to
724 * a GSocket object, or NULL if there was an error, in which case
725 * the last error field will be updated for the calling GSocket.
727 * Error codes (set in the calling GSocket)
728 * GSOCK_INVSOCK - the socket is not valid or not a server.
729 * GSOCK_TIMEDOUT - timeout, no incoming connections.
730 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
731 * GSOCK_MEMERR - couldn't allocate memory.
732 * GSOCK_IOERR - low-level error.
734 GSocket
*GSocket::WaitConnection()
736 struct sockaddr from
;
737 WX_SOCKLEN_T fromlen
= sizeof(from
);
744 /* If the socket has already been created, we exit immediately */
745 if (m_fd
== INVALID_SOCKET
|| !m_server
)
747 m_error
= GSOCK_INVSOCK
;
751 /* Create a GSocket object for the new connection */
752 connection
= GSocket_new();
756 m_error
= GSOCK_MEMERR
;
760 /* Wait for a connection (with timeout) */
761 if (Input_Timeout() == GSOCK_TIMEDOUT
)
764 /* m_error set by _GSocket_Input_Timeout */
768 connection
->m_fd
= accept(m_fd
, &from
, (WX_SOCKLEN_T
*) &fromlen
);
770 /* Reenable CONNECTION events */
771 Enable(GSOCK_CONNECTION
);
773 if (connection
->m_fd
== INVALID_SOCKET
)
775 if (errno
== EWOULDBLOCK
)
776 m_error
= GSOCK_WOULDBLOCK
;
778 m_error
= GSOCK_IOERR
;
784 /* Initialize all fields */
785 connection
->m_server
= false;
786 connection
->m_stream
= true;
788 /* Setup the peer address field */
789 connection
->m_peer
= GAddress_new();
790 if (!connection
->m_peer
)
793 m_error
= GSOCK_MEMERR
;
797 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
798 if (err
!= GSOCK_NOERROR
)
805 #if defined(__EMX__) || defined(__VISAGECPP__)
806 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
808 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
810 gs_gui_functions
->Enable_Events(connection
);
815 bool GSocket::SetReusable()
817 /* socket must not be null, and must not be in use/already bound */
818 if (this && m_fd
== INVALID_SOCKET
)
828 /* Client specific parts */
831 * For stream (connection oriented) sockets, GSocket_Connect() tries
832 * to establish a client connection to a server using the peer address
833 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
834 * connection has been successfully established, or one of the error
835 * codes listed below. Note that for nonblocking sockets, a return
836 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
837 * request can be completed later; you should use GSocket_Select()
838 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
839 * corresponding asynchronous events.
841 * For datagram (non connection oriented) sockets, GSocket_Connect()
842 * just sets the peer address established with GSocket_SetPeer() as
843 * default destination.
846 * GSOCK_INVSOCK - the socket is in use or not valid.
847 * GSOCK_INVADDR - the peer address has not been established.
848 * GSOCK_TIMEDOUT - timeout, the connection failed.
849 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
850 * GSOCK_MEMERR - couldn't allocate memory.
851 * GSOCK_IOERR - low-level error.
853 GSocketError
GSocket::Connect(GSocketStream stream
)
860 /* Enable CONNECTION events (needed for nonblocking connections) */
861 Enable(GSOCK_CONNECTION
);
863 if (m_fd
!= INVALID_SOCKET
)
865 m_error
= GSOCK_INVSOCK
;
866 return GSOCK_INVSOCK
;
871 m_error
= GSOCK_INVADDR
;
872 return GSOCK_INVADDR
;
875 /* Streamed or dgram socket? */
876 m_stream
= (stream
== GSOCK_STREAMED
);
878 m_establishing
= false;
880 /* Create the socket */
881 m_fd
= socket(m_peer
->m_realfamily
,
882 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
884 if (m_fd
== INVALID_SOCKET
)
886 m_error
= GSOCK_IOERR
;
890 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
892 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
895 #if defined(__EMX__) || defined(__VISAGECPP__)
896 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
898 ioctl(m_fd
, FIONBIO
, &arg
);
901 /* Connect it to the peer address, with a timeout (see below) */
902 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
904 /* We only call Enable_Events if we know we aren't shutting down the socket.
905 * NB: Enable_Events needs to be called whether the socket is blocking or
906 * non-blocking, it just shouldn't be called prior to knowing there is a
907 * connection _if_ blocking sockets are being used.
908 * If connect above returns 0, we are already connected and need to make the
909 * call to Enable_Events now.
912 if (m_non_blocking
|| ret
== 0)
913 gs_gui_functions
->Enable_Events(this);
919 /* If connect failed with EINPROGRESS and the GSocket object
920 * is in blocking mode, we select() for the specified timeout
921 * checking for writability to see if the connection request
924 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
926 if (Output_Timeout() == GSOCK_TIMEDOUT
)
929 /* m_error is set in _GSocket_Output_Timeout */
930 return GSOCK_TIMEDOUT
;
935 SOCKOPTLEN_T len
= sizeof(error
);
937 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
939 gs_gui_functions
->Enable_Events(this);
942 return GSOCK_NOERROR
;
946 /* If connect failed with EINPROGRESS and the GSocket object
947 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
948 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
949 * this way if the connection completes, a GSOCK_CONNECTION
950 * event will be generated, if enabled.
952 if ((err
== EINPROGRESS
) && (m_non_blocking
))
954 m_establishing
= true;
955 m_error
= GSOCK_WOULDBLOCK
;
956 return GSOCK_WOULDBLOCK
;
959 /* If connect failed with an error other than EINPROGRESS,
960 * then the call to GSocket_Connect has failed.
963 m_error
= GSOCK_IOERR
;
968 return GSOCK_NOERROR
;
971 /* Datagram sockets */
973 /* GSocket_SetNonOriented:
974 * Sets up this socket as a non-connection oriented (datagram) socket.
975 * Before using this function, the local address must have been set
976 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
977 * on success, or one of the following otherwise.
980 * GSOCK_INVSOCK - the socket is in use.
981 * GSOCK_INVADDR - the local address has not been set.
982 * GSOCK_IOERR - low-level error.
984 GSocketError
GSocket::SetNonOriented()
990 if (m_fd
!= INVALID_SOCKET
)
992 m_error
= GSOCK_INVSOCK
;
993 return GSOCK_INVSOCK
;
998 m_error
= GSOCK_INVADDR
;
999 return GSOCK_INVADDR
;
1002 /* Initialize all fields */
1006 /* Create the socket */
1007 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
1009 if (m_fd
== INVALID_SOCKET
)
1011 m_error
= GSOCK_IOERR
;
1014 #if defined(__EMX__) || defined(__VISAGECPP__)
1015 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
1017 ioctl(m_fd
, FIONBIO
, &arg
);
1019 gs_gui_functions
->Enable_Events(this);
1021 /* Bind to the local address,
1022 * and retrieve the actual address bound.
1024 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
1027 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0))
1030 m_error
= GSOCK_IOERR
;
1034 return GSOCK_NOERROR
;
1039 /* Like recv(), send(), ... */
1040 int GSocket::Read(char *buffer
, int size
)
1046 if (m_fd
== INVALID_SOCKET
|| m_server
)
1048 m_error
= GSOCK_INVSOCK
;
1052 /* Disable events during query of socket status */
1053 Disable(GSOCK_INPUT
);
1055 /* If the socket is blocking, wait for data (with a timeout) */
1056 if (Input_Timeout() == GSOCK_TIMEDOUT
) {
1057 m_error
= GSOCK_TIMEDOUT
;
1058 /* Don't return here immediately, otherwise socket events would not be
1066 ret
= Recv_Stream(buffer
, size
);
1068 ret
= Recv_Dgram(buffer
, size
);
1070 /* If recv returned zero, then the connection is lost, and errno is not set.
1071 * Otherwise, recv has returned an error (-1), in which case we have lost the
1072 * socket only if errno does _not_ indicate that there may be more data to read.
1075 m_error
= GSOCK_IOERR
;
1078 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1079 m_error
= GSOCK_WOULDBLOCK
;
1081 m_error
= GSOCK_IOERR
;
1085 /* Enable events again now that we are done processing */
1086 Enable(GSOCK_INPUT
);
1091 int GSocket::Write(const char *buffer
, int size
)
1097 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
1099 if (m_fd
== INVALID_SOCKET
|| m_server
)
1101 m_error
= GSOCK_INVSOCK
;
1105 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
1107 /* If the socket is blocking, wait for writability (with a timeout) */
1108 if (Output_Timeout() == GSOCK_TIMEDOUT
)
1111 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
1113 /* Write the data */
1115 ret
= Send_Stream(buffer
, size
);
1117 ret
= Send_Dgram(buffer
, size
);
1119 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
1123 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1125 m_error
= GSOCK_WOULDBLOCK
;
1126 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1130 m_error
= GSOCK_IOERR
;
1131 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1134 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1135 * in MSW). Once the first OUTPUT event is received, users can assume
1136 * that the socket is writable until a read operation fails. Only then
1137 * will further OUTPUT events be posted.
1139 Enable(GSOCK_OUTPUT
);
1144 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
1150 * Polls the socket to determine its status. This function will
1151 * check for the events specified in the 'flags' parameter, and
1152 * it will return a mask indicating which operations can be
1153 * performed. This function won't block, regardless of the
1154 * mode (blocking | nonblocking) of the socket.
1156 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
1158 if (!gs_gui_functions
->CanUseEventLoop())
1161 GSocketEventFlags result
= 0;
1170 return (GSOCK_LOST_FLAG
& flags
);
1172 /* Do not use a static struct, Linux can garble it */
1173 tv
.tv_sec
= m_timeout
/ 1000;
1174 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1176 wxFD_ZERO(&readfds
);
1177 wxFD_ZERO(&writefds
);
1178 wxFD_ZERO(&exceptfds
);
1179 wxFD_SET(m_fd
, &readfds
);
1180 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
1181 wxFD_SET(m_fd
, &writefds
);
1182 wxFD_SET(m_fd
, &exceptfds
);
1184 /* Check 'sticky' CONNECTION flag first */
1185 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
1187 /* If we have already detected a LOST event, then don't try
1188 * to do any further processing.
1190 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1192 m_establishing
= false;
1194 return (GSOCK_LOST_FLAG
& flags
);
1197 /* Try select now */
1198 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
1200 /* What to do here? */
1201 return (result
& flags
);
1204 /* Check for readability */
1205 if (wxFD_ISSET(m_fd
, &readfds
))
1209 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1213 result
|= GSOCK_INPUT_FLAG
;
1217 if (m_server
&& m_stream
)
1219 result
|= GSOCK_CONNECTION_FLAG
;
1220 m_detected
|= GSOCK_CONNECTION_FLAG
;
1222 /* If recv returned zero, then the connection is lost, and errno is not set.
1223 * Otherwise, recv has returned an error (-1), in which case we have lost the
1224 * socket only if errno does _not_ indicate that there may be more data to read.
1226 else if (num
== 0 ||
1227 (errno
!= EWOULDBLOCK
) && (errno
!= EAGAIN
) && (errno
!= EINTR
))
1229 m_detected
= GSOCK_LOST_FLAG
;
1230 m_establishing
= false;
1232 /* LOST event: Abort any further processing */
1233 return (GSOCK_LOST_FLAG
& flags
);
1238 /* Check for writability */
1239 if (wxFD_ISSET(m_fd
, &writefds
))
1241 if (m_establishing
&& !m_server
)
1244 SOCKOPTLEN_T len
= sizeof(error
);
1246 m_establishing
= false;
1248 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1252 m_detected
= GSOCK_LOST_FLAG
;
1254 /* LOST event: Abort any further processing */
1255 return (GSOCK_LOST_FLAG
& flags
);
1259 result
|= GSOCK_CONNECTION_FLAG
;
1260 m_detected
|= GSOCK_CONNECTION_FLAG
;
1265 result
|= GSOCK_OUTPUT_FLAG
;
1269 /* Check for exceptions and errors (is this useful in Unices?) */
1270 if (wxFD_ISSET(m_fd
, &exceptfds
))
1272 m_establishing
= false;
1273 m_detected
= GSOCK_LOST_FLAG
;
1275 /* LOST event: Abort any further processing */
1276 return (GSOCK_LOST_FLAG
& flags
);
1279 return (result
& flags
);
1285 return flags
& m_detected
;
1291 /* GSocket_SetNonBlocking:
1292 * Sets the socket to non-blocking mode. All IO calls will return
1295 void GSocket::SetNonBlocking(bool non_block
)
1299 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1301 m_non_blocking
= non_block
;
1304 /* GSocket_SetTimeout:
1305 * Sets the timeout for blocking calls. Time is expressed in
1308 void GSocket::SetTimeout(unsigned long millisec
)
1312 m_timeout
= millisec
;
1315 /* GSocket_GetError:
1316 * Returns the last error occurred for this socket. Note that successful
1317 * operations do not clear this back to GSOCK_NOERROR, so use it only
1320 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1330 * There is data to be read in the input buffer. If, after a read
1331 * operation, there is still data available, the callback function will
1334 * The socket is available for writing. That is, the next write call
1335 * won't block. This event is generated only once, when the connection is
1336 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1337 * when the output buffer empties again. This means that the app should
1338 * assume that it can write since the first OUTPUT event, and no more
1339 * OUTPUT events will be generated unless an error occurs.
1341 * Connection successfully established, for client sockets, or incoming
1342 * client connection, for server sockets. Wait for this event (also watch
1343 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1345 * The connection is lost (or a connection request failed); this could
1346 * be due to a failure, or due to the peer closing it gracefully.
1349 /* GSocket_SetCallback:
1350 * Enables the callbacks specified by 'flags'. Note that 'flags'
1351 * may be a combination of flags OR'ed toghether, so the same
1352 * callback function can be made to accept different events.
1353 * The callback function must have the following prototype:
1355 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1357 void GSocket::SetCallback(GSocketEventFlags flags
,
1358 GSocketCallback callback
, char *cdata
)
1364 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1366 if ((flags
& (1 << count
)) != 0)
1368 m_cbacks
[count
] = callback
;
1369 m_data
[count
] = cdata
;
1374 /* GSocket_UnsetCallback:
1375 * Disables all callbacks specified by 'flags', which may be a
1376 * combination of flags OR'ed toghether.
1378 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1384 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1386 if ((flags
& (1 << count
)) != 0)
1388 m_cbacks
[count
] = NULL
;
1389 m_data
[count
] = NULL
;
1394 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1395 void *optval
, int *optlen
)
1397 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1398 return GSOCK_NOERROR
;
1400 return GSOCK_OPTERR
;
1403 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1404 const void *optval
, int optlen
)
1406 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1407 return GSOCK_NOERROR
;
1409 return GSOCK_OPTERR
;
1412 #define CALL_CALLBACK(socket, event) { \
1413 socket->Disable(event); \
1414 if (socket->m_cbacks[event]) \
1415 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1419 void GSocket::Enable(GSocketEvent event
)
1421 m_detected
&= ~(1 << event
);
1422 gs_gui_functions
->Install_Callback(this, event
);
1425 void GSocket::Disable(GSocketEvent event
)
1427 m_detected
|= (1 << event
);
1428 gs_gui_functions
->Uninstall_Callback(this, event
);
1431 /* _GSocket_Input_Timeout:
1432 * For blocking sockets, wait until data is available or
1433 * until timeout ellapses.
1435 GSocketError
GSocket::Input_Timeout()
1441 /* Linux select() will overwrite the struct on return */
1442 tv
.tv_sec
= (m_timeout
/ 1000);
1443 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1445 if (!m_non_blocking
)
1447 wxFD_ZERO(&readfds
);
1448 wxFD_SET(m_fd
, &readfds
);
1449 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1452 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1453 m_error
= GSOCK_TIMEDOUT
;
1454 return GSOCK_TIMEDOUT
;
1459 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1460 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1461 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1462 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1463 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1464 m_error
= GSOCK_TIMEDOUT
;
1465 return GSOCK_TIMEDOUT
;
1469 return GSOCK_NOERROR
;
1472 /* _GSocket_Output_Timeout:
1473 * For blocking sockets, wait until data can be sent without
1474 * blocking or until timeout ellapses.
1476 GSocketError
GSocket::Output_Timeout()
1482 /* Linux select() will overwrite the struct on return */
1483 tv
.tv_sec
= (m_timeout
/ 1000);
1484 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1486 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1488 if (!m_non_blocking
)
1490 wxFD_ZERO(&writefds
);
1491 wxFD_SET(m_fd
, &writefds
);
1492 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1495 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1496 m_error
= GSOCK_TIMEDOUT
;
1497 return GSOCK_TIMEDOUT
;
1502 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1503 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1504 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1505 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1506 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1507 m_error
= GSOCK_TIMEDOUT
;
1508 return GSOCK_TIMEDOUT
;
1511 if ( ! wxFD_ISSET(m_fd
, &writefds
) )
1513 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1517 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1522 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1525 return GSOCK_NOERROR
;
1528 int GSocket::Recv_Stream(char *buffer
, int size
)
1533 ret
= recv(m_fd
, buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1535 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1540 int GSocket::Recv_Dgram(char *buffer
, int size
)
1542 struct sockaddr from
;
1543 WX_SOCKLEN_T fromlen
= sizeof(from
);
1547 fromlen
= sizeof(from
);
1551 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (WX_SOCKLEN_T
*) &fromlen
);
1553 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1558 /* Translate a system address into a GSocket address */
1561 m_peer
= GAddress_new();
1564 m_error
= GSOCK_MEMERR
;
1569 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1570 if (err
!= GSOCK_NOERROR
)
1572 GAddress_destroy(m_peer
);
1581 int GSocket::Send_Stream(const char *buffer
, int size
)
1589 ret
= send(m_fd
, (char *)buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1591 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1598 int GSocket::Send_Dgram(const char *buffer
, int size
)
1600 struct sockaddr
*addr
;
1606 m_error
= GSOCK_INVADDR
;
1610 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1611 if (err
!= GSOCK_NOERROR
)
1621 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1623 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1627 /* Frees memory allocated from _GAddress_translate_to */
1633 void GSocket::Detected_Read()
1637 /* Safeguard against straggling call to Detected_Read */
1638 if (m_fd
== INVALID_SOCKET
)
1643 /* If we have already detected a LOST event, then don't try
1644 * to do any further processing.
1646 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1648 m_establishing
= false;
1650 CALL_CALLBACK(this, GSOCK_LOST
);
1655 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1659 CALL_CALLBACK(this, GSOCK_INPUT
);
1663 if (m_server
&& m_stream
)
1665 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1669 /* Do not throw a lost event in cases where the socket isn't really lost */
1670 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
) || (errno
== EINTR
))
1672 CALL_CALLBACK(this, GSOCK_INPUT
);
1676 CALL_CALLBACK(this, GSOCK_LOST
);
1683 void GSocket::Detected_Write()
1685 /* If we have already detected a LOST event, then don't try
1686 * to do any further processing.
1688 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1690 m_establishing
= false;
1692 CALL_CALLBACK(this, GSOCK_LOST
);
1697 if (m_establishing
&& !m_server
)
1700 SOCKOPTLEN_T len
= sizeof(error
);
1702 m_establishing
= false;
1704 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1708 CALL_CALLBACK(this, GSOCK_LOST
);
1713 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1714 /* We have to fire this event by hand because CONNECTION (for clients)
1715 * and OUTPUT are internally the same and we just disabled CONNECTION
1716 * events with the above macro.
1718 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1723 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1727 /* Compatibility functions for GSocket */
1728 GSocket
*GSocket_new(void)
1730 GSocket
*newsocket
= new GSocket();
1731 if (newsocket
->IsOk())
1740 * -------------------------------------------------------------------------
1742 * -------------------------------------------------------------------------
1745 /* CHECK_ADDRESS verifies that the current address family is either
1746 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1747 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1748 * an appropiate error code.
1750 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1752 #define CHECK_ADDRESS(address, family) \
1754 if (address->m_family == GSOCK_NOFAMILY) \
1755 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1756 return address->m_error; \
1757 if (address->m_family != GSOCK_##family) \
1759 address->m_error = GSOCK_INVADDR; \
1760 return GSOCK_INVADDR; \
1764 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1766 if (address->m_family == GSOCK_NOFAMILY) \
1767 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1769 if (address->m_family != GSOCK_##family) \
1771 address->m_error = GSOCK_INVADDR; \
1777 GAddress
*GAddress_new(void)
1781 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1784 address
->m_family
= GSOCK_NOFAMILY
;
1785 address
->m_addr
= NULL
;
1791 GAddress
*GAddress_copy(GAddress
*address
)
1795 assert(address
!= NULL
);
1797 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1800 memcpy(addr2
, address
, sizeof(GAddress
));
1802 if (address
->m_addr
&& address
->m_len
> 0)
1804 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1805 if (addr2
->m_addr
== NULL
)
1810 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1816 void GAddress_destroy(GAddress
*address
)
1818 assert(address
!= NULL
);
1820 if (address
->m_addr
)
1821 free(address
->m_addr
);
1826 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1828 assert(address
!= NULL
);
1830 address
->m_family
= type
;
1833 GAddressType
GAddress_GetFamily(GAddress
*address
)
1835 assert(address
!= NULL
);
1837 return address
->m_family
;
1840 GSocketError
_GAddress_translate_from(GAddress
*address
,
1841 struct sockaddr
*addr
, int len
)
1843 address
->m_realfamily
= addr
->sa_family
;
1844 switch (addr
->sa_family
)
1847 address
->m_family
= GSOCK_INET
;
1850 address
->m_family
= GSOCK_UNIX
;
1854 address
->m_family
= GSOCK_INET6
;
1859 address
->m_error
= GSOCK_INVOP
;
1864 if (address
->m_addr
)
1865 free(address
->m_addr
);
1867 address
->m_len
= len
;
1868 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1870 if (address
->m_addr
== NULL
)
1872 address
->m_error
= GSOCK_MEMERR
;
1873 return GSOCK_MEMERR
;
1876 memcpy(address
->m_addr
, addr
, len
);
1878 return GSOCK_NOERROR
;
1881 GSocketError
_GAddress_translate_to(GAddress
*address
,
1882 struct sockaddr
**addr
, int *len
)
1884 if (!address
->m_addr
)
1886 address
->m_error
= GSOCK_INVADDR
;
1887 return GSOCK_INVADDR
;
1890 *len
= address
->m_len
;
1891 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1894 address
->m_error
= GSOCK_MEMERR
;
1895 return GSOCK_MEMERR
;
1898 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1899 return GSOCK_NOERROR
;
1903 * -------------------------------------------------------------------------
1904 * Internet address family
1905 * -------------------------------------------------------------------------
1908 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1910 address
->m_len
= sizeof(struct sockaddr_in
);
1911 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1912 if (address
->m_addr
== NULL
)
1914 address
->m_error
= GSOCK_MEMERR
;
1915 return GSOCK_MEMERR
;
1918 address
->m_family
= GSOCK_INET
;
1919 address
->m_realfamily
= PF_INET
;
1920 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1921 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1923 return GSOCK_NOERROR
;
1926 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1929 struct in_addr
*addr
;
1931 assert(address
!= NULL
);
1933 CHECK_ADDRESS(address
, INET
);
1935 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1937 /* If it is a numeric host name, convert it now */
1938 #if defined(HAVE_INET_ATON)
1939 if (inet_aton(hostname
, addr
) == 0)
1941 #elif defined(HAVE_INET_ADDR)
1942 if ( (addr
->s_addr
= inet_addr(hostname
)) == (unsigned)-1 )
1945 /* Use gethostbyname by default */
1947 int val
= 1; /* VA doesn't like constants in conditional expressions */
1952 struct in_addr
*array_addr
;
1954 /* It is a real name, we solve it */
1956 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
1957 struct hostent_data buffer
;
1962 he
= wxGethostbyname_r(hostname
, &h
, (void*)&buffer
, sizeof(buffer
), &err
);
1965 /* Reset to invalid address */
1966 addr
->s_addr
= INADDR_NONE
;
1967 address
->m_error
= GSOCK_NOHOST
;
1968 return GSOCK_NOHOST
;
1971 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1972 addr
->s_addr
= array_addr
[0].s_addr
;
1975 return GSOCK_NOERROR
;
1978 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1980 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1983 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1984 unsigned long hostaddr
)
1986 struct in_addr
*addr
;
1988 assert(address
!= NULL
);
1990 CHECK_ADDRESS(address
, INET
);
1992 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1993 addr
->s_addr
= htonl(hostaddr
);
1995 return GSOCK_NOERROR
;
1998 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1999 const char *protocol
)
2002 struct sockaddr_in
*addr
;
2004 assert(address
!= NULL
);
2005 CHECK_ADDRESS(address
, INET
);
2009 address
->m_error
= GSOCK_INVPORT
;
2010 return GSOCK_INVPORT
;
2013 #if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2014 struct servent_data buffer
;
2018 struct servent serv
;
2019 se
= wxGetservbyname_r(port
, protocol
, &serv
,
2020 (void*)&buffer
, sizeof(buffer
));
2023 /* the cast to int suppresses compiler warnings about subscript having the
2025 if (isdigit((int)port
[0]))
2029 port_int
= atoi(port
);
2030 addr
= (struct sockaddr_in
*)address
->m_addr
;
2031 addr
->sin_port
= htons(port_int
);
2032 return GSOCK_NOERROR
;
2035 address
->m_error
= GSOCK_INVPORT
;
2036 return GSOCK_INVPORT
;
2039 addr
= (struct sockaddr_in
*)address
->m_addr
;
2040 addr
->sin_port
= se
->s_port
;
2042 return GSOCK_NOERROR
;
2045 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
2047 struct sockaddr_in
*addr
;
2049 assert(address
!= NULL
);
2050 CHECK_ADDRESS(address
, INET
);
2052 addr
= (struct sockaddr_in
*)address
->m_addr
;
2053 addr
->sin_port
= htons(port
);
2055 return GSOCK_NOERROR
;
2058 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
2062 struct sockaddr_in
*addr
;
2064 assert(address
!= NULL
);
2065 CHECK_ADDRESS(address
, INET
);
2067 addr
= (struct sockaddr_in
*)address
->m_addr
;
2068 addr_buf
= (char *)&(addr
->sin_addr
);
2070 struct hostent temphost
;
2071 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2072 struct hostent_data buffer
;
2077 he
= wxGethostbyaddr_r(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
, &temphost
,
2078 (void*)&buffer
, sizeof(buffer
), &err
);
2081 address
->m_error
= GSOCK_NOHOST
;
2082 return GSOCK_NOHOST
;
2085 strncpy(hostname
, he
->h_name
, sbuf
);
2087 return GSOCK_NOERROR
;
2090 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
2092 struct sockaddr_in
*addr
;
2094 assert(address
!= NULL
);
2095 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
2097 addr
= (struct sockaddr_in
*)address
->m_addr
;
2099 return ntohl(addr
->sin_addr
.s_addr
);
2102 unsigned short GAddress_INET_GetPort(GAddress
*address
)
2104 struct sockaddr_in
*addr
;
2106 assert(address
!= NULL
);
2107 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
2109 addr
= (struct sockaddr_in
*)address
->m_addr
;
2110 return ntohs(addr
->sin_port
);
2114 * -------------------------------------------------------------------------
2115 * Unix address family
2116 * -------------------------------------------------------------------------
2119 #ifndef __VISAGECPP__
2120 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
2122 address
->m_len
= sizeof(struct sockaddr_un
);
2123 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
2124 if (address
->m_addr
== NULL
)
2126 address
->m_error
= GSOCK_MEMERR
;
2127 return GSOCK_MEMERR
;
2130 address
->m_family
= GSOCK_UNIX
;
2131 address
->m_realfamily
= PF_UNIX
;
2132 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
2133 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
2135 return GSOCK_NOERROR
;
2138 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2140 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
2142 struct sockaddr_un
*addr
;
2144 assert(address
!= NULL
);
2146 CHECK_ADDRESS(address
, UNIX
);
2148 addr
= ((struct sockaddr_un
*)address
->m_addr
);
2149 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
2150 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
2152 return GSOCK_NOERROR
;
2155 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
2157 struct sockaddr_un
*addr
;
2159 assert(address
!= NULL
);
2160 CHECK_ADDRESS(address
, UNIX
);
2162 addr
= (struct sockaddr_un
*)address
->m_addr
;
2164 strncpy(path
, addr
->sun_path
, sbuf
);
2166 return GSOCK_NOERROR
;
2168 #endif /* !defined(__VISAGECPP__) */
2169 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */