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>
46 u_char sun_len
; /* sockaddr len including null */
47 u_char sun_family
; /* AF_UNIX */
48 char sun_path
[108]; /* path name (gag) */
51 #include <sys/socket.h>
57 #include <netinet/in.h>
58 #include <arpa/inet.h>
65 #include <machine/endian.h>
71 #define EBADF SOCEBADF
77 #include <sys/socket.h>
78 #include <sys/ioctl.h>
79 #include <sys/select.h>
81 #define close(a) soclose(a)
82 #define select(a,b,c,d,e) bsdselect(a,b,c,d,e)
83 int _System
bsdselect(int,
88 int _System
soclose(int);
92 #include <sys/select.h>
100 # include <sys/filio.h>
103 # include <bstring.h>
106 # include <strings.h>
113 # define WX_SOCKLEN_T unsigned int
117 # define WX_SOCKLEN_T socklen_t
119 # elif defined(__WXMAC__)
120 # define WX_SOCKLEN_T socklen_t
122 # define WX_SOCKLEN_T int
126 #endif /* SOCKLEN_T */
129 #define SOCKOPTLEN_T WX_SOCKLEN_T
133 * MSW defines this, Unices don't.
135 #ifndef INVALID_SOCKET
136 #define INVALID_SOCKET -1
139 /* UnixWare reportedly needs this for FIONBIO definition */
141 #include <sys/filio.h>
145 * INADDR_BROADCAST is identical to INADDR_NONE which is not defined
146 * on all systems. INADDR_BROADCAST should be fine to indicate an error.
149 #define INADDR_NONE INADDR_BROADCAST
152 #if defined(__VISAGECPP__) || defined(__WATCOMC__)
154 #define MASK_SIGNAL() {
155 #define UNMASK_SIGNAL() }
158 extern "C" { typedef void (*wxSigHandler
)(int); }
160 #define MASK_SIGNAL() \
162 wxSigHandler old_handler = signal(SIGPIPE, SIG_IGN);
164 #define UNMASK_SIGNAL() \
165 signal(SIGPIPE, old_handler); \
170 /* If a SIGPIPE is issued by a socket call on a remotely closed socket,
171 the program will "crash" unless it explicitly handles the SIGPIPE.
172 By using MSG_NOSIGNAL, the SIGPIPE is suppressed. Later, we will
173 use SO_NOSIGPIPE (if available), the BSD equivalent. */
175 # define GSOCKET_MSG_NOSIGNAL MSG_NOSIGNAL
176 #else /* MSG_NOSIGNAL not available (FreeBSD including OS X) */
177 # define GSOCKET_MSG_NOSIGNAL 0
178 #endif /* MSG_NOSIGNAL */
180 #ifndef __GSOCKET_STANDALONE__
181 # include "wx/unix/gsockunx.h"
182 # include "wx/unix/private.h"
183 # include "wx/gsocket.h"
184 #if wxUSE_THREADS && (defined(HAVE_GETHOSTBYNAME) || defined(HAVE_GETSERVBYNAME))
185 # include "wx/thread.h"
188 # include "gsockunx.h"
189 # include "gsocket.h"
193 #endif /* __GSOCKET_STANDALONE__ */
195 #if defined(HAVE_GETHOSTBYNAME)
196 static struct hostent
* deepCopyHostent(struct hostent
*h
,
197 const struct hostent
*he
,
198 char *buffer
, int size
, int *err
)
200 memcpy(h
, he
, sizeof(struct hostent
));
201 int len
= strlen(h
->h_name
);
204 memcpy(buffer
, h
->h_name
, len
);
210 for (char **p
= h
->h_addr_list
; *p
!= 0; p
++) {
215 memcpy(buffer
, *p
, len
);
220 for (char **q
= h
->h_aliases
; size
> 0 && *q
!= 0; q
++){
224 memcpy(buffer
, *q
, len
);
234 struct hostent
* wxGethostbyname_r(const char *hostname
, struct hostent
*h
,
235 void *buffer
, int size
, int *err
)
238 struct hostent
*he
= NULL
;
240 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
241 if (gethostbyname_r(hostname
, h
, (char*)buffer
, size
, &he
, err
))
243 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
244 he
= gethostbyname_r(hostname
, h
, (char*)buffer
, size
, err
);
245 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
246 if (gethostbyname_r(hostname
, h
, (struct hostent_data
*) buffer
))
253 #elif defined(HAVE_GETHOSTBYNAME)
255 static wxMutex nameLock
;
256 wxMutexLocker
locker(nameLock
);
258 he
= gethostbyname(hostname
);
262 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
267 struct hostent
* wxGethostbyaddr_r(const char *addr_buf
, int buf_size
,
268 int proto
, struct hostent
*h
,
269 void *buffer
, int size
, int *err
)
271 struct hostent
*he
= NULL
;
273 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_6)
274 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
275 (char*)buffer
, size
, &he
, err
))
277 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_5)
278 he
= gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
, (char*)buffer
, size
, err
);
279 #elif defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
280 if (gethostbyaddr_r(addr_buf
, buf_size
, proto
, h
,
281 (struct hostent_data
*) buffer
))
288 #elif defined(HAVE_GETHOSTBYNAME)
290 static wxMutex addrLock
;
291 wxMutexLocker
locker(addrLock
);
293 he
= gethostbyaddr(addr_buf
, buf_size
, proto
);
297 he
= deepCopyHostent(h
, he
, (char*)buffer
, size
, err
);
302 #if defined(HAVE_GETSERVBYNAME)
303 static struct servent
* deepCopyServent(struct servent
*s
,
304 const struct servent
*se
,
305 char *buffer
, int size
)
307 memcpy(s
, se
, sizeof(struct servent
));
308 int len
= strlen(s
->s_name
);
311 memcpy(buffer
, s
->s_name
, len
);
316 len
= strlen(s
->s_proto
);
319 memcpy(buffer
, s
->s_proto
, len
);
324 for (char **q
= s
->s_aliases
; size
> 0 && *q
!= 0; q
++){
328 memcpy(buffer
, *q
, len
);
338 struct servent
*wxGetservbyname_r(const char *port
, const char *protocol
,
339 struct servent
*serv
, void *buffer
, int size
)
341 struct servent
*se
= NULL
;
342 #if defined(HAVE_FUNC_GETSERVBYNAME_R_6)
343 if (getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
, &se
))
345 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_5)
346 se
= getservbyname_r(port
, protocol
, serv
, (char*)buffer
, size
);
347 #elif defined(HAVE_FUNC_GETSERVBYNAME_R_4)
348 if (getservbyname_r(port
, protocol
, serv
, (struct servent_data
*) buffer
))
352 #elif defined(HAVE_GETSERVBYNAME)
354 static wxMutex servLock
;
355 wxMutexLocker
locker(servLock
);
357 se
= getservbyname(port
, protocol
);
359 se
= deepCopyServent(serv
, se
, (char*)buffer
, size
);
364 /* debugging helpers */
365 #ifdef __GSOCKET_DEBUG__
366 # define GSocket_Debug(args) printf args
368 # define GSocket_Debug(args)
369 #endif /* __GSOCKET_DEBUG__ */
371 /* Table of GUI-related functions. We must call them indirectly because
372 * of wxBase and GUI separation: */
374 static GSocketGUIFunctionsTable
*gs_gui_functions
;
376 class GSocketGUIFunctionsTableNull
: public GSocketGUIFunctionsTable
379 virtual bool OnInit();
380 virtual void OnExit();
381 virtual bool CanUseEventLoop();
382 virtual bool Init_Socket(GSocket
*socket
);
383 virtual void Destroy_Socket(GSocket
*socket
);
384 virtual void Install_Callback(GSocket
*socket
, GSocketEvent event
);
385 virtual void Uninstall_Callback(GSocket
*socket
, GSocketEvent event
);
386 virtual void Enable_Events(GSocket
*socket
);
387 virtual void Disable_Events(GSocket
*socket
);
390 bool GSocketGUIFunctionsTableNull::OnInit()
392 void GSocketGUIFunctionsTableNull::OnExit()
394 bool GSocketGUIFunctionsTableNull::CanUseEventLoop()
396 bool GSocketGUIFunctionsTableNull::Init_Socket(GSocket
*WXUNUSED(socket
))
398 void GSocketGUIFunctionsTableNull::Destroy_Socket(GSocket
*WXUNUSED(socket
))
400 void GSocketGUIFunctionsTableNull::Install_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
402 void GSocketGUIFunctionsTableNull::Uninstall_Callback(GSocket
*WXUNUSED(socket
), GSocketEvent
WXUNUSED(event
))
404 void GSocketGUIFunctionsTableNull::Enable_Events(GSocket
*WXUNUSED(socket
))
406 void GSocketGUIFunctionsTableNull::Disable_Events(GSocket
*WXUNUSED(socket
))
408 /* Global initialisers */
410 void GSocket_SetGUIFunctions(GSocketGUIFunctionsTable
*guifunc
)
412 gs_gui_functions
= guifunc
;
415 int GSocket_Init(void)
417 if (!gs_gui_functions
)
419 static GSocketGUIFunctionsTableNull table
;
420 gs_gui_functions
= &table
;
422 if ( !gs_gui_functions
->OnInit() )
427 void GSocket_Cleanup(void)
429 if (gs_gui_functions
)
431 gs_gui_functions
->OnExit();
435 /* Constructors / Destructors for GSocket */
441 m_fd
= INVALID_SOCKET
;
442 for (i
=0;i
<GSOCK_MAX_EVENT
;i
++)
449 m_error
= GSOCK_NOERROR
;
452 m_gui_dependent
= NULL
;
453 m_non_blocking
= false;
455 m_timeout
= 10*60*1000;
456 /* 10 minutes * 60 sec * 1000 millisec */
457 m_establishing
= false;
459 assert(gs_gui_functions
);
460 /* Per-socket GUI-specific initialization */
461 m_ok
= gs_gui_functions
->Init_Socket(this);
464 void GSocket::Close()
466 gs_gui_functions
->Disable_Events(this);
467 /* gsockosx.c calls CFSocketInvalidate which closes the socket for us */
468 #if !(defined(__DARWIN__) && (defined(__WXMAC__) || defined(__WXCOCOA__)))
471 m_fd
= INVALID_SOCKET
;
478 /* Check that the socket is really shutdowned */
479 if (m_fd
!= INVALID_SOCKET
)
482 /* Per-socket GUI-specific cleanup */
483 gs_gui_functions
->Destroy_Socket(this);
485 /* Destroy private addresses */
487 GAddress_destroy(m_local
);
490 GAddress_destroy(m_peer
);
494 * Disallow further read/write operations on this socket, close
495 * the fd and disable all callbacks.
497 void GSocket::Shutdown()
503 /* Don't allow events to fire after socket has been closed */
504 gs_gui_functions
->Disable_Events(this);
506 /* If socket has been created, shutdown it */
507 if (m_fd
!= INVALID_SOCKET
)
513 /* Disable GUI callbacks */
514 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
515 m_cbacks
[evt
] = NULL
;
517 m_detected
= GSOCK_LOST_FLAG
;
520 /* Address handling */
526 * Set or get the local or peer address for this socket. The 'set'
527 * functions return GSOCK_NOERROR on success, an error code otherwise.
528 * The 'get' functions return a pointer to a GAddress object on success,
529 * or NULL otherwise, in which case they set the error code of the
530 * corresponding GSocket.
533 * GSOCK_INVSOCK - the socket is not valid.
534 * GSOCK_INVADDR - the address is not valid.
536 GSocketError
GSocket::SetLocal(GAddress
*address
)
540 /* the socket must be initialized, or it must be a server */
541 if ((m_fd
!= INVALID_SOCKET
&& !m_server
))
543 m_error
= GSOCK_INVSOCK
;
544 return GSOCK_INVSOCK
;
548 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
550 m_error
= GSOCK_INVADDR
;
551 return GSOCK_INVADDR
;
555 GAddress_destroy(m_local
);
557 m_local
= GAddress_copy(address
);
559 return GSOCK_NOERROR
;
562 GSocketError
GSocket::SetPeer(GAddress
*address
)
567 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
569 m_error
= GSOCK_INVADDR
;
570 return GSOCK_INVADDR
;
574 GAddress_destroy(m_peer
);
576 m_peer
= GAddress_copy(address
);
578 return GSOCK_NOERROR
;
581 GAddress
*GSocket::GetLocal()
584 struct sockaddr addr
;
585 WX_SOCKLEN_T size
= sizeof(addr
);
590 /* try to get it from the m_local var first */
592 return GAddress_copy(m_local
);
594 /* else, if the socket is initialized, try getsockname */
595 if (m_fd
== INVALID_SOCKET
)
597 m_error
= GSOCK_INVSOCK
;
601 if (getsockname(m_fd
, &addr
, (WX_SOCKLEN_T
*) &size
) < 0)
603 m_error
= GSOCK_IOERR
;
607 /* got a valid address from getsockname, create a GAddress object */
608 address
= GAddress_new();
611 m_error
= GSOCK_MEMERR
;
615 err
= _GAddress_translate_from(address
, &addr
, size
);
616 if (err
!= GSOCK_NOERROR
)
618 GAddress_destroy(address
);
626 GAddress
*GSocket::GetPeer()
630 /* try to get it from the m_peer var */
632 return GAddress_copy(m_peer
);
637 /* Server specific parts */
639 /* GSocket_SetServer:
640 * Sets up this socket as a server. The local address must have been
641 * set with GSocket_SetLocal() before GSocket_SetServer() is called.
642 * Returns GSOCK_NOERROR on success, one of the following otherwise:
645 * GSOCK_INVSOCK - the socket is in use.
646 * GSOCK_INVADDR - the local address has not been set.
647 * GSOCK_IOERR - low-level error.
649 GSocketError
GSocket::SetServer()
655 /* must not be in use */
656 if (m_fd
!= INVALID_SOCKET
)
658 m_error
= GSOCK_INVSOCK
;
659 return GSOCK_INVSOCK
;
662 /* the local addr must have been set */
665 m_error
= GSOCK_INVADDR
;
666 return GSOCK_INVADDR
;
669 /* Initialize all fields */
673 /* Create the socket */
674 m_fd
= socket(m_local
->m_realfamily
, SOCK_STREAM
, 0);
676 if (m_fd
== INVALID_SOCKET
)
678 m_error
= GSOCK_IOERR
;
682 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
684 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
687 ioctl(m_fd
, FIONBIO
, &arg
);
688 gs_gui_functions
->Enable_Events(this);
690 /* allow a socket to re-bind if the socket is in the TIME_WAIT
691 state after being previously closed.
695 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
697 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEPORT
, (const char*)&arg
, sizeof(u_long
));
701 /* Bind to the local address,
702 * retrieve the actual address bound,
703 * and listen up to 5 connections.
705 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
708 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0) ||
709 (listen(m_fd
, 5) != 0))
712 m_error
= GSOCK_IOERR
;
716 return GSOCK_NOERROR
;
719 /* GSocket_WaitConnection:
720 * Waits for an incoming client connection. Returns a pointer to
721 * a GSocket object, or NULL if there was an error, in which case
722 * the last error field will be updated for the calling GSocket.
724 * Error codes (set in the calling GSocket)
725 * GSOCK_INVSOCK - the socket is not valid or not a server.
726 * GSOCK_TIMEDOUT - timeout, no incoming connections.
727 * GSOCK_WOULDBLOCK - the call would block and the socket is nonblocking.
728 * GSOCK_MEMERR - couldn't allocate memory.
729 * GSOCK_IOERR - low-level error.
731 GSocket
*GSocket::WaitConnection()
733 struct sockaddr from
;
734 WX_SOCKLEN_T fromlen
= sizeof(from
);
741 /* If the socket has already been created, we exit immediately */
742 if (m_fd
== INVALID_SOCKET
|| !m_server
)
744 m_error
= GSOCK_INVSOCK
;
748 /* Create a GSocket object for the new connection */
749 connection
= GSocket_new();
753 m_error
= GSOCK_MEMERR
;
757 /* Wait for a connection (with timeout) */
758 if (Input_Timeout() == GSOCK_TIMEDOUT
)
761 /* m_error set by _GSocket_Input_Timeout */
765 connection
->m_fd
= accept(m_fd
, &from
, (WX_SOCKLEN_T
*) &fromlen
);
767 /* Reenable CONNECTION events */
768 Enable(GSOCK_CONNECTION
);
770 if (connection
->m_fd
== INVALID_SOCKET
)
772 if (errno
== EWOULDBLOCK
)
773 m_error
= GSOCK_WOULDBLOCK
;
775 m_error
= GSOCK_IOERR
;
781 /* Initialize all fields */
782 connection
->m_server
= false;
783 connection
->m_stream
= true;
785 /* Setup the peer address field */
786 connection
->m_peer
= GAddress_new();
787 if (!connection
->m_peer
)
790 m_error
= GSOCK_MEMERR
;
794 err
= _GAddress_translate_from(connection
->m_peer
, &from
, fromlen
);
795 if (err
!= GSOCK_NOERROR
)
802 #if defined(__EMX__) || defined(__VISAGECPP__)
803 ioctl(connection
->m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
805 ioctl(connection
->m_fd
, FIONBIO
, &arg
);
807 gs_gui_functions
->Enable_Events(connection
);
812 bool GSocket::SetReusable()
814 /* socket must not be null, and must not be in use/already bound */
815 if (this && m_fd
== INVALID_SOCKET
)
825 /* Client specific parts */
828 * For stream (connection oriented) sockets, GSocket_Connect() tries
829 * to establish a client connection to a server using the peer address
830 * as established with GSocket_SetPeer(). Returns GSOCK_NOERROR if the
831 * connection has been successfully established, or one of the error
832 * codes listed below. Note that for nonblocking sockets, a return
833 * value of GSOCK_WOULDBLOCK doesn't mean a failure. The connection
834 * request can be completed later; you should use GSocket_Select()
835 * to poll for GSOCK_CONNECTION | GSOCK_LOST, or wait for the
836 * corresponding asynchronous events.
838 * For datagram (non connection oriented) sockets, GSocket_Connect()
839 * just sets the peer address established with GSocket_SetPeer() as
840 * default destination.
843 * GSOCK_INVSOCK - the socket is in use or not valid.
844 * GSOCK_INVADDR - the peer address has not been established.
845 * GSOCK_TIMEDOUT - timeout, the connection failed.
846 * GSOCK_WOULDBLOCK - connection in progress (nonblocking sockets only)
847 * GSOCK_MEMERR - couldn't allocate memory.
848 * GSOCK_IOERR - low-level error.
850 GSocketError
GSocket::Connect(GSocketStream stream
)
857 /* Enable CONNECTION events (needed for nonblocking connections) */
858 Enable(GSOCK_CONNECTION
);
860 if (m_fd
!= INVALID_SOCKET
)
862 m_error
= GSOCK_INVSOCK
;
863 return GSOCK_INVSOCK
;
868 m_error
= GSOCK_INVADDR
;
869 return GSOCK_INVADDR
;
872 /* Streamed or dgram socket? */
873 m_stream
= (stream
== GSOCK_STREAMED
);
875 m_establishing
= false;
877 /* Create the socket */
878 m_fd
= socket(m_peer
->m_realfamily
,
879 m_stream
? SOCK_STREAM
: SOCK_DGRAM
, 0);
881 if (m_fd
== INVALID_SOCKET
)
883 m_error
= GSOCK_IOERR
;
887 /* FreeBSD variants can't use MSG_NOSIGNAL, and instead use a socket option */
889 setsockopt(m_fd
, SOL_SOCKET
, SO_NOSIGPIPE
, (const char*)&arg
, sizeof(u_long
));
892 #if defined(__EMX__) || defined(__VISAGECPP__)
893 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
895 ioctl(m_fd
, FIONBIO
, &arg
);
898 // If the reuse flag is set, use the applicable socket reuse flags(s)
901 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char*)&arg
, sizeof(u_long
));
903 setsockopt(m_fd
, SOL_SOCKET
, SO_REUSEPORT
, (const char*)&arg
, sizeof(u_long
));
907 // If a local address has been set, then we need to bind to it before calling connect
908 if (m_local
&& m_local
->m_addr
)
910 bind(m_fd
, m_local
->m_addr
, m_local
->m_len
);
913 /* Connect it to the peer address, with a timeout (see below) */
914 ret
= connect(m_fd
, m_peer
->m_addr
, m_peer
->m_len
);
916 /* We only call Enable_Events if we know we aren't shutting down the socket.
917 * NB: Enable_Events needs to be called whether the socket is blocking or
918 * non-blocking, it just shouldn't be called prior to knowing there is a
919 * connection _if_ blocking sockets are being used.
920 * If connect above returns 0, we are already connected and need to make the
921 * call to Enable_Events now.
924 if (m_non_blocking
|| ret
== 0)
925 gs_gui_functions
->Enable_Events(this);
931 /* If connect failed with EINPROGRESS and the GSocket object
932 * is in blocking mode, we select() for the specified timeout
933 * checking for writability to see if the connection request
936 if ((err
== EINPROGRESS
) && (!m_non_blocking
))
938 if (Output_Timeout() == GSOCK_TIMEDOUT
)
941 /* m_error is set in _GSocket_Output_Timeout */
942 return GSOCK_TIMEDOUT
;
947 SOCKOPTLEN_T len
= sizeof(error
);
949 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*) &error
, &len
);
951 gs_gui_functions
->Enable_Events(this);
954 return GSOCK_NOERROR
;
958 /* If connect failed with EINPROGRESS and the GSocket object
959 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
960 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
961 * this way if the connection completes, a GSOCK_CONNECTION
962 * event will be generated, if enabled.
964 if ((err
== EINPROGRESS
) && (m_non_blocking
))
966 m_establishing
= true;
967 m_error
= GSOCK_WOULDBLOCK
;
968 return GSOCK_WOULDBLOCK
;
971 /* If connect failed with an error other than EINPROGRESS,
972 * then the call to GSocket_Connect has failed.
975 m_error
= GSOCK_IOERR
;
980 return GSOCK_NOERROR
;
983 /* Datagram sockets */
985 /* GSocket_SetNonOriented:
986 * Sets up this socket as a non-connection oriented (datagram) socket.
987 * Before using this function, the local address must have been set
988 * with GSocket_SetLocal(), or the call will fail. Returns GSOCK_NOERROR
989 * on success, or one of the following otherwise.
992 * GSOCK_INVSOCK - the socket is in use.
993 * GSOCK_INVADDR - the local address has not been set.
994 * GSOCK_IOERR - low-level error.
996 GSocketError
GSocket::SetNonOriented()
1002 if (m_fd
!= INVALID_SOCKET
)
1004 m_error
= GSOCK_INVSOCK
;
1005 return GSOCK_INVSOCK
;
1010 m_error
= GSOCK_INVADDR
;
1011 return GSOCK_INVADDR
;
1014 /* Initialize all fields */
1018 /* Create the socket */
1019 m_fd
= socket(m_local
->m_realfamily
, SOCK_DGRAM
, 0);
1021 if (m_fd
== INVALID_SOCKET
)
1023 m_error
= GSOCK_IOERR
;
1026 #if defined(__EMX__) || defined(__VISAGECPP__)
1027 ioctl(m_fd
, FIONBIO
, (char*)&arg
, sizeof(arg
));
1029 ioctl(m_fd
, FIONBIO
, &arg
);
1031 gs_gui_functions
->Enable_Events(this);
1033 /* Bind to the local address,
1034 * and retrieve the actual address bound.
1036 if ((bind(m_fd
, m_local
->m_addr
, m_local
->m_len
) != 0) ||
1039 (WX_SOCKLEN_T
*) &m_local
->m_len
) != 0))
1042 m_error
= GSOCK_IOERR
;
1046 return GSOCK_NOERROR
;
1051 /* Like recv(), send(), ... */
1052 int GSocket::Read(char *buffer
, int size
)
1058 if (m_fd
== INVALID_SOCKET
|| m_server
)
1060 m_error
= GSOCK_INVSOCK
;
1064 /* Disable events during query of socket status */
1065 Disable(GSOCK_INPUT
);
1067 /* If the socket is blocking, wait for data (with a timeout) */
1068 if (Input_Timeout() == GSOCK_TIMEDOUT
) {
1069 m_error
= GSOCK_TIMEDOUT
;
1070 /* Don't return here immediately, otherwise socket events would not be
1078 ret
= Recv_Stream(buffer
, size
);
1080 ret
= Recv_Dgram(buffer
, size
);
1082 /* If recv returned zero, then the connection is lost, and errno is not set.
1083 * Otherwise, recv has returned an error (-1), in which case we have lost the
1084 * socket only if errno does _not_ indicate that there may be more data to read.
1087 m_error
= GSOCK_IOERR
;
1090 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1091 m_error
= GSOCK_WOULDBLOCK
;
1093 m_error
= GSOCK_IOERR
;
1097 /* Enable events again now that we are done processing */
1098 Enable(GSOCK_INPUT
);
1103 int GSocket::Write(const char *buffer
, int size
)
1109 GSocket_Debug(( "GSocket_Write #1, size %d\n", size
));
1111 if (m_fd
== INVALID_SOCKET
|| m_server
)
1113 m_error
= GSOCK_INVSOCK
;
1117 GSocket_Debug(( "GSocket_Write #2, size %d\n", size
));
1119 /* If the socket is blocking, wait for writability (with a timeout) */
1120 if (Output_Timeout() == GSOCK_TIMEDOUT
)
1123 GSocket_Debug(( "GSocket_Write #3, size %d\n", size
));
1125 /* Write the data */
1127 ret
= Send_Stream(buffer
, size
);
1129 ret
= Send_Dgram(buffer
, size
);
1131 GSocket_Debug(( "GSocket_Write #4, size %d\n", size
));
1135 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
))
1137 m_error
= GSOCK_WOULDBLOCK
;
1138 GSocket_Debug(( "GSocket_Write error WOULDBLOCK\n" ));
1142 m_error
= GSOCK_IOERR
;
1143 GSocket_Debug(( "GSocket_Write error IOERR\n" ));
1146 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
1147 * in MSW). Once the first OUTPUT event is received, users can assume
1148 * that the socket is writable until a read operation fails. Only then
1149 * will further OUTPUT events be posted.
1151 Enable(GSOCK_OUTPUT
);
1156 GSocket_Debug(( "GSocket_Write #5, size %d ret %d\n", size
, ret
));
1162 * Polls the socket to determine its status. This function will
1163 * check for the events specified in the 'flags' parameter, and
1164 * it will return a mask indicating which operations can be
1165 * performed. This function won't block, regardless of the
1166 * mode (blocking | nonblocking) of the socket.
1168 GSocketEventFlags
GSocket::Select(GSocketEventFlags flags
)
1170 if (!gs_gui_functions
->CanUseEventLoop())
1173 GSocketEventFlags result
= 0;
1182 return (GSOCK_LOST_FLAG
& flags
);
1184 /* Do not use a static struct, Linux can garble it */
1185 tv
.tv_sec
= m_timeout
/ 1000;
1186 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1188 wxFD_ZERO(&readfds
);
1189 wxFD_ZERO(&writefds
);
1190 wxFD_ZERO(&exceptfds
);
1191 wxFD_SET(m_fd
, &readfds
);
1192 if (flags
& GSOCK_OUTPUT_FLAG
|| flags
& GSOCK_CONNECTION_FLAG
)
1193 wxFD_SET(m_fd
, &writefds
);
1194 wxFD_SET(m_fd
, &exceptfds
);
1196 /* Check 'sticky' CONNECTION flag first */
1197 result
|= (GSOCK_CONNECTION_FLAG
& m_detected
);
1199 /* If we have already detected a LOST event, then don't try
1200 * to do any further processing.
1202 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1204 m_establishing
= false;
1206 return (GSOCK_LOST_FLAG
& flags
);
1209 /* Try select now */
1210 if (select(m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
) <= 0)
1212 /* What to do here? */
1213 return (result
& flags
);
1216 /* Check for readability */
1217 if (wxFD_ISSET(m_fd
, &readfds
))
1221 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1225 result
|= GSOCK_INPUT_FLAG
;
1229 if (m_server
&& m_stream
)
1231 result
|= GSOCK_CONNECTION_FLAG
;
1232 m_detected
|= GSOCK_CONNECTION_FLAG
;
1234 /* If recv returned zero, then the connection is lost, and errno is not set.
1235 * Otherwise, recv has returned an error (-1), in which case we have lost the
1236 * socket only if errno does _not_ indicate that there may be more data to read.
1238 else if (num
== 0 ||
1239 (errno
!= EWOULDBLOCK
) && (errno
!= EAGAIN
) && (errno
!= EINTR
))
1241 m_detected
= GSOCK_LOST_FLAG
;
1242 m_establishing
= false;
1244 /* LOST event: Abort any further processing */
1245 return (GSOCK_LOST_FLAG
& flags
);
1250 /* Check for writability */
1251 if (wxFD_ISSET(m_fd
, &writefds
))
1253 if (m_establishing
&& !m_server
)
1256 SOCKOPTLEN_T len
= sizeof(error
);
1258 m_establishing
= false;
1260 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1264 m_detected
= GSOCK_LOST_FLAG
;
1266 /* LOST event: Abort any further processing */
1267 return (GSOCK_LOST_FLAG
& flags
);
1271 result
|= GSOCK_CONNECTION_FLAG
;
1272 m_detected
|= GSOCK_CONNECTION_FLAG
;
1277 result
|= GSOCK_OUTPUT_FLAG
;
1281 /* Check for exceptions and errors (is this useful in Unices?) */
1282 if (wxFD_ISSET(m_fd
, &exceptfds
))
1284 m_establishing
= false;
1285 m_detected
= GSOCK_LOST_FLAG
;
1287 /* LOST event: Abort any further processing */
1288 return (GSOCK_LOST_FLAG
& flags
);
1291 return (result
& flags
);
1297 return flags
& m_detected
;
1303 /* GSocket_SetNonBlocking:
1304 * Sets the socket to non-blocking mode. All IO calls will return
1307 void GSocket::SetNonBlocking(bool non_block
)
1311 GSocket_Debug( ("GSocket_SetNonBlocking: %d\n", (int)non_block
) );
1313 m_non_blocking
= non_block
;
1316 /* GSocket_SetTimeout:
1317 * Sets the timeout for blocking calls. Time is expressed in
1320 void GSocket::SetTimeout(unsigned long millisec
)
1324 m_timeout
= millisec
;
1327 /* GSocket_GetError:
1328 * Returns the last error occurred for this socket. Note that successful
1329 * operations do not clear this back to GSOCK_NOERROR, so use it only
1332 GSocketError WXDLLIMPEXP_NET
GSocket::GetError()
1342 * There is data to be read in the input buffer. If, after a read
1343 * operation, there is still data available, the callback function will
1346 * The socket is available for writing. That is, the next write call
1347 * won't block. This event is generated only once, when the connection is
1348 * first established, and then only if a call failed with GSOCK_WOULDBLOCK,
1349 * when the output buffer empties again. This means that the app should
1350 * assume that it can write since the first OUTPUT event, and no more
1351 * OUTPUT events will be generated unless an error occurs.
1353 * Connection successfully established, for client sockets, or incoming
1354 * client connection, for server sockets. Wait for this event (also watch
1355 * out for GSOCK_LOST) after you issue a nonblocking GSocket_Connect() call.
1357 * The connection is lost (or a connection request failed); this could
1358 * be due to a failure, or due to the peer closing it gracefully.
1361 /* GSocket_SetCallback:
1362 * Enables the callbacks specified by 'flags'. Note that 'flags'
1363 * may be a combination of flags OR'ed toghether, so the same
1364 * callback function can be made to accept different events.
1365 * The callback function must have the following prototype:
1367 * void function(GSocket *socket, GSocketEvent event, char *cdata)
1369 void GSocket::SetCallback(GSocketEventFlags flags
,
1370 GSocketCallback callback
, char *cdata
)
1376 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1378 if ((flags
& (1 << count
)) != 0)
1380 m_cbacks
[count
] = callback
;
1381 m_data
[count
] = cdata
;
1386 /* GSocket_UnsetCallback:
1387 * Disables all callbacks specified by 'flags', which may be a
1388 * combination of flags OR'ed toghether.
1390 void GSocket::UnsetCallback(GSocketEventFlags flags
)
1396 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
1398 if ((flags
& (1 << count
)) != 0)
1400 m_cbacks
[count
] = NULL
;
1401 m_data
[count
] = NULL
;
1406 GSocketError
GSocket::GetSockOpt(int level
, int optname
,
1407 void *optval
, int *optlen
)
1409 if (getsockopt(m_fd
, level
, optname
, (char*)optval
, (SOCKOPTLEN_T
*)optlen
) == 0)
1410 return GSOCK_NOERROR
;
1412 return GSOCK_OPTERR
;
1415 GSocketError
GSocket::SetSockOpt(int level
, int optname
,
1416 const void *optval
, int optlen
)
1418 if (setsockopt(m_fd
, level
, optname
, (const char*)optval
, optlen
) == 0)
1419 return GSOCK_NOERROR
;
1421 return GSOCK_OPTERR
;
1424 #define CALL_CALLBACK(socket, event) { \
1425 socket->Disable(event); \
1426 if (socket->m_cbacks[event]) \
1427 socket->m_cbacks[event](socket, event, socket->m_data[event]); \
1431 void GSocket::Enable(GSocketEvent event
)
1433 m_detected
&= ~(1 << event
);
1434 gs_gui_functions
->Install_Callback(this, event
);
1437 void GSocket::Disable(GSocketEvent event
)
1439 m_detected
|= (1 << event
);
1440 gs_gui_functions
->Uninstall_Callback(this, event
);
1443 /* _GSocket_Input_Timeout:
1444 * For blocking sockets, wait until data is available or
1445 * until timeout ellapses.
1447 GSocketError
GSocket::Input_Timeout()
1453 /* Linux select() will overwrite the struct on return */
1454 tv
.tv_sec
= (m_timeout
/ 1000);
1455 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1457 if (!m_non_blocking
)
1459 wxFD_ZERO(&readfds
);
1460 wxFD_SET(m_fd
, &readfds
);
1461 ret
= select(m_fd
+ 1, &readfds
, NULL
, NULL
, &tv
);
1464 GSocket_Debug(( "GSocket_Input_Timeout, select returned 0\n" ));
1465 m_error
= GSOCK_TIMEDOUT
;
1466 return GSOCK_TIMEDOUT
;
1471 GSocket_Debug(( "GSocket_Input_Timeout, select returned -1\n" ));
1472 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1473 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1474 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1475 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1476 m_error
= GSOCK_TIMEDOUT
;
1477 return GSOCK_TIMEDOUT
;
1481 return GSOCK_NOERROR
;
1484 /* _GSocket_Output_Timeout:
1485 * For blocking sockets, wait until data can be sent without
1486 * blocking or until timeout ellapses.
1488 GSocketError
GSocket::Output_Timeout()
1494 /* Linux select() will overwrite the struct on return */
1495 tv
.tv_sec
= (m_timeout
/ 1000);
1496 tv
.tv_usec
= (m_timeout
% 1000) * 1000;
1498 GSocket_Debug( ("m_non_blocking has: %d\n", (int)m_non_blocking
) );
1500 if (!m_non_blocking
)
1502 wxFD_ZERO(&writefds
);
1503 wxFD_SET(m_fd
, &writefds
);
1504 ret
= select(m_fd
+ 1, NULL
, &writefds
, NULL
, &tv
);
1507 GSocket_Debug(( "GSocket_Output_Timeout, select returned 0\n" ));
1508 m_error
= GSOCK_TIMEDOUT
;
1509 return GSOCK_TIMEDOUT
;
1514 GSocket_Debug(( "GSocket_Output_Timeout, select returned -1\n" ));
1515 if (errno
== EBADF
) { GSocket_Debug(( "Invalid file descriptor\n" )); }
1516 if (errno
== EINTR
) { GSocket_Debug(( "A non blocked signal was caught\n" )); }
1517 if (errno
== EINVAL
) { GSocket_Debug(( "The highest number descriptor is negative\n" )); }
1518 if (errno
== ENOMEM
) { GSocket_Debug(( "Not enough memory\n" )); }
1519 m_error
= GSOCK_TIMEDOUT
;
1520 return GSOCK_TIMEDOUT
;
1523 if ( ! wxFD_ISSET(m_fd
, &writefds
) )
1525 GSocket_Debug(( "GSocket_Output_Timeout is buggy!\n" ));
1529 GSocket_Debug(( "GSocket_Output_Timeout seems correct\n" ));
1534 GSocket_Debug(( "GSocket_Output_Timeout, didn't try select!\n" ));
1537 return GSOCK_NOERROR
;
1540 int GSocket::Recv_Stream(char *buffer
, int size
)
1545 ret
= recv(m_fd
, buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1547 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1552 int GSocket::Recv_Dgram(char *buffer
, int size
)
1554 struct sockaddr from
;
1555 WX_SOCKLEN_T fromlen
= sizeof(from
);
1559 fromlen
= sizeof(from
);
1563 ret
= recvfrom(m_fd
, buffer
, size
, 0, &from
, (WX_SOCKLEN_T
*) &fromlen
);
1565 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1570 /* Translate a system address into a GSocket address */
1573 m_peer
= GAddress_new();
1576 m_error
= GSOCK_MEMERR
;
1581 err
= _GAddress_translate_from(m_peer
, &from
, fromlen
);
1582 if (err
!= GSOCK_NOERROR
)
1584 GAddress_destroy(m_peer
);
1593 int GSocket::Send_Stream(const char *buffer
, int size
)
1601 ret
= send(m_fd
, (char *)buffer
, size
, GSOCKET_MSG_NOSIGNAL
);
1603 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1610 int GSocket::Send_Dgram(const char *buffer
, int size
)
1612 struct sockaddr
*addr
;
1618 m_error
= GSOCK_INVADDR
;
1622 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
1623 if (err
!= GSOCK_NOERROR
)
1633 ret
= sendto(m_fd
, (char *)buffer
, size
, 0, addr
, len
);
1635 while (ret
== -1 && errno
== EINTR
); /* Loop until not interrupted */
1639 /* Frees memory allocated from _GAddress_translate_to */
1645 void GSocket::Detected_Read()
1649 /* Safeguard against straggling call to Detected_Read */
1650 if (m_fd
== INVALID_SOCKET
)
1655 /* If we have already detected a LOST event, then don't try
1656 * to do any further processing.
1658 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1660 m_establishing
= false;
1662 CALL_CALLBACK(this, GSOCK_LOST
);
1667 int num
= recv(m_fd
, &c
, 1, MSG_PEEK
| GSOCKET_MSG_NOSIGNAL
);
1671 CALL_CALLBACK(this, GSOCK_INPUT
);
1675 if (m_server
&& m_stream
)
1677 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1681 /* Do not throw a lost event in cases where the socket isn't really lost */
1682 if ((errno
== EWOULDBLOCK
) || (errno
== EAGAIN
) || (errno
== EINTR
))
1684 CALL_CALLBACK(this, GSOCK_INPUT
);
1688 CALL_CALLBACK(this, GSOCK_LOST
);
1695 void GSocket::Detected_Write()
1697 /* If we have already detected a LOST event, then don't try
1698 * to do any further processing.
1700 if ((m_detected
& GSOCK_LOST_FLAG
) != 0)
1702 m_establishing
= false;
1704 CALL_CALLBACK(this, GSOCK_LOST
);
1709 if (m_establishing
&& !m_server
)
1712 SOCKOPTLEN_T len
= sizeof(error
);
1714 m_establishing
= false;
1716 getsockopt(m_fd
, SOL_SOCKET
, SO_ERROR
, (char*)&error
, &len
);
1720 CALL_CALLBACK(this, GSOCK_LOST
);
1725 CALL_CALLBACK(this, GSOCK_CONNECTION
);
1726 /* We have to fire this event by hand because CONNECTION (for clients)
1727 * and OUTPUT are internally the same and we just disabled CONNECTION
1728 * events with the above macro.
1730 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1735 CALL_CALLBACK(this, GSOCK_OUTPUT
);
1739 /* Compatibility functions for GSocket */
1740 GSocket
*GSocket_new(void)
1742 GSocket
*newsocket
= new GSocket();
1743 if (newsocket
->IsOk())
1752 * -------------------------------------------------------------------------
1754 * -------------------------------------------------------------------------
1757 /* CHECK_ADDRESS verifies that the current address family is either
1758 * GSOCK_NOFAMILY or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it
1759 * initalizes it to be a GSOCK_*family*. In other cases, it returns
1760 * an appropiate error code.
1762 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
1764 #define CHECK_ADDRESS(address, family) \
1766 if (address->m_family == GSOCK_NOFAMILY) \
1767 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1768 return address->m_error; \
1769 if (address->m_family != GSOCK_##family) \
1771 address->m_error = GSOCK_INVADDR; \
1772 return GSOCK_INVADDR; \
1776 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
1778 if (address->m_family == GSOCK_NOFAMILY) \
1779 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1781 if (address->m_family != GSOCK_##family) \
1783 address->m_error = GSOCK_INVADDR; \
1789 GAddress
*GAddress_new(void)
1793 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1796 address
->m_family
= GSOCK_NOFAMILY
;
1797 address
->m_addr
= NULL
;
1803 GAddress
*GAddress_copy(GAddress
*address
)
1807 assert(address
!= NULL
);
1809 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1812 memcpy(addr2
, address
, sizeof(GAddress
));
1814 if (address
->m_addr
&& address
->m_len
> 0)
1816 addr2
->m_addr
= (struct sockaddr
*)malloc(addr2
->m_len
);
1817 if (addr2
->m_addr
== NULL
)
1822 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1828 void GAddress_destroy(GAddress
*address
)
1830 assert(address
!= NULL
);
1832 if (address
->m_addr
)
1833 free(address
->m_addr
);
1838 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1840 assert(address
!= NULL
);
1842 address
->m_family
= type
;
1845 GAddressType
GAddress_GetFamily(GAddress
*address
)
1847 assert(address
!= NULL
);
1849 return address
->m_family
;
1852 GSocketError
_GAddress_translate_from(GAddress
*address
,
1853 struct sockaddr
*addr
, int len
)
1855 address
->m_realfamily
= addr
->sa_family
;
1856 switch (addr
->sa_family
)
1859 address
->m_family
= GSOCK_INET
;
1862 address
->m_family
= GSOCK_UNIX
;
1866 address
->m_family
= GSOCK_INET6
;
1871 address
->m_error
= GSOCK_INVOP
;
1876 if (address
->m_addr
)
1877 free(address
->m_addr
);
1879 address
->m_len
= len
;
1880 address
->m_addr
= (struct sockaddr
*)malloc(len
);
1882 if (address
->m_addr
== NULL
)
1884 address
->m_error
= GSOCK_MEMERR
;
1885 return GSOCK_MEMERR
;
1888 memcpy(address
->m_addr
, addr
, len
);
1890 return GSOCK_NOERROR
;
1893 GSocketError
_GAddress_translate_to(GAddress
*address
,
1894 struct sockaddr
**addr
, int *len
)
1896 if (!address
->m_addr
)
1898 address
->m_error
= GSOCK_INVADDR
;
1899 return GSOCK_INVADDR
;
1902 *len
= address
->m_len
;
1903 *addr
= (struct sockaddr
*)malloc(address
->m_len
);
1906 address
->m_error
= GSOCK_MEMERR
;
1907 return GSOCK_MEMERR
;
1910 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1911 return GSOCK_NOERROR
;
1915 * -------------------------------------------------------------------------
1916 * Internet address family
1917 * -------------------------------------------------------------------------
1920 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1922 address
->m_len
= sizeof(struct sockaddr_in
);
1923 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1924 if (address
->m_addr
== NULL
)
1926 address
->m_error
= GSOCK_MEMERR
;
1927 return GSOCK_MEMERR
;
1930 address
->m_family
= GSOCK_INET
;
1931 address
->m_realfamily
= PF_INET
;
1932 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1933 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1935 return GSOCK_NOERROR
;
1938 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1941 struct in_addr
*addr
;
1943 assert(address
!= NULL
);
1945 CHECK_ADDRESS(address
, INET
);
1947 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1949 /* If it is a numeric host name, convert it now */
1950 #if defined(HAVE_INET_ATON)
1951 if (inet_aton(hostname
, addr
) == 0)
1953 #elif defined(HAVE_INET_ADDR)
1954 if ( (addr
->s_addr
= inet_addr(hostname
)) == (unsigned)-1 )
1957 /* Use gethostbyname by default */
1959 int val
= 1; /* VA doesn't like constants in conditional expressions */
1964 struct in_addr
*array_addr
;
1966 /* It is a real name, we solve it */
1968 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
1969 struct hostent_data buffer
;
1974 he
= wxGethostbyname_r(hostname
, &h
, (void*)&buffer
, sizeof(buffer
), &err
);
1977 /* Reset to invalid address */
1978 addr
->s_addr
= INADDR_NONE
;
1979 address
->m_error
= GSOCK_NOHOST
;
1980 return GSOCK_NOHOST
;
1983 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1984 addr
->s_addr
= array_addr
[0].s_addr
;
1987 return GSOCK_NOERROR
;
1990 GSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1992 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1995 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1996 unsigned long hostaddr
)
1998 struct in_addr
*addr
;
2000 assert(address
!= NULL
);
2002 CHECK_ADDRESS(address
, INET
);
2004 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
2005 addr
->s_addr
= htonl(hostaddr
);
2007 return GSOCK_NOERROR
;
2010 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
2011 const char *protocol
)
2014 struct sockaddr_in
*addr
;
2016 assert(address
!= NULL
);
2017 CHECK_ADDRESS(address
, INET
);
2021 address
->m_error
= GSOCK_INVPORT
;
2022 return GSOCK_INVPORT
;
2025 #if defined(HAVE_FUNC_GETSERVBYNAME_R_4)
2026 struct servent_data buffer
;
2030 struct servent serv
;
2031 se
= wxGetservbyname_r(port
, protocol
, &serv
,
2032 (void*)&buffer
, sizeof(buffer
));
2035 /* the cast to int suppresses compiler warnings about subscript having the
2037 if (isdigit((int)port
[0]))
2041 port_int
= atoi(port
);
2042 addr
= (struct sockaddr_in
*)address
->m_addr
;
2043 addr
->sin_port
= htons(port_int
);
2044 return GSOCK_NOERROR
;
2047 address
->m_error
= GSOCK_INVPORT
;
2048 return GSOCK_INVPORT
;
2051 addr
= (struct sockaddr_in
*)address
->m_addr
;
2052 addr
->sin_port
= se
->s_port
;
2054 return GSOCK_NOERROR
;
2057 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
2059 struct sockaddr_in
*addr
;
2061 assert(address
!= NULL
);
2062 CHECK_ADDRESS(address
, INET
);
2064 addr
= (struct sockaddr_in
*)address
->m_addr
;
2065 addr
->sin_port
= htons(port
);
2067 return GSOCK_NOERROR
;
2070 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
2074 struct sockaddr_in
*addr
;
2076 assert(address
!= NULL
);
2077 CHECK_ADDRESS(address
, INET
);
2079 addr
= (struct sockaddr_in
*)address
->m_addr
;
2080 addr_buf
= (char *)&(addr
->sin_addr
);
2082 struct hostent temphost
;
2083 #if defined(HAVE_FUNC_GETHOSTBYNAME_R_3)
2084 struct hostent_data buffer
;
2089 he
= wxGethostbyaddr_r(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
, &temphost
,
2090 (void*)&buffer
, sizeof(buffer
), &err
);
2093 address
->m_error
= GSOCK_NOHOST
;
2094 return GSOCK_NOHOST
;
2097 strncpy(hostname
, he
->h_name
, sbuf
);
2099 return GSOCK_NOERROR
;
2102 unsigned long GAddress_INET_GetHostAddress(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
;
2111 return ntohl(addr
->sin_addr
.s_addr
);
2114 unsigned short GAddress_INET_GetPort(GAddress
*address
)
2116 struct sockaddr_in
*addr
;
2118 assert(address
!= NULL
);
2119 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
2121 addr
= (struct sockaddr_in
*)address
->m_addr
;
2122 return ntohs(addr
->sin_port
);
2126 * -------------------------------------------------------------------------
2127 * Unix address family
2128 * -------------------------------------------------------------------------
2131 #ifndef __VISAGECPP__
2132 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
2134 address
->m_len
= sizeof(struct sockaddr_un
);
2135 address
->m_addr
= (struct sockaddr
*)malloc(address
->m_len
);
2136 if (address
->m_addr
== NULL
)
2138 address
->m_error
= GSOCK_MEMERR
;
2139 return GSOCK_MEMERR
;
2142 address
->m_family
= GSOCK_UNIX
;
2143 address
->m_realfamily
= PF_UNIX
;
2144 ((struct sockaddr_un
*)address
->m_addr
)->sun_family
= AF_UNIX
;
2145 ((struct sockaddr_un
*)address
->m_addr
)->sun_path
[0] = 0;
2147 return GSOCK_NOERROR
;
2150 #define UNIX_SOCK_PATHLEN (sizeof(addr->sun_path)/sizeof(addr->sun_path[0]))
2152 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
2154 struct sockaddr_un
*addr
;
2156 assert(address
!= NULL
);
2158 CHECK_ADDRESS(address
, UNIX
);
2160 addr
= ((struct sockaddr_un
*)address
->m_addr
);
2161 strncpy(addr
->sun_path
, path
, UNIX_SOCK_PATHLEN
);
2162 addr
->sun_path
[UNIX_SOCK_PATHLEN
- 1] = '\0';
2164 return GSOCK_NOERROR
;
2167 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
2169 struct sockaddr_un
*addr
;
2171 assert(address
!= NULL
);
2172 CHECK_ADDRESS(address
, UNIX
);
2174 addr
= (struct sockaddr_un
*)address
->m_addr
;
2176 strncpy(path
, addr
->sun_path
, sbuf
);
2178 return GSOCK_NOERROR
;
2180 #endif /* !defined(__VISAGECPP__) */
2181 #endif /* wxUSE_SOCKETS || defined(__GSOCKET_STANDALONE__) */