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 #include <sys/ioctl.h>
42 #ifdef HAVE_SYS_SELECT_H
43 # include <sys/select.h>
50 u_char sun_len
; /* sockaddr len including null */
51 u_char sun_family
; /* AF_UNIX */
52 char sun_path
[108]; /* path name (gag) */
55 #include <sys/socket.h>
61 #include <netinet/in.h>
62 #include <arpa/inet.h>
69 #include <machine/endian.h>
75 #define EBADF SOCEBADF
81 #include <sys/socket.h>
82 #include <sys/ioctl.h>
83 #include <sys/select.h>
85 #define close(a) soclose(a)
86 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
87 int _System
bsdselect(int,
92 int _System
soclose(int);
96 #include <sys/select.h>
104 # include <sys/filio.h>
107 # include <bstring.h>
110 # include <strings.h>
117 # define WX_SOCKLEN_T unsigned int
121 # define WX_SOCKLEN_T socklen_t
123 # elif defined(__WXMAC__)
124 # define WX_SOCKLEN_T socklen_t
126 # define WX_SOCKLEN_T int
130 #endif /* SOCKLEN_T */
133 #define SOCKOPTLEN_T WX_SOCKLEN_T
137 * MSW defines this, Unices don't.
139 #ifndef INVALID_SOCKET
140 #define INVALID_SOCKET -1
143 /* UnixWare reportedly needs this for FIONBIO definition */
145 #include <sys/filio.h>
149 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
150 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
153 #define INADDR_NONE INADDR_BROADCAST
156 #if defined(__VISAGECPP__) || defined(__WATCOMC__)
158 #define MASK_SIGNAL() {
159 #define UNMASK_SIGNAL() }
162 extern "C" { typedef void (*wxSigHandler
)(int); }
164 #define MASK_SIGNAL() \
166 wxSigHandler old_handler = signal(SIGPIPE, SIG_IGN);
168 #define UNMASK_SIGNAL() \
169 signal(SIGPIPE, old_handler); \
174 /* If a SIGPIPE is issued by a socket call on a remotely closed socket,
175 the program will "crash" unless it explicitly handles the SIGPIPE.
176 By using MSG_NOSIGNAL, the SIGPIPE is suppressed. Later, we will
177 use SO_NOSIGPIPE (if available), the BSD equivalent. */
179 # define GSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
180 #else /* MSG_NOSIGNAL not available (FreeBSD including OS X) */
181 # define GSOCKET_MSG_NOSIGNAL 0
182 #endif /* MSG_NOSIGNAL */
184 #ifndef __GSOCKET_STANDALONE__
185 # include "wx/unix/gsockunx.h"
186 # include "wx/unix/private.h"
187 # include "wx/gsocket.h"
188 #if wxUSE_THREADS && (defined(HAVE_GETHOSTBYNAME) || defined(HAVE_GETSERVBYNAME))
189 # include "wx/thread.h"
192 # include "gsockunx.h"
193 # include "gsocket.h"
197 #endif /* __GSOCKET_STANDALONE__ */
199 #if defined(HAVE_GETHOSTBYNAME)
200 static struct hostent
* deepCopyHostent(struct hostent
*h
,
201 const struct hostent
*he
,
202 char *buffer
, int size
, int *err
)
204 /* copy old structure */
205 memcpy(h
, he
, sizeof(struct hostent
));
208 int len
= strlen(h
->h_name
);
214 memcpy(buffer
, h
->h_name
, len
);
218 /* track position in the buffer */
221 /* reuse len to store address length */
224 /* ensure pointer alignment */
225 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
226 if(misalign
< sizeof(char *))
229 /* leave space for pointer list */
230 char **p
= h
->h_addr_list
, **q
;
231 char **h_addr_list
= (char **)(buffer
+ pos
);
233 pos
+= sizeof(char *);
235 /* copy addresses and fill new pointer list */
236 for (p
= h
->h_addr_list
, q
= h_addr_list
; *p
!= 0; p
++, q
++)
238 if (size
< pos
+ len
)
243 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
244 *q
= buffer
+ pos
; /* set copied pointer to copied content */
247 *++q
= 0; /* null terminate the pointer list */
248 h
->h_addr_list
= h_addr_list
; /* copy pointer to pointers */
250 /* ensure word alignment of pointers */
251 misalign
= sizeof(char *) - pos%sizeof
(char *);
252 if(misalign
< sizeof(char *))
255 /* leave space for pointer list */
257 char **h_aliases
= (char **)(buffer
+ pos
);
259 pos
+= sizeof(char *);
261 /* copy aliases and fill new pointer list */
262 for (p
= h
->h_aliases
, q
= h_aliases
; *p
!= 0; p
++, q
++)
265 if (size
<= pos
+ len
)
270 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
271 buffer
[pos
+ len
] = '\0';
272 *q
= buffer
+ pos
; /* set copied pointer to copied content */
275 *++q
= 0; /* null terminate the pointer list */
276 h
->h_aliases
= h_aliases
; /* copy pointer to pointers */
282 #if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
283 static wxMutex nameLock
;
285 struct hostent
* wxGethostbyname_r(const char *hostname
, struct hostent
*h
,
286 void *buffer
, int size
, int *err
)
289 struct hostent
*he
= NULL
;
291 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
292 if (gethostbyname_r(hostname
, h
, (char*)buffer
, size
, &he
, err
))
294 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
295 he
= gethostbyname_r(hostname
, h
, (char*)buffer
, size
, err
);
296 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
297 if (gethostbyname_r(hostname
, h
, (struct hostent_data
*) buffer
))
304 #elif defined(HAVE_GETHOSTBYNAME)
306 wxMutexLocker
locker(nameLock
);
308 he
= gethostbyname(hostname
);
312 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
317 #if defined(HAVE_GETHOSTBYNAME) && wxUSE_THREADS
318 static wxMutex addrLock
;
320 struct hostent
* wxGethostbyaddr_r(const char *addr_buf
, int buf_size
,
321 int proto
, struct hostent
*h
,
322 void *buffer
, int size
, int *err
)
324 struct hostent
*he
= NULL
;
326 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
327 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
328 (char*)buffer
, size
, &he
, err
))
330 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
331 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, (char*)buffer
, size
, err
);
332 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
333 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
334 (struct hostent_data
*) buffer
))
341 #elif defined(HAVE_GETHOSTBYNAME)
343 wxMutexLocker
locker(addrLock
);
345 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
349 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
354 #if defined(HAVE_GETSERVBYNAME)
355 static struct servent
* deepCopyServent(struct servent
*s
,
356 const struct servent
*se
,
357 char *buffer
, int size
)
359 /* copy plain old structure */
360 memcpy(s
, se
, sizeof(struct servent
));
363 int len
= strlen(s
->s_name
);
368 memcpy(buffer
, s
->s_name
, len
);
372 /* track position in the buffer */
376 len
= strlen(s
->s_proto
);
377 if (pos
+ len
>= size
)
381 memcpy(buffer
+ pos
, s
->s_proto
, len
);
382 buffer
[pos
+ len
] = '\0';
383 s
->s_proto
= buffer
+ pos
;
385 /* track position in the buffer */
388 /* ensure pointer alignment */
389 unsigned int misalign
= sizeof(char *) - pos%sizeof
(char *);
390 if(misalign
< sizeof(char *))
393 /* leave space for pointer list */
394 char **p
= s
->s_aliases
, **q
;
395 char **s_aliases
= (char **)(buffer
+ pos
);
397 pos
+= sizeof(char *);
399 /* copy addresses and fill new pointer list */
400 for (p
= s
->s_aliases
, q
= s_aliases
; *p
!= 0; p
++, q
++){
402 if (size
<= pos
+ len
)
406 memcpy(buffer
+ pos
, *p
, len
); /* copy content */
407 buffer
[pos
+ len
] = '\0';
408 *q
= buffer
+ pos
; /* set copied pointer to copied content */
411 *++q
= 0; /* null terminate the pointer list */
412 s
->s_aliases
= s_aliases
; /* copy pointer to pointers */
417 #if defined(HAVE_GETSERVBYNAME) && wxUSE_THREADS
418 static wxMutex servLock
;
420 struct servent
*wxGetservbyname_r(const char *port
, const char *protocol
,
421 struct servent
*serv
, void *buffer
, int size
)
423 struct servent
*se
= NULL
;
424 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
425 if (getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
, &se
))
427 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
428 se
= getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
);
429 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
430 if (getservbyname_r(port
, protocol
, serv
, (struct servent_data
*) buffer
))
434 #elif defined(HAVE_GETSERVBYNAME)
436 wxMutexLocker
locker(servLock
);
438 se
= getservbyname(port
, protocol
);
440 se
= deepCopyServent(serv
, se
, (char*)buffer
, size
);
445 /* debugging helpers */
446 #ifdef __GSOCKET_DEBUG__
447 # define GSocket_Debug(args) printf args
449 # define GSocket_Debug(args)
450 #endif /* __GSOCKET_DEBUG__ */
452 /* Table of GUI-related functions. We must call them indirectly because
453 * of wxBase and GUI separation: */
455 static GSocketGUIFunctionsTable
*gs_gui_functions
;
457 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
460 virtual bool OnInit();
461 virtual void OnExit();
462 virtual bool CanUseEventLoop();
463 virtual bool Init_Socket(GSocket
*socket
);
464 virtual void Destroy_Socket(GSocket
*socket
);
465 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
466 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
467 virtual void Enable_Events(GSocket
*socket
);
468 virtual void Disable_Events(GSocket
*socket
);
471 bool GSocketGUIFunctionsTableNull::OnInit()
473 void GSocketGUIFunctionsTableNull::OnExit()
475 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
477 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
479 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
481 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
483 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
485 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
487 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
489 /* Global initialisers */
491 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
493 gs_gui_functions
= guifunc
;
496 int GSocket_Init(void)
498 if (!gs_gui_functions
)
500 static GSocketGUIFunctionsTableNull table
;
501 gs_gui_functions
= &table
;
503 if ( !gs_gui_functions
->OnInit() )
508 void GSocket_Cleanup(void)
510 if (gs_gui_functions
)
512 gs_gui_functions
->OnExit();
516 /* Constructors / Destructors for GSocket */
522 m_fd
= INVALID_SOCKET
;
523 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
530 m_error
= GSOCK_NOERROR
;
533 m_gui_dependent
= NULL
;
534 m_non_blocking
= false;
536 m_timeout
= 10*60*1000;
537 /* 10 minutes * 60 sec * 1000 millisec */
538 m_establishing
= false;
540 assert(gs_gui_functions
);
541 /* Per-socket GUI-specific initialization */
542 m_ok
= gs_gui_functions
->Init_Socket(this);
545 void GSocket::Close()
547 gs_gui_functions
->Disable_Events(this);
548 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
549 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
552 m_fd
= INVALID_SOCKET
;
559 /* Check that the socket is really shutdowned */
560 if (m_fd
!= INVALID_SOCKET
)
563 /* Per-socket GUI-specific cleanup */
564 gs_gui_functions
->Destroy_Socket(this);
566 /* Destroy private addresses */
568 GAddress_destroy(m_local
);
571 GAddress_destroy(m_peer
);
575 * Disallow further read/write operations on this socket, close
576 * the fd and disable all callbacks.
578 void GSocket::Shutdown()
584 /* Don't allow events to fire after socket has been closed */
585 gs_gui_functions
->Disable_Events(this);
587 /* If socket has been created, shutdown it */
588 if (m_fd
!= INVALID_SOCKET
)
594 /* Disable GUI callbacks */
595 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
596 m_cbacks
[evt
] = NULL
;
598 m_detected
= GSOCK_LOST_FLAG
;
601 /* Address handling */
607 * Set or get the local or peer address for this socket. The 'set'
608 * functions return GSOCK_NOERROR on success, an error code otherwise.
609 * The 'get' functions return a pointer to a GAddress object on success,
610 * or NULL otherwise, in which case they set the error code of the
611 * corresponding GSocket.
614 * GSOCK_INVSOCK - the socket is not valid.
615 * GSOCK_INVADDR - the address is not valid.
617 GSocketError
GSocket::SetLocal(GAddress
*address
)
621 /* the socket must be initialized, or it must be a server */
622 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
624 m_error
= GSOCK_INVSOCK
;
625 return GSOCK_INVSOCK
;
629 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
631 m_error
= GSOCK_INVADDR
;
632 return GSOCK_INVADDR
;
636 GAddress_destroy(m_local
);
638 m_local
= GAddress_copy(address
);
640 return GSOCK_NOERROR
;
643 GSocketError
GSocket::SetPeer(GAddress
*address
)
648 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
650 m_error
= GSOCK_INVADDR
;
651 return GSOCK_INVADDR
;
655 GAddress_destroy(m_peer
);
657 m_peer
= GAddress_copy(address
);
659 return GSOCK_NOERROR
;
662 GAddress
*GSocket::GetLocal()
665 struct sockaddr addr
;
666 WX_SOCKLEN_T size
= sizeof(addr
);
671 /* try to get it from the m_local var first */
673 return GAddress_copy(m_local
);
675 /* else, if the socket is initialized, try getsockname */
676 if (m_fd
== INVALID_SOCKET
)
678 m_error
= GSOCK_INVSOCK
;
682 if (getsockname(m_fd
, &addr
, (WX_SOCKLEN_T
*) &size
) < 0)
684 m_error
= GSOCK_IOERR
;
688 /* got a valid address from getsockname, create a GAddress object */
689 address
= GAddress_new();
692 m_error
= GSOCK_MEMERR
;
696 err
= _GAddress_translate_from(address
, &addr
, size
);
697 if (err
!= GSOCK_NOERROR
)
699 GAddress_destroy(address
);
707 GAddress
*GSocket::GetPeer()
711 /* try to get it from the m_peer var */
713 return GAddress_copy(m_peer
);
718 /* Server specific parts */
720 /* GSocket_SetServer:
721 * Sets up this socket as a server. The local address must have been
722 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
723 * Returns GSOCK_NOERROR on success, one of the following otherwise:
726 * GSOCK_INVSOCK - the socket is in use.
727 * GSOCK_INVADDR - the local address has not been set.
728 * GSOCK_IOERR - low-level error.
730 GSocketError
GSocket::SetServer()
736 /* must not be in use */
737 if (m_fd
!= INVALID_SOCKET
)
739 m_error
= GSOCK_INVSOCK
;
740 return GSOCK_INVSOCK
;
743 /* the local addr must have been set */
746 m_error
= GSOCK_INVADDR
;
747 return GSOCK_INVADDR
;
750 /* Initialize all fields */
754 /* Create the socket */
755 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
757 if (m_fd
== INVALID_SOCKET
)
759 m_error
= GSOCK_IOERR
;
763 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
765 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(arg
));
768 ioctl(m_fd
, FIONBIO
, &arg
);
769 gs_gui_functions
->Enable_Events(this);
771 /* allow a socket to re-bind if the socket is in the TIME_WAIT
772 state after being previously closed.
776 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
778 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEPORT
, (const char*)&arg
, sizeof(arg
));
782 /* Bind to the local address,
783 * retrieve the actual address bound,
784 * and listen up to 5 connections.
786 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
789 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
790 (listen(m_fd
, 5) != 0))
793 m_error
= GSOCK_IOERR
;
797 return GSOCK_NOERROR
;
800 /* GSocket_WaitConnection:
801 * Waits for an incoming client connection. Returns a pointer to
802 * a GSocket object, or NULL if there was an error, in which case
803 * the last error field will be updated for the calling GSocket.
805 * Error codes (set in the calling GSocket)
806 * GSOCK_INVSOCK - the socket is not valid or not a server.
807 * GSOCK_TIMEDOUT - timeout, no incoming connections.
808 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
809 * GSOCK_MEMERR - couldn't allocate memory.
810 * GSOCK_IOERR - low-level error.
812 GSocket
*GSocket::WaitConnection()
814 struct sockaddr from
;
815 WX_SOCKLEN_T fromlen
= sizeof(from
);
822 /* If the socket has already been created, we exit immediately */
823 if (m_fd
== INVALID_SOCKET
|| !m_server
)
825 m_error
= GSOCK_INVSOCK
;
829 /* Create a GSocket object for the new connection */
830 connection
= GSocket_new();
834 m_error
= GSOCK_MEMERR
;
838 /* Wait for a connection (with timeout) */
839 if (Input_Timeout() == GSOCK_TIMEDOUT
)
842 /* m_error set by _GSocket_Input_Timeout */
846 connection
->m_fd
= accept(m_fd
, &from
, (WX_SOCKLEN_T
*) &fromlen
);
848 /* Reenable CONNECTION events */
849 Enable(GSOCK_CONNECTION
);
851 if (connection
->m_fd
== INVALID_SOCKET
)
853 if (errno
== EWOULDBLOCK
)
854 m_error
= GSOCK_WOULDBLOCK
;
856 m_error
= GSOCK_IOERR
;
862 /* Initialize all fields */
863 connection
->m_server
= false;
864 connection
->m_stream
= true;
866 /* Setup the peer address field */
867 connection
->m_peer
= GAddress_new();
868 if (!connection
->m_peer
)
871 m_error
= GSOCK_MEMERR
;
875 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
876 if (err
!= GSOCK_NOERROR
)
883 #if defined(__EMX__) || defined(__VISAGECPP__)
884 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
886 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
888 gs_gui_functions
->Enable_Events(connection
);
893 bool GSocket::SetReusable()
895 /* socket must not be null, and must not be in use/already bound */
896 if (this && m_fd
== INVALID_SOCKET
)
906 /* Client specific parts */
909 * For stream (connection oriented) sockets, GSocket_Connect() tries
910 * to establish a client connection to a server using the peer address
911 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
912 * connection has been successfully established, or one of the error
913 * codes listed below. Note that for nonblocking sockets, a return
914 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
915 * request can be completed later; you should use GSocket_Select()
916 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
917 * corresponding asynchronous events.
919 * For datagram (non connection oriented) sockets, GSocket_Connect()
920 * just sets the peer address established with GSocket_SetPeer() as
921 * default destination.
924 * GSOCK_INVSOCK - the socket is in use or not valid.
925 * GSOCK_INVADDR - the peer address has not been established.
926 * GSOCK_TIMEDOUT - timeout, the connection failed.
927 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
928 * GSOCK_MEMERR - couldn't allocate memory.
929 * GSOCK_IOERR - low-level error.
931 GSocketError
GSocket::Connect(GSocketStream stream
)
938 /* Enable CONNECTION events (needed for nonblocking connections) */
939 Enable(GSOCK_CONNECTION
);
941 if (m_fd
!= INVALID_SOCKET
)
943 m_error
= GSOCK_INVSOCK
;
944 return GSOCK_INVSOCK
;
949 m_error
= GSOCK_INVADDR
;
950 return GSOCK_INVADDR
;
953 /* Streamed or dgram socket? */
954 m_stream
= (stream
== GSOCK_STREAMED
);
956 m_establishing
= false;
958 /* Create the socket */
959 m_fd
= socket(m_peer
->m_realfamily
,
960 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
962 if (m_fd
== INVALID_SOCKET
)
964 m_error
= GSOCK_IOERR
;
968 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
970 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(arg
));
973 #if defined(__EMX__) || defined(__VISAGECPP__)
974 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
976 ioctl(m_fd
, FIONBIO
, &arg
);
979 // If the reuse flag is set, use the applicable socket reuse flags(s)
982 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
984 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEPORT
, (const char*)&arg
, sizeof(arg
));
988 // If a local address has been set, then we need to bind to it before calling connect
989 if (m_local
&& m_local
->m_addr
)
991 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
994 /* Connect it to the peer address, with a timeout (see below) */
995 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
997 /* We only call Enable_Events if we know we aren't shutting down the socket.
998 * NB: Enable_Events needs to be called whether the socket is blocking or
999 * non-blocking, it just shouldn't be called prior to knowing there is a
1000 * connection _if_ blocking sockets are being used.
1001 * If connect above returns 0, we are already connected and need to make the
1002 * call to Enable_Events now.
1005 if (m_non_blocking
|| ret
== 0)
1006 gs_gui_functions
->Enable_Events(this);
1012 /* If connect failed with EINPROGRESS and the GSocket object
1013 * is in blocking mode, we select() for the specified timeout
1014 * checking for writability to see if the connection request
1017 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
1019 if (Output_Timeout() == GSOCK_TIMEDOUT
)
1022 /* m_error is set in _GSocket_Output_Timeout */
1023 return GSOCK_TIMEDOUT
;
1028 SOCKOPTLEN_T len
= sizeof(error
);
1030 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
1032 gs_gui_functions
->Enable_Events(this);
1035 return GSOCK_NOERROR
;
1039 /* If connect failed with EINPROGRESS and the GSocket object
1040 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
1041 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
1042 * this way if the connection completes, a GSOCK_CONNECTION
1043 * event will be generated, if enabled.
1045 if ((err
== EINPROGRESS
) && (m_non_blocking
))
1047 m_establishing
= true;
1048 m_error
= GSOCK_WOULDBLOCK
;
1049 return GSOCK_WOULDBLOCK
;
1052 /* If connect failed with an error other than EINPROGRESS,
1053 * then the call to GSocket_Connect has failed.
1056 m_error
= GSOCK_IOERR
;
1061 return GSOCK_NOERROR
;
1064 /* Datagram sockets */
1066 /* GSocket_SetNonOriented:
1067 * Sets up this socket as a non-connection oriented (datagram) socket.
1068 * Before using this function, the local address must have been set
1069 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
1070 * on success, or one of the following otherwise.
1073 * GSOCK_INVSOCK - the socket is in use.
1074 * GSOCK_INVADDR - the local address has not been set.
1075 * GSOCK_IOERR - low-level error.
1077 GSocketError
GSocket::SetNonOriented()
1083 if (m_fd
!= INVALID_SOCKET
)
1085 m_error
= GSOCK_INVSOCK
;
1086 return GSOCK_INVSOCK
;
1091 m_error
= GSOCK_INVADDR
;
1092 return GSOCK_INVADDR
;
1095 /* Initialize all fields */
1099 /* Create the socket */
1100 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
1102 if (m_fd
== INVALID_SOCKET
)
1104 m_error
= GSOCK_IOERR
;
1107 #if defined(__EMX__) || defined(__VISAGECPP__)
1108 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
1110 ioctl(m_fd
, FIONBIO
, &arg
);
1112 gs_gui_functions
->Enable_Events(this);
1116 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(arg
));
1118 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEPORT
, (const char*)&arg
, sizeof(arg
));
1122 /* Bind to the local address,
1123 * and retrieve the actual address bound.
1125 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
1128 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0))
1131 m_error
= GSOCK_IOERR
;
1135 return GSOCK_NOERROR
;
1140 /* Like recv(), send(), ... */
1141 int GSocket::Read(char *buffer
, int size
)
1147 if (m_fd
== INVALID_SOCKET
|| m_server
)
1149 m_error
= GSOCK_INVSOCK
;
1153 /* Disable events during query of socket status */
1154 Disable(GSOCK_INPUT
);
1156 /* If the socket is blocking, wait for data (with a timeout) */
1157 if (Input_Timeout() == GSOCK_TIMEDOUT
) {
1158 m_error
= GSOCK_TIMEDOUT
;
1159 /* Don't return here immediately, otherwise socket events would not be
1167 ret
= Recv_Stream(buffer
, size
);
1169 ret
= Recv_Dgram(buffer
, size
);
1171 /* If recv returned zero, then the connection has been gracefully closed.
1172 * Otherwise, recv has returned an error (-1), in which case we have lost the
1173 * socket only if errno does _not_ indicate that there may be more data to read.
1177 /* Make sure wxSOCKET_LOST event gets sent and shut down the socket */
1178 m_detected
= GSOCK_LOST_FLAG
;
1184 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1185 m_error
= GSOCK_WOULDBLOCK
;
1187 m_error
= GSOCK_IOERR
;
1191 /* Enable events again now that we are done processing */
1192 Enable(GSOCK_INPUT
);
1197 int GSocket::Write(const char *buffer
, int size
)
1203 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
1205 if (m_fd
== INVALID_SOCKET
|| m_server
)
1207 m_error
= GSOCK_INVSOCK
;
1211 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
1213 /* If the socket is blocking, wait for writability (with a timeout) */
1214 if (Output_Timeout() == GSOCK_TIMEDOUT
)
1217 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
1219 /* Write the data */
1221 ret
= Send_Stream(buffer
, size
);
1223 ret
= Send_Dgram(buffer
, size
);
1225 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
1229 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1231 m_error
= GSOCK_WOULDBLOCK
;
1232 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1236 m_error
= GSOCK_IOERR
;
1237 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1240 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1241 * in MSW). Once the first OUTPUT event is received, users can assume
1242 * that the socket is writable until a read operation fails. Only then
1243 * will further OUTPUT events be posted.
1245 Enable(GSOCK_OUTPUT
);
1250 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
1256 * Polls the socket to determine its status. This function will
1257 * check for the events specified in the 'flags' parameter, and
1258 * it will return a mask indicating which operations can be
1259 * performed. This function won't block, regardless of the
1260 * mode (blocking | nonblocking) of the socket.
1262 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
1264 if (!gs_gui_functions
->CanUseEventLoop())
1267 GSocketEventFlags result
= 0;
1276 return (GSOCK_LOST_FLAG
& flags
);
1278 /* Do not use a static struct, Linux can garble it */
1279 tv
.tv_sec
= m_timeout
/ 1000;
1280 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1282 wxFD_ZERO(&readfds
);
1283 wxFD_ZERO(&writefds
);
1284 wxFD_ZERO(&exceptfds
);
1285 wxFD_SET(m_fd
, &readfds
);
1286 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
1287 wxFD_SET(m_fd
, &writefds
);
1288 wxFD_SET(m_fd
, &exceptfds
);
1290 /* Check 'sticky' CONNECTION flag first */
1291 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
1293 /* If we have already detected a LOST event, then don't try
1294 * to do any further processing.
1296 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1298 m_establishing
= false;
1300 return (GSOCK_LOST_FLAG
& flags
);
1303 /* Try select now */
1304 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
1306 /* What to do here? */
1307 return (result
& flags
);
1310 /* Check for exceptions and errors */
1311 if (wxFD_ISSET(m_fd
, &exceptfds
))
1313 m_establishing
= false;
1314 m_detected
= GSOCK_LOST_FLAG
;
1316 /* LOST event: Abort any further processing */
1317 return (GSOCK_LOST_FLAG
& flags
);
1320 /* Check for readability */
1321 if (wxFD_ISSET(m_fd
, &readfds
))
1323 result
|= GSOCK_INPUT_FLAG
;
1325 if (m_server
&& m_stream
)
1327 /* This is a TCP server socket that detected a connection.
1328 While the INPUT_FLAG is also set, it doesn't matter on
1329 this kind of sockets, as we can only Accept() from them. */
1330 result
|= GSOCK_CONNECTION_FLAG
;
1331 m_detected
|= GSOCK_CONNECTION_FLAG
;
1335 /* Check for writability */
1336 if (wxFD_ISSET(m_fd
, &writefds
))
1338 if (m_establishing
&& !m_server
)
1341 SOCKOPTLEN_T len
= sizeof(error
);
1343 m_establishing
= false;
1345 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1349 m_detected
= GSOCK_LOST_FLAG
;
1351 /* LOST event: Abort any further processing */
1352 return (GSOCK_LOST_FLAG
& flags
);
1356 result
|= GSOCK_CONNECTION_FLAG
;
1357 m_detected
|= GSOCK_CONNECTION_FLAG
;
1362 result
|= GSOCK_OUTPUT_FLAG
;
1366 return (result
& flags
);
1372 return flags
& m_detected
;
1378 /* GSocket_SetNonBlocking:
1379 * Sets the socket to non-blocking mode. All IO calls will return
1382 void GSocket::SetNonBlocking(bool non_block
)
1386 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1388 m_non_blocking
= non_block
;
1391 /* GSocket_SetTimeout:
1392 * Sets the timeout for blocking calls. Time is expressed in
1395 void GSocket::SetTimeout(unsigned long millisec
)
1399 m_timeout
= millisec
;
1402 /* GSocket_GetError:
1403 * Returns the last error occurred for this socket. Note that successful
1404 * operations do not clear this back to GSOCK_NOERROR, so use it only
1407 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1417 * There is data to be read in the input buffer. If, after a read
1418 * operation, there is still data available, the callback function will
1421 * The socket is available for writing. That is, the next write call
1422 * won't block. This event is generated only once, when the connection is
1423 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1424 * when the output buffer empties again. This means that the app should
1425 * assume that it can write since the first OUTPUT event, and no more
1426 * OUTPUT events will be generated unless an error occurs.
1428 * Connection successfully established, for client sockets, or incoming
1429 * client connection, for server sockets. Wait for this event (also watch
1430 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1432 * The connection is lost (or a connection request failed); this could
1433 * be due to a failure, or due to the peer closing it gracefully.
1436 /* GSocket_SetCallback:
1437 * Enables the callbacks specified by 'flags'. Note that 'flags'
1438 * may be a combination of flags OR'ed toghether, so the same
1439 * callback function can be made to accept different events.
1440 * The callback function must have the following prototype:
1442 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1444 void GSocket::SetCallback(GSocketEventFlags flags
,
1445 GSocketCallback callback
, char *cdata
)
1451 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1453 if ((flags
& (1 << count
)) != 0)
1455 m_cbacks
[count
] = callback
;
1456 m_data
[count
] = cdata
;
1461 /* GSocket_UnsetCallback:
1462 * Disables all callbacks specified by 'flags', which may be a
1463 * combination of flags OR'ed toghether.
1465 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1471 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1473 if ((flags
& (1 << count
)) != 0)
1475 m_cbacks
[count
] = NULL
;
1476 m_data
[count
] = NULL
;
1481 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1482 void *optval
, int *optlen
)
1484 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1485 return GSOCK_NOERROR
;
1487 return GSOCK_OPTERR
;
1490 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1491 const void *optval
, int optlen
)
1493 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1494 return GSOCK_NOERROR
;
1496 return GSOCK_OPTERR
;
1499 #define CALL_CALLBACK(socket, event) { \
1500 socket->Disable(event); \
1501 if (socket->m_cbacks[event]) \
1502 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1506 void GSocket::Enable(GSocketEvent event
)
1508 m_detected
&= ~(1 << event
);
1509 gs_gui_functions
->Install_Callback(this, event
);
1512 void GSocket::Disable(GSocketEvent event
)
1514 m_detected
|= (1 << event
);
1515 gs_gui_functions
->Uninstall_Callback(this, event
);
1518 /* _GSocket_Input_Timeout:
1519 * For blocking sockets, wait until data is available or
1520 * until timeout ellapses.
1522 GSocketError
GSocket::Input_Timeout()
1528 /* Linux select() will overwrite the struct on return */
1529 tv
.tv_sec
= (m_timeout
/ 1000);
1530 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1532 if (!m_non_blocking
)
1534 wxFD_ZERO(&readfds
);
1535 wxFD_SET(m_fd
, &readfds
);
1536 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1539 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1540 m_error
= GSOCK_TIMEDOUT
;
1541 return GSOCK_TIMEDOUT
;
1546 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1547 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1548 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1549 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1550 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1551 m_error
= GSOCK_TIMEDOUT
;
1552 return GSOCK_TIMEDOUT
;
1556 return GSOCK_NOERROR
;
1559 /* _GSocket_Output_Timeout:
1560 * For blocking sockets, wait until data can be sent without
1561 * blocking or until timeout ellapses.
1563 GSocketError
GSocket::Output_Timeout()
1569 /* Linux select() will overwrite the struct on return */
1570 tv
.tv_sec
= (m_timeout
/ 1000);
1571 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1573 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1575 if (!m_non_blocking
)
1577 wxFD_ZERO(&writefds
);
1578 wxFD_SET(m_fd
, &writefds
);
1579 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1582 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1583 m_error
= GSOCK_TIMEDOUT
;
1584 return GSOCK_TIMEDOUT
;
1589 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1590 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1591 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1592 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1593 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1594 m_error
= GSOCK_TIMEDOUT
;
1595 return GSOCK_TIMEDOUT
;
1598 if ( ! wxFD_ISSET(m_fd
, &writefds
) )
1600 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1604 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1609 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1612 return GSOCK_NOERROR
;
1615 int GSocket::Recv_Stream(char *buffer
, int size
)
1620 ret
= recv(m_fd
, buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1622 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1627 int GSocket::Recv_Dgram(char *buffer
, int size
)
1629 struct sockaddr from
;
1630 WX_SOCKLEN_T fromlen
= sizeof(from
);
1634 fromlen
= sizeof(from
);
1638 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (WX_SOCKLEN_T
*) &fromlen
);
1640 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1645 /* Translate a system address into a GSocket address */
1648 m_peer
= GAddress_new();
1651 m_error
= GSOCK_MEMERR
;
1656 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1657 if (err
!= GSOCK_NOERROR
)
1659 GAddress_destroy(m_peer
);
1668 int GSocket::Send_Stream(const char *buffer
, int size
)
1676 ret
= send(m_fd
, (char *)buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1678 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1685 int GSocket::Send_Dgram(const char *buffer
, int size
)
1687 struct sockaddr
*addr
;
1693 m_error
= GSOCK_INVADDR
;
1697 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1698 if (err
!= GSOCK_NOERROR
)
1708 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1710 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1714 /* Frees memory allocated from _GAddress_translate_to */
1720 void GSocket::Detected_Read()
1724 /* Safeguard against straggling call to Detected_Read */
1725 if (m_fd
== INVALID_SOCKET
)
1730 /* If we have already detected a LOST event, then don't try
1731 * to do any further processing.
1733 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1735 m_establishing
= false;
1737 CALL_CALLBACK(this, GSOCK_LOST
);
1742 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1746 CALL_CALLBACK(this, GSOCK_INPUT
);
1750 if (m_server
&& m_stream
)
1752 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1756 /* graceful shutdown */
1757 CALL_CALLBACK(this, GSOCK_LOST
);
1762 /* Do not throw a lost event in cases where the socket isn't really lost */
1763 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
) || (errno
== EINTR
))
1765 CALL_CALLBACK(this, GSOCK_INPUT
);
1769 CALL_CALLBACK(this, GSOCK_LOST
);
1776 void GSocket::Detected_Write()
1778 /* If we have already detected a LOST event, then don't try
1779 * to do any further processing.
1781 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1783 m_establishing
= false;
1785 CALL_CALLBACK(this, GSOCK_LOST
);
1790 if (m_establishing
&& !m_server
)
1793 SOCKOPTLEN_T len
= sizeof(error
);
1795 m_establishing
= false;
1797 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1801 CALL_CALLBACK(this, GSOCK_LOST
);
1806 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1807 /* We have to fire this event by hand because CONNECTION (for clients)
1808 * and OUTPUT are internally the same and we just disabled CONNECTION
1809 * events with the above macro.
1811 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1816 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1820 /* Compatibility functions for GSocket */
1821 GSocket
*GSocket_new(void)
1823 GSocket
*newsocket
= new GSocket();
1824 if (newsocket
->IsOk())
1833 * -------------------------------------------------------------------------
1835 * -------------------------------------------------------------------------
1838 /* CHECK_ADDRESS verifies that the current address family is either
1839 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1840 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1841 * an appropiate error code.
1843 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1845 #define CHECK_ADDRESS(address, family) \
1847 if (address->m_family == GSOCK_NOFAMILY) \
1848 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1849 return address->m_error; \
1850 if (address->m_family != GSOCK_##family) \
1852 address->m_error = GSOCK_INVADDR; \
1853 return GSOCK_INVADDR; \
1857 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1859 if (address->m_family == GSOCK_NOFAMILY) \
1860 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1862 if (address->m_family != GSOCK_##family) \
1864 address->m_error = GSOCK_INVADDR; \
1870 GAddress
*GAddress_new(void)
1874 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1877 address
->m_family
= GSOCK_NOFAMILY
;
1878 address
->m_addr
= NULL
;
1884 GAddress
*GAddress_copy(GAddress
*address
)
1888 assert(address
!= NULL
);
1890 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1893 memcpy(addr2
, address
, sizeof(GAddress
));
1895 if (address
->m_addr
&& address
->m_len
> 0)
1897 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1898 if (addr2
->m_addr
== NULL
)
1903 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1909 void GAddress_destroy(GAddress
*address
)
1911 assert(address
!= NULL
);
1913 if (address
->m_addr
)
1914 free(address
->m_addr
);
1919 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1921 assert(address
!= NULL
);
1923 address
->m_family
= type
;
1926 GAddressType
GAddress_GetFamily(GAddress
*address
)
1928 assert(address
!= NULL
);
1930 return address
->m_family
;
1933 GSocketError
_GAddress_translate_from(GAddress
*address
,
1934 struct sockaddr
*addr
, int len
)
1936 address
->m_realfamily
= addr
->sa_family
;
1937 switch (addr
->sa_family
)
1940 address
->m_family
= GSOCK_INET
;
1943 address
->m_family
= GSOCK_UNIX
;
1947 address
->m_family
= GSOCK_INET6
;
1952 address
->m_error
= GSOCK_INVOP
;
1957 if (address
->m_addr
)
1958 free(address
->m_addr
);
1960 address
->m_len
= len
;
1961 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1963 if (address
->m_addr
== NULL
)
1965 address
->m_error
= GSOCK_MEMERR
;
1966 return GSOCK_MEMERR
;
1969 memcpy(address
->m_addr
, addr
, len
);
1971 return GSOCK_NOERROR
;
1974 GSocketError
_GAddress_translate_to(GAddress
*address
,
1975 struct sockaddr
**addr
, int *len
)
1977 if (!address
->m_addr
)
1979 address
->m_error
= GSOCK_INVADDR
;
1980 return GSOCK_INVADDR
;
1983 *len
= address
->m_len
;
1984 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1987 address
->m_error
= GSOCK_MEMERR
;
1988 return GSOCK_MEMERR
;
1991 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1992 return GSOCK_NOERROR
;
1996 * -------------------------------------------------------------------------
1997 * Internet address family
1998 * -------------------------------------------------------------------------
2001 GSocketError
_GAddress_Init_INET(GAddress
*address
)
2003 address
->m_len
= sizeof(struct sockaddr_in
);
2004 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
2005 if (address
->m_addr
== NULL
)
2007 address
->m_error
= GSOCK_MEMERR
;
2008 return GSOCK_MEMERR
;
2011 address
->m_family
= GSOCK_INET
;
2012 address
->m_realfamily
= PF_INET
;
2013 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
2014 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
2016 return GSOCK_NOERROR
;
2019 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
2022 struct in_addr
*addr
;
2024 assert(address
!= NULL
);
2026 CHECK_ADDRESS(address
, INET
);
2028 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
2030 /* If it is a numeric host name, convert it now */
2031 #if defined(HAVE_INET_ATON)
2032 if (inet_aton(hostname
, addr
) == 0)
2034 #elif defined(HAVE_INET_ADDR)
2035 if ( (addr
->s_addr
= inet_addr(hostname
)) == (unsigned)-1 )
2038 /* Use gethostbyname by default */
2040 int val
= 1; /* VA doesn't like constants in conditional expressions */
2045 struct in_addr
*array_addr
;
2047 /* It is a real name, we solve it */
2049 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2050 struct hostent_data buffer
;
2055 he
= wxGethostbyname_r(hostname
, &h
, (void*)&buffer
, sizeof(buffer
), &err
);
2058 /* Reset to invalid address */
2059 addr
->s_addr
= INADDR_NONE
;
2060 address
->m_error
= GSOCK_NOHOST
;
2061 return GSOCK_NOHOST
;
2064 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
2065 addr
->s_addr
= array_addr
[0].s_addr
;
2068 return GSOCK_NOERROR
;
2071 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
2073 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
2076 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
2077 unsigned long hostaddr
)
2079 struct in_addr
*addr
;
2081 assert(address
!= NULL
);
2083 CHECK_ADDRESS(address
, INET
);
2085 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
2086 addr
->s_addr
= htonl(hostaddr
);
2088 return GSOCK_NOERROR
;
2091 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
2092 const char *protocol
)
2095 struct sockaddr_in
*addr
;
2097 assert(address
!= NULL
);
2098 CHECK_ADDRESS(address
, INET
);
2102 address
->m_error
= GSOCK_INVPORT
;
2103 return GSOCK_INVPORT
;
2106 #if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2107 struct servent_data buffer
;
2111 struct servent serv
;
2112 se
= wxGetservbyname_r(port
, protocol
, &serv
,
2113 (void*)&buffer
, sizeof(buffer
));
2116 /* the cast to int suppresses compiler warnings about subscript having the
2118 if (isdigit((int)port
[0]))
2122 port_int
= atoi(port
);
2123 addr
= (struct sockaddr_in
*)address
->m_addr
;
2124 addr
->sin_port
= htons(port_int
);
2125 return GSOCK_NOERROR
;
2128 address
->m_error
= GSOCK_INVPORT
;
2129 return GSOCK_INVPORT
;
2132 addr
= (struct sockaddr_in
*)address
->m_addr
;
2133 addr
->sin_port
= se
->s_port
;
2135 return GSOCK_NOERROR
;
2138 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
2140 struct sockaddr_in
*addr
;
2142 assert(address
!= NULL
);
2143 CHECK_ADDRESS(address
, INET
);
2145 addr
= (struct sockaddr_in
*)address
->m_addr
;
2146 addr
->sin_port
= htons(port
);
2148 return GSOCK_NOERROR
;
2151 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
2155 struct sockaddr_in
*addr
;
2157 assert(address
!= NULL
);
2158 CHECK_ADDRESS(address
, INET
);
2160 addr
= (struct sockaddr_in
*)address
->m_addr
;
2161 addr_buf
= (char *)&(addr
->sin_addr
);
2163 struct hostent temphost
;
2164 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2165 struct hostent_data buffer
;
2170 he
= wxGethostbyaddr_r(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
, &temphost
,
2171 (void*)&buffer
, sizeof(buffer
), &err
);
2174 address
->m_error
= GSOCK_NOHOST
;
2175 return GSOCK_NOHOST
;
2178 strncpy(hostname
, he
->h_name
, sbuf
);
2180 return GSOCK_NOERROR
;
2183 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
2185 struct sockaddr_in
*addr
;
2187 assert(address
!= NULL
);
2188 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
2190 addr
= (struct sockaddr_in
*)address
->m_addr
;
2192 return ntohl(addr
->sin_addr
.s_addr
);
2195 unsigned short GAddress_INET_GetPort(GAddress
*address
)
2197 struct sockaddr_in
*addr
;
2199 assert(address
!= NULL
);
2200 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
2202 addr
= (struct sockaddr_in
*)address
->m_addr
;
2203 return ntohs(addr
->sin_port
);
2207 * -------------------------------------------------------------------------
2208 * Unix address family
2209 * -------------------------------------------------------------------------
2212 #ifndef __VISAGECPP__
2213 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
2215 address
->m_len
= sizeof(struct sockaddr_un
);
2216 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
2217 if (address
->m_addr
== NULL
)
2219 address
->m_error
= GSOCK_MEMERR
;
2220 return GSOCK_MEMERR
;
2223 address
->m_family
= GSOCK_UNIX
;
2224 address
->m_realfamily
= PF_UNIX
;
2225 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
2226 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
2228 return GSOCK_NOERROR
;
2231 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2233 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
2235 struct sockaddr_un
*addr
;
2237 assert(address
!= NULL
);
2239 CHECK_ADDRESS(address
, UNIX
);
2241 addr
= ((struct sockaddr_un
*)address
->m_addr
);
2242 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
2243 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
2245 return GSOCK_NOERROR
;
2248 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
2250 struct sockaddr_un
*addr
;
2252 assert(address
!= NULL
);
2253 CHECK_ADDRESS(address
, UNIX
);
2255 addr
= (struct sockaddr_un
*)address
->m_addr
;
2257 strncpy(path
, addr
->sun_path
, sbuf
);
2259 return GSOCK_NOERROR
;
2261 #endif /* !defined(__VISAGECPP__) */
2262 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */