1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/sockmsw.cpp
3 // Purpose: MSW-specific socket code
4 // Authors: Guilhem Lavaux, Guillermo Rodriguez Garcia
6 // Copyright: (C) 1999-1997, Guilhem Lavaux
7 // (C) 1999-2000, Guillermo Rodriguez Garcia
8 // (C) 2008 Vadim Zeitlin
10 // License: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
14 // For compilers that support precompilation, includes "wx.h".
15 #include "wx/wxprec.h"
23 /* including rasasync.h (included from windows.h itself included from
24 * wx/setup.h and/or winsock.h results in this warning for
25 * RPCNOTIFICATION_ROUTINE
28 # pragma warning(disable:4115) /* named type definition in parentheses */
31 #include "wx/private/socket.h"
32 #include "wx/apptrait.h"
33 #include "wx/thread.h"
35 extern "C" WXDLLIMPEXP_BASE HINSTANCE
wxGetInstance();
36 #define INSTANCE wxGetInstance()
42 * As WSAAsyncSelect is not present on WinCE, it now uses WSACreateEvent,
43 * WSAEventSelect, WSAWaitForMultipleEvents and WSAEnumNetworkEvents. When
44 * enabling eventhandling for a socket a new thread it created that keeps track
45 * of the events and posts a messageto the hidden window to use the standard
48 #include "wx/msw/wince/net.h"
49 #include "wx/hashmap.h"
50 WX_DECLARE_HASH_MAP(int,bool,wxIntegerHash
,wxIntegerEqual
,SocketHash
);
53 #define isdigit(x) (x > 47 && x < 58)
55 #include "wx/msw/wince/net.h"
60 # pragma warning(default:4115) /* named type definition in parentheses */
63 #define CLASSNAME TEXT("_wxSocket_Internal_Window_Class")
65 /* implemented in utils.cpp */
66 extern "C" WXDLLIMPEXP_BASE HWND
67 wxCreateHiddenWindow(LPCTSTR
*pclassname
, LPCTSTR classname
, WNDPROC wndproc
);
69 /* Maximum number of different wxSocket objects at a given time.
70 * This value can be modified at will, but it CANNOT be greater
71 * than (0x7FFF - WM_USER + 1)
73 #define MAXSOCKETS 1024
75 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
76 #error "MAXSOCKETS is too big!"
80 typedef int (PASCAL
*WSAAsyncSelectFunc
)(SOCKET
,HWND
,u_int
,long);
82 /* Typedef the needed function prototypes and the WSANETWORKEVENTS structure
84 typedef struct _WSANETWORKEVENTS
{
87 } WSANETWORKEVENTS
, FAR
* LPWSANETWORKEVENTS
;
88 typedef HANDLE (PASCAL
*WSACreateEventFunc
)();
89 typedef int (PASCAL
*WSAEventSelectFunc
)(SOCKET
,HANDLE
,long);
90 typedef int (PASCAL
*WSAWaitForMultipleEventsFunc
)(long,HANDLE
,BOOL
,long,BOOL
);
91 typedef int (PASCAL
*WSAEnumNetworkEventsFunc
)(SOCKET
,HANDLE
,LPWSANETWORKEVENTS
);
94 LRESULT CALLBACK
wxSocket_Internal_WinProc(HWND
, UINT
, WPARAM
, LPARAM
);
96 /* Global variables */
99 wxCRIT_SECT_DECLARE_MEMBER(gs_critical
);
100 static wxSocketImplMSW
*socketList
[MAXSOCKETS
];
101 static int firstAvailable
;
104 static WSAAsyncSelectFunc gs_WSAAsyncSelect
= NULL
;
106 static SocketHash socketHash
;
107 static unsigned int currSocket
;
108 HANDLE hThread
[MAXSOCKETS
];
109 static WSACreateEventFunc gs_WSACreateEvent
= NULL
;
110 static WSAEventSelectFunc gs_WSAEventSelect
= NULL
;
111 static WSAWaitForMultipleEventsFunc gs_WSAWaitForMultipleEvents
= NULL
;
112 static WSAEnumNetworkEventsFunc gs_WSAEnumNetworkEvents
= NULL
;
113 /* This structure will be used to pass data on to the thread that handles socket events.
115 typedef struct thread_data
{
117 unsigned long msgnumber
;
119 unsigned long lEvent
;
123 static HMODULE gs_wsock32dll
= 0;
127 /* This thread handles socket events on WinCE using WSAEventSelect() as WSAAsyncSelect is not supported.
128 * When an event occures for the socket, it is checked what kind of event happend and the correct message gets posted
129 * so that the hidden window can handle it as it would in other MSW builds.
131 DWORD WINAPI
SocketThread(LPVOID data
)
133 WSANETWORKEVENTS NetworkEvents
;
134 thread_data
* d
= (thread_data
*)data
;
136 HANDLE NetworkEvent
= gs_WSACreateEvent();
137 gs_WSAEventSelect(d
->fd
, NetworkEvent
, d
->lEvent
);
139 while(socketHash
[d
->fd
] == true)
141 if ((gs_WSAWaitForMultipleEvents(1, &NetworkEvent
, FALSE
,INFINITE
, FALSE
)) == WAIT_FAILED
)
143 printf("WSAWaitForMultipleEvents failed with error %d\n", WSAGetLastError());
146 if (gs_WSAEnumNetworkEvents(d
->fd
,NetworkEvent
, &NetworkEvents
) == SOCKET_ERROR
)
148 printf("WSAEnumNetworkEvents failed with error %d\n", WSAGetLastError());
152 long flags
= NetworkEvents
.lNetworkEvents
;
154 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_READ
);
155 if (flags
& FD_WRITE
)
156 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_WRITE
);
158 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_OOB
);
159 if (flags
& FD_ACCEPT
)
160 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_ACCEPT
);
161 if (flags
& FD_CONNECT
)
162 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CONNECT
);
163 if (flags
& FD_CLOSE
)
164 ::PostMessage(d
->hEvtWin
, d
->msgnumber
,d
->fd
, FD_CLOSE
);
167 gs_WSAEventSelect(d
->fd
, NetworkEvent
, 0);
173 // ----------------------------------------------------------------------------
174 // MSW implementation of wxSocketManager
175 // ----------------------------------------------------------------------------
177 class wxSocketMSWManager
: public wxSocketManager
180 virtual bool OnInit();
181 virtual void OnExit();
183 virtual wxSocketImpl
*CreateSocket(wxSocketBase
& wxsocket
)
185 return new wxSocketImplMSW(wxsocket
);
187 virtual void Install_Callback(wxSocketImpl
*socket
, wxSocketNotify event
);
188 virtual void Uninstall_Callback(wxSocketImpl
*socket
, wxSocketNotify event
);
191 bool wxSocketMSWManager
::OnInit()
193 static LPCTSTR pclassname
= NULL
;
196 /* Create internal window for event notifications */
197 hWin
= wxCreateHiddenWindow(&pclassname
, CLASSNAME
, wxSocket_Internal_WinProc
);
201 /* Initialize socket list */
202 for (i
= 0; i
< MAXSOCKETS
; i
++)
204 socketList
[i
] = NULL
;
208 /* Load WSAAsyncSelect from wsock32.dll (we don't link against it
209 statically to avoid dependency on wsock32.dll for apps that don't use
212 gs_wsock32dll
= LoadLibrary(wxT("wsock32.dll"));
215 gs_WSAAsyncSelect
=(WSAAsyncSelectFunc
)GetProcAddress(gs_wsock32dll
,
217 if (!gs_WSAAsyncSelect
)
220 /* On WinCE we load ws2.dll which will provide the needed functions.
222 gs_wsock32dll
= LoadLibrary(wxT("ws2.dll"));
225 gs_WSAEventSelect
=(WSAEventSelectFunc
)GetProcAddress(gs_wsock32dll
,
226 wxT("WSAEventSelect"));
227 if (!gs_WSAEventSelect
)
230 gs_WSACreateEvent
=(WSACreateEventFunc
)GetProcAddress(gs_wsock32dll
,
231 wxT("WSACreateEvent"));
232 if (!gs_WSACreateEvent
)
235 gs_WSAWaitForMultipleEvents
=(WSAWaitForMultipleEventsFunc
)GetProcAddress(gs_wsock32dll
,
236 wxT("WSAWaitForMultipleEvents"));
237 if (!gs_WSAWaitForMultipleEvents
)
240 gs_WSAEnumNetworkEvents
=(WSAEnumNetworkEventsFunc
)GetProcAddress(gs_wsock32dll
,
241 wxT("WSAEnumNetworkEvents"));
242 if (!gs_WSAEnumNetworkEvents
)
248 // finally initialize WinSock
250 return WSAStartup((1 << 8) | 1, &wsaData
) == 0;
253 void wxSocketMSWManager
::OnExit()
256 /* Delete the threads here */
257 for(unsigned int i
=0; i
< currSocket
; i
++)
258 CloseHandle(hThread
[i
]);
260 /* Destroy internal window */
262 UnregisterClass(CLASSNAME
, INSTANCE
);
264 /* Unlock wsock32.dll */
267 FreeLibrary(gs_wsock32dll
);
274 /* Per-socket GUI initialization / cleanup */
276 wxSocketImplMSW
::wxSocketImplMSW(wxSocketBase
& wxsocket
)
277 : wxSocketImpl(wxsocket
)
279 /* Allocate a new message number for this socket */
280 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
282 int i
= firstAvailable
;
283 while (socketList
[i
] != NULL
)
285 i
= (i
+ 1) % MAXSOCKETS
;
287 if (i
== firstAvailable
) /* abort! */
289 m_msgnumber
= 0; // invalid
293 socketList
[i
] = this;
294 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
295 m_msgnumber
= (i
+ WM_USER
);
298 wxSocketImplMSW
::~wxSocketImplMSW()
300 /* Remove the socket from the list */
301 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
305 // we need to remove any pending messages for this socket to avoid having
306 // them sent to a new socket which could reuse the same message number as
307 // soon as we destroy this one
309 while ( ::PeekMessage(&msg
, hWin
, m_msgnumber
, m_msgnumber
, PM_REMOVE
) )
312 socketList
[m_msgnumber
- WM_USER
] = NULL
;
314 //else: the socket has never been created successfully
317 /* Windows proc for asynchronous event handling */
319 LRESULT CALLBACK
wxSocket_Internal_WinProc(HWND hWnd
,
324 if ( uMsg
< WM_USER
|| uMsg
> (WM_USER
+ MAXSOCKETS
- 1))
325 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
327 wxSocketImplMSW
*socket
;
328 wxSocketNotify event
;
330 wxCRIT_SECT_LOCKER(lock
, gs_critical
);
332 socket
= socketList
[(uMsg
- WM_USER
)];
333 event
= (wxSocketNotify
) -1;
335 /* Check that the socket still exists (it has not been
336 * destroyed) and for safety, check that the m_fd field
337 * is what we expect it to be.
339 if ((socket
!= NULL
) && ((WPARAM
)socket
->m_fd
== wParam
))
341 switch WSAGETSELECTEVENT(lParam
)
343 case FD_READ
: event
= wxSOCKET_INPUT
; break;
344 case FD_WRITE
: event
= wxSOCKET_OUTPUT
; break;
345 case FD_ACCEPT
: event
= wxSOCKET_CONNECTION
; break;
348 if (WSAGETSELECTERROR(lParam
) != 0)
349 event
= wxSOCKET_LOST
;
351 event
= wxSOCKET_CONNECTION
;
354 case FD_CLOSE
: event
= wxSOCKET_LOST
; break;
359 if (event
== wxSOCKET_LOST
)
360 socket
->m_detected
= wxSOCKET_LOST_FLAG
;
362 socket
->m_detected
|= (1 << event
);
365 } // unlock gs_critical
368 socket
->NotifyOnStateChange(event
);
374 * Enable all event notifications; we need to be notified of all
375 * events for internal processing, but we will only notify users
376 * when an appropriate callback function has been installed.
378 void wxSocketMSWManager
::Install_Callback(wxSocketImpl
*socket_
,
379 wxSocketNotify
WXUNUSED(event
))
381 wxSocketImplMSW
* const socket
= static_cast<wxSocketImplMSW
*>(socket_
);
383 if (socket
->m_fd
!= INVALID_SOCKET
)
385 /* We could probably just subscribe to all events regardless
386 * of the socket type, but MS recommends to do it this way.
388 long lEvent
= socket
->m_server?
389 FD_ACCEPT
: (FD_READ
| FD_WRITE
| FD_CONNECT
| FD_CLOSE
);
391 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, lEvent
);
394 * WinCE creates a thread for socket event handling.
395 * All needed parameters get passed through the thread_data structure.
398 thread_data
* d
= new thread_data
;
401 d
->msgnumber
= socket
->m_msgnumber
;
402 d
->fd
= socket
->m_fd
;
403 socketHash
[socket
->m_fd
] = true;
404 hThread
[currSocket
++] = CreateThread(NULL
, 0, &SocketThread
,(LPVOID
)d
, 0, NULL
);
410 * Disable event notifications (used when shutting down the socket)
412 void wxSocketMSWManager
::Uninstall_Callback(wxSocketImpl
*socket_
,
413 wxSocketNotify
WXUNUSED(event
))
415 wxSocketImplMSW
* const socket
= static_cast<wxSocketImplMSW
*>(socket_
);
417 if (socket
->m_fd
!= INVALID_SOCKET
)
420 gs_WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, 0);
423 socketHash
[socket
->m_fd
] = false;
428 // set the wxBase variable to point to our wxSocketManager implementation
430 // see comments in wx/apptrait.h for the explanation of why do we do it
432 static struct ManagerSetter
436 static wxSocketMSWManager s_manager
;
437 wxAppTraits
::SetDefaultSocketManager(&s_manager
);
441 // ============================================================================
442 // wxSocketImpl implementation
443 // ============================================================================
446 wxSocketImpl
*wxSocketImpl
::Create(wxSocketBase
& wxsocket
)
448 return new wxSocketImplMSW(wxsocket
);
451 void wxSocketImplMSW
::DoClose()
453 wxSocketManager
::Get()->
454 Uninstall_Callback(this, wxSOCKET_MAX_EVENT
/* unused anyhow */);
460 * Waits for an incoming client connection. Returns a pointer to
461 * a wxSocketImpl object, or NULL if there was an error, in which case
462 * the last error field will be updated for the calling wxSocketImpl.
464 * Error codes (set in the calling wxSocketImpl)
465 * wxSOCKET_INVSOCK - the socket is not valid or not a server.
466 * wxSOCKET_TIMEDOUT - timeout, no incoming connections.
467 * wxSOCKET_WOULDBLOCK - the call would block and the socket is nonblocking.
468 * wxSOCKET_MEMERR - couldn't allocate memory.
469 * wxSOCKET_IOERR - low-level error.
471 wxSocketImpl
*wxSocketImplMSW
::WaitConnection(wxSocketBase
& wxsocket
)
473 wxSocketImpl
*connection
;
475 WX_SOCKLEN_T fromlen
= sizeof(from
);
479 /* Reenable CONNECTION events */
480 m_detected
&= ~wxSOCKET_CONNECTION_FLAG
;
482 /* If the socket has already been created, we exit immediately */
483 if (m_fd
== INVALID_SOCKET
|| !m_server
)
485 m_error
= wxSOCKET_INVSOCK
;
489 /* Create a wxSocketImpl object for the new connection */
490 connection
= wxSocketImplMSW
::Create(wxsocket
);
494 m_error
= wxSOCKET_MEMERR
;
498 /* Wait for a connection (with timeout) */
499 if (Input_Timeout() == wxSOCKET_TIMEDOUT
)
502 /* m_error set by Input_Timeout */
506 connection
->m_fd
= accept(m_fd
, (sockaddr
*)&from
, &fromlen
);
508 if (connection
->m_fd
== INVALID_SOCKET
)
510 if (WSAGetLastError() == WSAEWOULDBLOCK
)
511 m_error
= wxSOCKET_WOULDBLOCK
;
513 m_error
= wxSOCKET_IOERR
;
519 /* Initialize all fields */
520 connection
->m_server
= false;
521 connection
->m_stream
= true;
523 /* Setup the peer address field */
524 connection
->m_peer
= GAddress_new();
525 if (!connection
->m_peer
)
528 m_error
= wxSOCKET_MEMERR
;
531 err
= _GAddress_translate_from(connection
->m_peer
, (sockaddr
*)&from
, fromlen
);
532 if (err
!= wxSOCKET_NOERROR
)
534 GAddress_destroy(connection
->m_peer
);
540 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
541 wxSocketManager
::Get()->Install_Callback(connection
);
546 wxSocketError wxSocketImplMSW
::DoHandleConnect(int ret
)
549 if (ret
== SOCKET_ERROR
)
551 int err
= WSAGetLastError();
553 /* If connect failed with EWOULDBLOCK and the wxSocketImpl object
554 * is in blocking mode, we select() for the specified timeout
555 * checking for writability to see if the connection request
558 if ((err
== WSAEWOULDBLOCK
) && (!m_non_blocking
))
560 err
= Connect_Timeout();
562 if (err
!= wxSOCKET_NOERROR
)
565 /* m_error is set in Connect_Timeout */
568 return (wxSocketError
) err
;
571 /* If connect failed with EWOULDBLOCK and the wxSocketImpl object
572 * is set to nonblocking, we set m_error to wxSOCKET_WOULDBLOCK
573 * (and return wxSOCKET_WOULDBLOCK) but we don't close the socket;
574 * this way if the connection completes, a wxSOCKET_CONNECTION
575 * event will be generated, if enabled.
577 if ((err
== WSAEWOULDBLOCK
) && (m_non_blocking
))
579 m_establishing
= true;
580 m_error
= wxSOCKET_WOULDBLOCK
;
581 return wxSOCKET_WOULDBLOCK
;
584 /* If connect failed with an error other than EWOULDBLOCK,
585 * then the call to Connect() has failed.
588 m_error
= wxSOCKET_IOERR
;
589 return wxSOCKET_IOERR
;
592 return wxSOCKET_NOERROR
;
597 /* Like recv(), send(), ... */
598 int wxSocketImplMSW
::Read(void *buffer
, int size
)
602 /* Reenable INPUT events */
603 m_detected
&= ~wxSOCKET_INPUT_FLAG
;
605 if (m_fd
== INVALID_SOCKET
|| m_server
)
607 m_error
= wxSOCKET_INVSOCK
;
611 /* If the socket is blocking, wait for data (with a timeout) */
612 if (Input_Timeout() == wxSOCKET_TIMEDOUT
)
614 m_error
= wxSOCKET_TIMEDOUT
;
620 ret
= Recv_Stream(buffer
, size
);
622 ret
= Recv_Dgram(buffer
, size
);
624 if (ret
== SOCKET_ERROR
)
626 if (WSAGetLastError() != WSAEWOULDBLOCK
)
627 m_error
= wxSOCKET_IOERR
;
629 m_error
= wxSOCKET_WOULDBLOCK
;
636 int wxSocketImplMSW
::Write(const void *buffer
, int size
)
640 if (m_fd
== INVALID_SOCKET
|| m_server
)
642 m_error
= wxSOCKET_INVSOCK
;
646 /* If the socket is blocking, wait for writability (with a timeout) */
647 if (Output_Timeout() == wxSOCKET_TIMEDOUT
)
652 ret
= Send_Stream(buffer
, size
);
654 ret
= Send_Dgram(buffer
, size
);
656 if (ret
== SOCKET_ERROR
)
658 if (WSAGetLastError() != WSAEWOULDBLOCK
)
659 m_error
= wxSOCKET_IOERR
;
661 m_error
= wxSOCKET_WOULDBLOCK
;
663 /* Only reenable OUTPUT events after an error (just like WSAAsyncSelect
664 * does). Once the first OUTPUT event is received, users can assume
665 * that the socket is writable until a read operation fails. Only then
666 * will further OUTPUT events be posted.
668 m_detected
&= ~wxSOCKET_OUTPUT_FLAG
;
678 * For blocking sockets, wait until data is available or
679 * until timeout ellapses.
681 wxSocketError wxSocketImplMSW
::Input_Timeout()
688 FD_SET(m_fd
, &readfds
);
689 if (select(0, &readfds
, NULL
, NULL
, &m_timeout
) == 0)
691 m_error
= wxSOCKET_TIMEDOUT
;
692 return wxSOCKET_TIMEDOUT
;
695 return wxSOCKET_NOERROR
;
699 * For blocking sockets, wait until data can be sent without
700 * blocking or until timeout ellapses.
702 wxSocketError wxSocketImplMSW
::Output_Timeout()
709 FD_SET(m_fd
, &writefds
);
710 if (select(0, NULL
, &writefds
, NULL
, &m_timeout
) == 0)
712 m_error
= wxSOCKET_TIMEDOUT
;
713 return wxSOCKET_TIMEDOUT
;
716 return wxSOCKET_NOERROR
;
720 * For blocking sockets, wait until the connection is
721 * established or fails, or until timeout ellapses.
723 wxSocketError wxSocketImplMSW
::Connect_Timeout()
730 FD_SET(m_fd
, &writefds
);
731 FD_SET(m_fd
, &exceptfds
);
732 if (select(0, NULL
, &writefds
, &exceptfds
, &m_timeout
) == 0)
734 m_error
= wxSOCKET_TIMEDOUT
;
735 return wxSOCKET_TIMEDOUT
;
737 if (!FD_ISSET(m_fd
, &writefds
))
739 m_error
= wxSOCKET_IOERR
;
740 return wxSOCKET_IOERR
;
743 return wxSOCKET_NOERROR
;
746 int wxSocketImplMSW
::Recv_Stream(void *buffer
, int size
)
748 return recv(m_fd
, static_cast<char *>(buffer
), size
, 0);
751 int wxSocketImplMSW
::Recv_Dgram(void *buffer
, int size
)
754 WX_SOCKLEN_T fromlen
= sizeof(from
);
758 ret
= recvfrom(m_fd
, static_cast<char *>(buffer
),
759 size
, 0, &from
, &fromlen
);
761 if (ret
== SOCKET_ERROR
)
764 /* Translate a system address into a wxSocketImpl address */
767 m_peer
= GAddress_new();
770 m_error
= wxSOCKET_MEMERR
;
774 err
= _GAddress_translate_from(m_peer
, (sockaddr
*)&from
, fromlen
);
775 if (err
!= wxSOCKET_NOERROR
)
777 GAddress_destroy(m_peer
);
786 int wxSocketImplMSW
::Send_Stream(const void *buffer
, int size
)
788 return send(m_fd
, static_cast<const char *>(buffer
), size
, 0);
791 int wxSocketImplMSW
::Send_Dgram(const void *buffer
, int size
)
793 struct sockaddr
*addr
;
799 m_error
= wxSOCKET_INVADDR
;
803 err
= _GAddress_translate_to(m_peer
, &addr
, &len
);
804 if (err
!= wxSOCKET_NOERROR
)
810 ret
= sendto(m_fd
, static_cast<const char *>(buffer
), size
, 0, addr
, len
);
812 /* Frees memory allocated by _GAddress_translate_to */
819 * -------------------------------------------------------------------------
821 * -------------------------------------------------------------------------
824 /* CHECK_ADDRESS verifies that the current address family is either
825 * wxSOCKET_NOFAMILY or wxSOCKET_*family*, and if it is wxSOCKET_NOFAMILY, it
826 * initalizes it to be a wxSOCKET_*family*. In other cases, it returns
827 * an appropiate error code.
829 * CHECK_ADDRESS_RETVAL does the same but returning 'retval' on error.
831 #define CHECK_ADDRESS(address, family) \
833 if (address->m_family == wxSOCKET_NOFAMILY) \
834 if (_GAddress_Init_##family(address) != wxSOCKET_NOERROR) \
835 return address->m_error; \
836 if (address->m_family != wxSOCKET_##family) \
838 address->m_error = wxSOCKET_INVADDR; \
839 return wxSOCKET_INVADDR; \
843 #define CHECK_ADDRESS_RETVAL(address, family, retval) \
845 if (address->m_family == wxSOCKET_NOFAMILY) \
846 if (_GAddress_Init_##family(address) != wxSOCKET_NOERROR) \
848 if (address->m_family != wxSOCKET_##family) \
850 address->m_error = wxSOCKET_INVADDR; \
856 GAddress
*GAddress_new()
860 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
863 address
->m_family
= wxSOCKET_NOFAMILY
;
864 address
->m_addr
= NULL
;
870 GAddress
*GAddress_copy(GAddress
*address
)
874 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
877 memcpy(addr2
, address
, sizeof(GAddress
));
881 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
882 if (addr2
->m_addr
== NULL
)
887 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
893 void GAddress_destroy(GAddress
*address
)
896 free(address
->m_addr
);
901 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
903 address
->m_family
= type
;
906 GAddressType
GAddress_GetFamily(GAddress
*address
)
908 return address
->m_family
;
911 wxSocketError
_GAddress_translate_from(GAddress
*address
,
912 struct sockaddr
*addr
, int len
)
914 address
->m_realfamily
= addr
->sa_family
;
915 switch (addr
->sa_family
)
918 address
->m_family
= wxSOCKET_INET
;
921 address
->m_family
= wxSOCKET_UNIX
;
925 address
->m_family
= wxSOCKET_INET6
;
930 address
->m_error
= wxSOCKET_INVOP
;
931 return wxSOCKET_INVOP
;
936 free(address
->m_addr
);
938 address
->m_len
= len
;
939 address
->m_addr
= (struct sockaddr
*) malloc(len
);
941 if (address
->m_addr
== NULL
)
943 address
->m_error
= wxSOCKET_MEMERR
;
944 return wxSOCKET_MEMERR
;
946 memcpy(address
->m_addr
, addr
, len
);
948 return wxSOCKET_NOERROR
;
951 wxSocketError
_GAddress_translate_to(GAddress
*address
,
952 struct sockaddr
**addr
, int *len
)
954 if (!address
->m_addr
)
956 address
->m_error
= wxSOCKET_INVADDR
;
957 return wxSOCKET_INVADDR
;
960 *len
= address
->m_len
;
961 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
964 address
->m_error
= wxSOCKET_MEMERR
;
965 return wxSOCKET_MEMERR
;
968 memcpy(*addr
, address
->m_addr
, address
->m_len
);
969 return wxSOCKET_NOERROR
;
973 * -------------------------------------------------------------------------
974 * Internet address family
975 * -------------------------------------------------------------------------
978 wxSocketError
_GAddress_Init_INET(GAddress
*address
)
980 address
->m_len
= sizeof(struct sockaddr_in
);
981 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
982 if (address
->m_addr
== NULL
)
984 address
->m_error
= wxSOCKET_MEMERR
;
985 return wxSOCKET_MEMERR
;
988 address
->m_family
= wxSOCKET_INET
;
989 address
->m_realfamily
= AF_INET
;
990 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
991 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
993 return wxSOCKET_NOERROR
;
996 wxSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
999 struct in_addr
*addr
;
1001 CHECK_ADDRESS(address
, INET
);
1003 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1005 addr
->s_addr
= inet_addr(hostname
);
1007 /* If it is a numeric host name, convert it now */
1008 if (addr
->s_addr
== INADDR_NONE
)
1010 struct in_addr
*array_addr
;
1012 /* It is a real name, we solve it */
1013 if ((he
= gethostbyname(hostname
)) == NULL
)
1015 /* addr->s_addr = INADDR_NONE just done by inet_addr() above */
1016 address
->m_error
= wxSOCKET_NOHOST
;
1017 return wxSOCKET_NOHOST
;
1019 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1020 addr
->s_addr
= array_addr
[0].s_addr
;
1022 return wxSOCKET_NOERROR
;
1025 wxSocketError
GAddress_INET_SetBroadcastAddress(GAddress
*address
)
1027 return GAddress_INET_SetHostAddress(address
, INADDR_BROADCAST
);
1030 wxSocketError
GAddress_INET_SetAnyAddress(GAddress
*address
)
1032 return GAddress_INET_SetHostAddress(address
, INADDR_ANY
);
1035 wxSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1036 unsigned long hostaddr
)
1038 struct in_addr
*addr
;
1040 CHECK_ADDRESS(address
, INET
);
1042 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1043 addr
->s_addr
= htonl(hostaddr
);
1045 return wxSOCKET_NOERROR
;
1048 wxSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1049 const char *protocol
)
1052 struct sockaddr_in
*addr
;
1054 CHECK_ADDRESS(address
, INET
);
1058 address
->m_error
= wxSOCKET_INVPORT
;
1059 return wxSOCKET_INVPORT
;
1062 se
= getservbyname(port
, protocol
);
1065 if (isdigit(port
[0]))
1069 port_int
= atoi(port
);
1070 addr
= (struct sockaddr_in
*)address
->m_addr
;
1071 addr
->sin_port
= htons((u_short
) port_int
);
1072 return wxSOCKET_NOERROR
;
1075 address
->m_error
= wxSOCKET_INVPORT
;
1076 return wxSOCKET_INVPORT
;
1079 addr
= (struct sockaddr_in
*)address
->m_addr
;
1080 addr
->sin_port
= se
->s_port
;
1082 return wxSOCKET_NOERROR
;
1085 wxSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1087 struct sockaddr_in
*addr
;
1089 CHECK_ADDRESS(address
, INET
);
1091 addr
= (struct sockaddr_in
*)address
->m_addr
;
1092 addr
->sin_port
= htons(port
);
1094 return wxSOCKET_NOERROR
;
1097 wxSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1101 struct sockaddr_in
*addr
;
1103 CHECK_ADDRESS(address
, INET
);
1105 addr
= (struct sockaddr_in
*)address
->m_addr
;
1106 addr_buf
= (char *)&(addr
->sin_addr
);
1108 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1111 address
->m_error
= wxSOCKET_NOHOST
;
1112 return wxSOCKET_NOHOST
;
1115 strncpy(hostname
, he
->h_name
, sbuf
);
1117 return wxSOCKET_NOERROR
;
1120 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1122 struct sockaddr_in
*addr
;
1124 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1126 addr
= (struct sockaddr_in
*)address
->m_addr
;
1128 return ntohl(addr
->sin_addr
.s_addr
);
1131 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1133 struct sockaddr_in
*addr
;
1135 CHECK_ADDRESS_RETVAL(address
, INET
, 0);
1137 addr
= (struct sockaddr_in
*)address
->m_addr
;
1138 return ntohs(addr
->sin_port
);
1144 * -------------------------------------------------------------------------
1145 * Internet IPv6 address family
1146 * -------------------------------------------------------------------------
1148 #include "ws2tcpip.h"
1151 #pragma comment(lib,"ws2_32")
1152 #endif // __VISUALC__
1154 wxSocketError
_GAddress_Init_INET6(GAddress
*address
)
1156 struct in6_addr any_address
= IN6ADDR_ANY_INIT
;
1157 address
->m_len
= sizeof(struct sockaddr_in6
);
1158 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1159 if (address
->m_addr
== NULL
)
1161 address
->m_error
= wxSOCKET_MEMERR
;
1162 return wxSOCKET_MEMERR
;
1164 memset(address
->m_addr
,0,address
->m_len
);
1166 address
->m_family
= wxSOCKET_INET6
;
1167 address
->m_realfamily
= AF_INET6
;
1168 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_family
= AF_INET6
;
1169 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= any_address
;
1171 return wxSOCKET_NOERROR
;
1174 wxSocketError
GAddress_INET6_SetHostName(GAddress
*address
, const char *hostname
)
1176 CHECK_ADDRESS(address
, INET6
);
1179 memset( & hints
, 0, sizeof( hints
) );
1180 hints
.ai_family
= AF_INET6
;
1181 addrinfo
* info
= 0;
1182 if ( getaddrinfo( hostname
, "0", & hints
, & info
) || ! info
)
1184 address
->m_error
= wxSOCKET_NOHOST
;
1185 return wxSOCKET_NOHOST
;
1188 memcpy( address
->m_addr
, info
->ai_addr
, info
->ai_addrlen
);
1189 freeaddrinfo( info
);
1190 return wxSOCKET_NOERROR
;
1193 wxSocketError
GAddress_INET6_SetAnyAddress(GAddress
*address
)
1195 CHECK_ADDRESS(address
, INET6
);
1197 struct in6_addr addr
;
1198 memset( & addr
, 0, sizeof( addr
) );
1199 return GAddress_INET6_SetHostAddress(address
, addr
);
1201 wxSocketError
GAddress_INET6_SetHostAddress(GAddress
*address
,
1202 struct in6_addr hostaddr
)
1204 CHECK_ADDRESS(address
, INET6
);
1206 ((struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
= hostaddr
;
1208 return wxSOCKET_NOERROR
;
1211 wxSocketError
GAddress_INET6_SetPortName(GAddress
*address
, const char *port
,
1212 const char *protocol
)
1215 struct sockaddr_in6
*addr
;
1217 CHECK_ADDRESS(address
, INET6
);
1221 address
->m_error
= wxSOCKET_INVPORT
;
1222 return wxSOCKET_INVPORT
;
1225 se
= getservbyname(port
, protocol
);
1228 if (isdigit((unsigned char) port
[0]))
1232 port_int
= atoi(port
);
1233 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1234 addr
->sin6_port
= htons((u_short
) port_int
);
1235 return wxSOCKET_NOERROR
;
1238 address
->m_error
= wxSOCKET_INVPORT
;
1239 return wxSOCKET_INVPORT
;
1242 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1243 addr
->sin6_port
= se
->s_port
;
1245 return wxSOCKET_NOERROR
;
1248 wxSocketError
GAddress_INET6_SetPort(GAddress
*address
, unsigned short port
)
1250 struct sockaddr_in6
*addr
;
1252 CHECK_ADDRESS(address
, INET6
);
1254 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1255 addr
->sin6_port
= htons(port
);
1257 return wxSOCKET_NOERROR
;
1260 wxSocketError
GAddress_INET6_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1264 struct sockaddr_in6
*addr
;
1266 CHECK_ADDRESS(address
, INET6
);
1268 addr
= (struct sockaddr_in6
*)address
->m_addr
;
1269 addr_buf
= (char *)&(addr
->sin6_addr
);
1271 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin6_addr
), AF_INET6
);
1274 address
->m_error
= wxSOCKET_NOHOST
;
1275 return wxSOCKET_NOHOST
;
1278 strncpy(hostname
, he
->h_name
, sbuf
);
1280 return wxSOCKET_NOERROR
;
1283 wxSocketError
GAddress_INET6_GetHostAddress(GAddress
*address
,struct in6_addr
*hostaddr
)
1285 CHECK_ADDRESS_RETVAL(address
, INET6
, wxSOCKET_INVADDR
);
1286 *hostaddr
= ( (struct sockaddr_in6
*)address
->m_addr
)->sin6_addr
;
1287 return wxSOCKET_NOERROR
;
1290 unsigned short GAddress_INET6_GetPort(GAddress
*address
)
1292 CHECK_ADDRESS_RETVAL(address
, INET6
, 0);
1294 return ntohs( ((struct sockaddr_in6
*)address
->m_addr
)->sin6_port
);
1297 #endif // wxUSE_IPV6
1300 * -------------------------------------------------------------------------
1301 * Unix address family
1302 * -------------------------------------------------------------------------
1305 wxSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1307 address
->m_error
= wxSOCKET_INVADDR
;
1308 return wxSOCKET_INVADDR
;
1311 wxSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *WXUNUSED(path
))
1313 address
->m_error
= wxSOCKET_INVADDR
;
1314 return wxSOCKET_INVADDR
;
1317 wxSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *WXUNUSED(path
), size_t WXUNUSED(sbuf
))
1319 address
->m_error
= wxSOCKET_INVADDR
;
1320 return wxSOCKET_INVADDR
;
1323 #endif // wxUSE_SOCKETS