1 /* -------------------------------------------------------------------------
2 * Project: GSocket (Generic Socket) for WX
4 * Purpose: GSocket main MSW file
6 * -------------------------------------------------------------------------
10 #ifndef __GSOCKET_STANDALONE__
13 #include "wx/msw/gsockmsw.h"
14 #include "wx/gsocket.h"
16 #define INSTANCE wxhInstance
23 /* If not using wxWindows, a global var called hInst must
24 * be available and it must containt the app's instance
27 #define INSTANCE hInst
29 #endif /* __GSOCKET_STANDALONE__ */
32 #if defined(__GSOCKET_STANDALONE__) || defined(wxUSE_SOCKETS)
43 #define CLASSNAME "_GSocket_Internal_Window_Class"
44 #define WINDOWNAME "_GSocket_Internal_Window_Name"
46 /* Maximum number of different GSocket objects at a given time.
47 * This value can be modified at will, but it CANNOT be greater
48 * than (0x7FFF - WM_USER + 1)
50 #define MAXSOCKETS 1024
52 #if (MAXSOCKETS > (0x7FFF - WM_USER + 1))
53 #error "MAXSOCKETS is too big!"
57 /* Global variables */
59 extern HINSTANCE INSTANCE
;
61 static CRITICAL_SECTION critical
;
62 static GSocket
* socketList
[MAXSOCKETS
];
63 static int firstAvailable
;
65 /* Global initializers */
73 /* Create internal window for event notifications */
75 winClass
.lpfnWndProc
= _GSocket_Internal_WinProc
;
76 winClass
.cbClsExtra
= 0;
77 winClass
.cbWndExtra
= 0;
78 winClass
.hInstance
= INSTANCE
;
79 winClass
.hIcon
= (HICON
) NULL
;
80 winClass
.hCursor
= (HCURSOR
) NULL
;
81 winClass
.hbrBackground
= (HBRUSH
) NULL
;
82 winClass
.lpszMenuName
= (LPCTSTR
) NULL
;
83 winClass
.lpszClassName
= CLASSNAME
;
85 RegisterClass(&winClass
);
86 hWin
= CreateWindow(CLASSNAME
,
89 (HWND
) NULL
, (HMENU
) NULL
, INSTANCE
, (LPVOID
) NULL
);
91 if (!hWin
) return FALSE
;
93 /* Initialize socket list */
94 InitializeCriticalSection(&critical
);
96 for (i
= 0; i
< MAXSOCKETS
; i
++)
102 /* Initialize WinSocket */
103 return (WSAStartup((1 << 8) | 1, &wsaData
) == 0);
106 void GSocket_Cleanup()
108 /* Destroy internal window */
110 UnregisterClass(CLASSNAME
, INSTANCE
);
112 /* Delete critical section */
113 DeleteCriticalSection(&critical
);
115 /* Cleanup WinSocket */
119 /* Constructors / Destructors */
121 GSocket
*GSocket_new()
126 if ((socket
= (GSocket
*) malloc(sizeof(GSocket
))) == NULL
)
129 socket
->m_fd
= INVALID_SOCKET
;
130 for (i
= 0; i
< GSOCK_MAX_EVENT
; i
++)
132 socket
->m_cbacks
[i
] = NULL
;
134 socket
->m_local
= NULL
;
135 socket
->m_peer
= NULL
;
136 socket
->m_error
= GSOCK_NOERROR
;
137 socket
->m_server
= FALSE
;
138 socket
->m_stream
= TRUE
;
139 socket
->m_non_blocking
= FALSE
;
140 socket
->m_timeout
.tv_sec
= 10 * 60; /* 10 minutes */
141 socket
->m_timeout
.tv_usec
= 0;
143 /* Allocate a new message number for this socket */
144 EnterCriticalSection(&critical
);
147 while (socketList
[i
] != NULL
)
149 i
= (i
+ 1) % MAXSOCKETS
;
151 if (i
== firstAvailable
) /* abort! */
154 LeaveCriticalSection(&critical
);
158 socketList
[i
] = socket
;
159 firstAvailable
= (i
+ 1) % MAXSOCKETS
;
160 socket
->m_msgnumber
= (i
+ WM_USER
);
162 LeaveCriticalSection(&critical
);
167 void GSocket_destroy(GSocket
*socket
)
169 assert(socket
!= NULL
);
171 /* We don't want more event notifications; so first of all we
172 * remove the socket from the list (NOTE: we won't get a CLOSE
173 * event for this socket if it wasn't closed before).
175 EnterCriticalSection(&critical
);
176 socketList
[(socket
->m_msgnumber
- WM_USER
)] = NULL
;
177 LeaveCriticalSection(&critical
);
179 /* We check that the socket is really shutdowned */
180 if (socket
->m_fd
!= INVALID_SOCKET
)
181 GSocket_Shutdown(socket
);
183 /* We destroy private addresses */
185 GAddress_destroy(socket
->m_local
);
188 GAddress_destroy(socket
->m_peer
);
190 /* We destroy socket itself */
194 void GSocket_Shutdown(GSocket
*socket
)
198 assert(socket
!= NULL
);
200 /* If socket has been created, we shutdown it */
201 if (socket
->m_fd
!= INVALID_SOCKET
)
203 shutdown(socket
->m_fd
, 2);
204 closesocket(socket
->m_fd
);
205 socket
->m_fd
= INVALID_SOCKET
;
208 /* We disable GUI callbacks */
209 for (evt
= 0; evt
< GSOCK_MAX_EVENT
; evt
++)
211 socket
->m_cbacks
[evt
] = NULL
;
214 _GSocket_Configure_Callbacks(socket
);
217 /* Address handling */
219 GSocketError
GSocket_SetLocal(GSocket
*socket
, GAddress
*address
)
221 assert(socket
!= NULL
);
223 if (socket
->m_fd
!= INVALID_SOCKET
&& !socket
->m_server
)
225 socket
->m_error
= GSOCK_INVSOCK
;
226 return GSOCK_INVSOCK
;
229 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
231 socket
->m_error
= GSOCK_INVADDR
;
232 return GSOCK_INVADDR
;
236 GAddress_destroy(socket
->m_local
);
238 socket
->m_local
= GAddress_copy(address
);
240 return GSOCK_NOERROR
;
243 GSocketError
GSocket_SetPeer(GSocket
*socket
, GAddress
*address
)
245 assert(socket
!= NULL
);
247 if (address
== NULL
|| address
->m_family
== GSOCK_NOFAMILY
)
249 socket
->m_error
= GSOCK_INVADDR
;
250 return GSOCK_INVADDR
;
254 GAddress_destroy(socket
->m_peer
);
256 socket
->m_peer
= GAddress_copy(address
);
258 return GSOCK_NOERROR
;
261 GAddress
*GSocket_GetLocal(GSocket
*socket
)
264 struct sockaddr addr
;
267 assert(socket
!= NULL
);
270 return GAddress_copy(socket
->m_local
);
272 if (socket
->m_fd
== INVALID_SOCKET
)
274 socket
->m_error
= GSOCK_INVSOCK
;
280 if (getsockname(socket
->m_fd
, &addr
, &size
) == SOCKET_ERROR
)
282 socket
->m_error
= GSOCK_IOERR
;
286 address
= GAddress_new();
289 socket
->m_error
= GSOCK_MEMERR
;
292 if (_GAddress_translate_from(address
, &addr
, size
) != GSOCK_NOERROR
)
294 socket
->m_error
= GSOCK_MEMERR
;
295 GAddress_destroy(address
);
302 GAddress
*GSocket_GetPeer(GSocket
*socket
)
304 assert(socket
!= NULL
);
307 return GAddress_copy(socket
->m_peer
);
312 /* Server specific parts */
314 /* GSocket_SetServer:
315 * Sets up the socket as a server. It uses the "Local" field of GSocket.
316 * "Local" must be set by GSocket_SetLocal() before GSocket_SetServer()
317 * is called. Possible error codes are: GSOCK_INVSOCK if socket has not
318 * been initialized, GSOCK_INVADDR if the local address has not been
319 * defined and GSOCK_IOERR for other internal errors.
321 GSocketError
GSocket_SetServer(GSocket
*sck
)
327 if (sck
->m_fd
!= INVALID_SOCKET
)
329 sck
->m_error
= GSOCK_INVSOCK
;
330 return GSOCK_INVSOCK
;
335 sck
->m_error
= GSOCK_INVADDR
;
336 return GSOCK_INVADDR
;
339 /* Initialize all fields */
340 sck
->m_server
= TRUE
;
341 sck
->m_stream
= TRUE
;
342 sck
->m_oriented
= TRUE
;
344 /* Create the socket */
345 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_STREAM
, 0);
347 if (sck
->m_fd
== INVALID_SOCKET
)
349 sck
->m_error
= GSOCK_IOERR
;
353 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
354 _GSocket_Configure_Callbacks(sck
);
356 /* Bind the socket to the LOCAL address */
357 if (bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0)
359 closesocket(sck
->m_fd
);
360 sck
->m_fd
= INVALID_SOCKET
;
361 sck
->m_error
= GSOCK_IOERR
;
365 /* Enable listening up to 5 connections */
366 if (listen(sck
->m_fd
, 5) != 0)
368 closesocket(sck
->m_fd
);
369 sck
->m_fd
= INVALID_SOCKET
;
370 sck
->m_error
= GSOCK_IOERR
;
374 return GSOCK_NOERROR
;
377 /* GSocket_WaitConnection:
378 * Waits for an incoming client connection.
380 GSocket
*GSocket_WaitConnection(GSocket
*sck
)
387 /* If the socket has already been created, we exit immediately */
388 if (sck
->m_fd
== INVALID_SOCKET
|| !sck
->m_server
)
390 sck
->m_error
= GSOCK_INVSOCK
;
394 /* Create a GSocket object for the new connection */
395 connection
= GSocket_new();
399 sck
->m_error
= GSOCK_MEMERR
;
403 /* Wait for a connection (with timeout) */
404 if (_GSocket_Input_Timeout(sck
) == GSOCK_TIMEDOUT
)
406 GSocket_destroy(connection
);
407 /* sck->m_error set by _GSocket_Input_Timeout */
411 connection
->m_fd
= accept(sck
->m_fd
, NULL
, NULL
);
413 if (connection
->m_fd
== INVALID_SOCKET
)
415 if (WSAGetLastError() == WSAEWOULDBLOCK
)
416 sck
->m_error
= GSOCK_WOULDBLOCK
;
418 sck
->m_error
= GSOCK_IOERR
;
420 GSocket_destroy(connection
);
424 /* Initialize all fields */
425 connection
->m_server
= FALSE
;
426 connection
->m_stream
= TRUE
;
427 connection
->m_oriented
= TRUE
;
429 ioctlsocket(connection
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
430 _GSocket_Configure_Callbacks(connection
);
435 /* Non oriented connections */
437 GSocketError
GSocket_SetNonOriented(GSocket
*sck
)
443 if (sck
->m_fd
!= INVALID_SOCKET
)
445 sck
->m_error
= GSOCK_INVSOCK
;
446 return GSOCK_INVSOCK
;
451 sck
->m_error
= GSOCK_INVADDR
;
452 return GSOCK_INVADDR
;
455 /* Initialize all fields */
456 sck
->m_stream
= FALSE
;
457 sck
->m_server
= FALSE
;
458 sck
->m_oriented
= FALSE
;
460 /* Create the socket */
461 sck
->m_fd
= socket(sck
->m_local
->m_realfamily
, SOCK_DGRAM
, 0);
463 if (sck
->m_fd
== INVALID_SOCKET
)
465 sck
->m_error
= GSOCK_IOERR
;
469 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
470 _GSocket_Configure_Callbacks(sck
);
472 /* Bind it to the LOCAL address */
473 if (bind(sck
->m_fd
, sck
->m_local
->m_addr
, sck
->m_local
->m_len
) != 0)
475 closesocket(sck
->m_fd
);
476 sck
->m_fd
= INVALID_SOCKET
;
477 sck
->m_error
= GSOCK_IOERR
;
481 return GSOCK_NOERROR
;
484 GSocketError
GSocket_SetBroadcast(GSocket
*sck
)
490 if (GSocket_SetNonOriented(sck
) != GSOCK_NOERROR
)
494 setsockopt(sck
->m_fd
, SOL_SOCKET
, SO_BROADCAST
, (const char FAR
*) &b
, sizeof(b
));
496 return GSOCK_NOERROR
;
499 /* Client specific parts */
502 * Establishes a client connection to a server using the "Peer"
503 * field of GSocket. "Peer" must be set by GSocket_SetPeer() before
504 * GSocket_Connect() is called. Possible error codes are GSOCK_INVSOCK,
505 * GSOCK_INVADDR, GSOCK_TIMEDOUT, GSOCK_WOULDBLOCK and GSOCK_IOERR.
506 * If a socket is nonblocking and Connect() returns GSOCK_WOULDBLOCK,
507 * the connection request can be completed later. Use GSocket_Select()
508 * to check or wait for a GSOCK_CONNECTION event.
510 GSocketError
GSocket_Connect(GSocket
*sck
, GSocketStream stream
)
517 if (sck
->m_fd
!= INVALID_SOCKET
)
519 sck
->m_error
= GSOCK_INVSOCK
;
520 return GSOCK_INVSOCK
;
525 sck
->m_error
= GSOCK_INVADDR
;
526 return GSOCK_INVADDR
;
529 /* Test whether we want the socket to be a stream (e.g. TCP) */
530 sck
->m_stream
= (stream
== GSOCK_STREAMED
);
531 sck
->m_oriented
= TRUE
;
532 sck
->m_server
= FALSE
;
539 /* Create the socket */
540 sck
->m_fd
= socket(sck
->m_peer
->m_realfamily
, type
, 0);
542 if (sck
->m_fd
== INVALID_SOCKET
)
544 sck
->m_error
= GSOCK_IOERR
;
548 ioctlsocket(sck
->m_fd
, FIONBIO
, (u_long FAR
*) &arg
);
549 _GSocket_Configure_Callbacks(sck
);
551 /* Connect it to the PEER address, with a timeout (see below) */
552 ret
= connect(sck
->m_fd
, sck
->m_peer
->m_addr
, sck
->m_peer
->m_len
);
554 if (ret
== SOCKET_ERROR
)
556 err
= WSAGetLastError();
558 /* If connect failed with EWOULDBLOCK and the GSocket object
559 * is in blocking mode, we select() for the specified timeout
560 * checking for writability to see if the connection request
563 if ((err
== WSAEWOULDBLOCK
) && (!sck
->m_non_blocking
))
565 if (_GSocket_Output_Timeout(sck
) == GSOCK_TIMEDOUT
)
567 closesocket(sck
->m_fd
);
568 sck
->m_fd
= INVALID_SOCKET
;
569 /* sck->m_error is set in _GSocket_Output_Timeout */
570 return GSOCK_TIMEDOUT
;
573 return GSOCK_NOERROR
;
576 /* If connect failed with EWOULDBLOCK and the GSocket object
577 * is set to nonblocking, we set m_error to GSOCK_WOULDBLOCK
578 * (and return GSOCK_WOULDBLOCK) but we don't close the socket;
579 * this way if the connection completes, a GSOCK_CONNECTION
580 * event will be generated, if enabled.
582 if ((err
== WSAEWOULDBLOCK
) && (sck
->m_non_blocking
))
584 sck
->m_error
= GSOCK_WOULDBLOCK
;
585 return GSOCK_WOULDBLOCK
;
588 /* If connect failed with an error other than EWOULDBLOCK,
589 * then the call to GSocket_Connect has failed.
591 closesocket(sck
->m_fd
);
592 sck
->m_fd
= INVALID_SOCKET
;
593 sck
->m_error
= GSOCK_IOERR
;
597 return GSOCK_NOERROR
;
602 /* Like recv(), send(), ... */
603 int GSocket_Read(GSocket
*socket
, char *buffer
, int size
)
605 assert(socket
!= NULL
);
607 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
609 socket
->m_error
= GSOCK_INVSOCK
;
613 if (_GSocket_Input_Timeout(socket
) == GSOCK_TIMEDOUT
)
616 if (socket
->m_stream
)
617 return _GSocket_Recv_Stream(socket
, buffer
, size
);
619 return _GSocket_Recv_Dgram(socket
, buffer
, size
);
622 int GSocket_Write(GSocket
*socket
, const char *buffer
, int size
)
624 assert(socket
!= NULL
);
626 if (socket
->m_fd
== INVALID_SOCKET
|| socket
->m_server
)
628 socket
->m_error
= GSOCK_INVSOCK
;
632 if (_GSocket_Output_Timeout(socket
) == GSOCK_TIMEDOUT
)
635 if (socket
->m_stream
)
636 return _GSocket_Send_Stream(socket
, buffer
, size
);
638 return _GSocket_Send_Dgram(socket
, buffer
, size
);
642 * Polls the socket to determine its status. This function will
643 * check for the events specified in the 'flags' parameter, and
644 * it will return a mask indicating which operations can be
645 * performed. This function won't block, regardless of the
646 * mode (blocking|nonblocking) of the socket.
648 GSocketEventFlags
GSocket_Select(GSocket
*socket
, GSocketEventFlags flags
)
650 fd_set readfds
, writefds
, exceptfds
;
652 GSocketEventFlags mask
;
654 assert(socket
!= NULL
);
656 if (socket
->m_fd
== INVALID_SOCKET
)
658 socket
->m_error
= GSOCK_INVSOCK
;
665 FD_SET(socket
->m_fd
, &readfds
);
666 FD_SET(socket
->m_fd
, &writefds
);
667 FD_SET(socket
->m_fd
, &exceptfds
);
671 select(socket
->m_fd
+ 1, &readfds
, &writefds
, &exceptfds
, &tv
);
675 /* If select() says that the socket is readable, then we have
676 * no way to distinguish if that means 'data available' (to
677 * recv) or 'incoming connection' (to accept). The same goes
678 * for writability: we cannot distinguish between 'you can
679 * send data' and 'connection request completed'. So we will
680 * assume the following: if the flag was set upon entry,
681 * that means that the event was possible.
683 if (FD_ISSET(socket
->m_fd
, &readfds
))
685 mask
|= (flags
& GSOCK_CONNECTION_FLAG
);
686 mask
|= (flags
& GSOCK_INPUT_FLAG
);
688 if (FD_ISSET(socket
->m_fd
, &writefds
))
690 mask
|= (flags
& GSOCK_CONNECTION_FLAG
);
691 mask
|= (flags
& GSOCK_OUTPUT_FLAG
);
693 if (FD_ISSET(socket
->m_fd
, &exceptfds
))
694 mask
|= (flags
& GSOCK_LOST_FLAG
);
701 /* GSocket_SetNonBlocking:
702 * Sets the socket to non-blocking mode. This is useful if
703 * we don't want to wait.
705 void GSocket_SetNonBlocking(GSocket
*socket
, bool non_block
)
707 assert(socket
!= NULL
);
709 socket
->m_non_blocking
= non_block
;
712 /* GSocket_SetTimeout:
713 * Sets the timeout for blocking calls. Time is
714 * expressed in milliseconds.
716 void GSocket_SetTimeout(GSocket
*socket
, unsigned long millisecs
)
718 assert(socket
!= NULL
);
720 socket
->m_timeout
.tv_sec
= (millisecs
/ 1000);
721 socket
->m_timeout
.tv_usec
= (millisecs
% 1000) * 1000;
725 * Returns the last error occured for this socket.
727 GSocketError
GSocket_GetError(GSocket
*socket
)
729 assert(socket
!= NULL
);
731 return socket
->m_error
;
736 /* Only one callback is possible for each event (INPUT, OUTPUT, CONNECTION
737 * and LOST). The callbacks are called in the following situations:
739 * INPUT: There is at least one byte in the input buffer
740 * OUTPUT: The system is sure that the next write call will not block
741 * CONNECTION: Two cases are possible:
742 * Client socket -> the connection is established
743 * Server socket -> a client requests a connection
744 * LOST: The connection is lost
746 * An event is generated only once and its state is reseted when the
747 * relative IO call is requested.
748 * For example: INPUT -> GSocket_Read()
749 * CONNECTION -> GSocket_Accept()
752 /* GSocket_SetCallback:
753 * Enables the callbacks specified by 'flags'. Note that 'flags'
754 * may be a combination of flags OR'ed toghether, so the same
755 * callback function can be made to accept different events.
756 * The callback function must have the following prototype:
758 * void function(GSocket *socket, GSocketEvent event, char *cdata)
760 void GSocket_SetCallback(GSocket
*socket
, GSocketEventFlags flags
,
761 GSocketCallback callback
, char *cdata
)
765 assert (socket
!= NULL
);
767 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
769 /* We test each flag and enable the corresponding events */
770 if ((flags
& (1 << count
)) != 0)
772 socket
->m_cbacks
[count
] = callback
;
773 socket
->m_data
[count
] = cdata
;
777 _GSocket_Configure_Callbacks(socket
);
780 /* GSocket_UnsetCallback:
781 * Disables all callbacks specified by 'flags', which may be a
782 * combination of flags OR'ed toghether.
784 void GSocket_UnsetCallback(GSocket
*socket
, GSocketEventFlags flags
)
788 assert(socket
!= NULL
);
790 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
792 /* We test each flag and disable the corresponding events */
793 if ((flags
& (1 << count
)) != 0)
795 socket
->m_cbacks
[count
] = NULL
;
799 _GSocket_Configure_Callbacks(socket
);
805 void _GSocket_Configure_Callbacks(GSocket
*socket
)
810 if (socket
->m_fd
== INVALID_SOCKET
)
813 for (count
= 0; count
< GSOCK_MAX_EVENT
; count
++)
815 if (socket
->m_cbacks
[count
] != NULL
)
819 case GSOCK_INPUT
: mask
|= FD_READ
; break;
820 case GSOCK_OUTPUT
: mask
|= FD_WRITE
; break;
821 case GSOCK_CONNECTION
: mask
|= (FD_ACCEPT
| FD_CONNECT
); break;
822 case GSOCK_LOST
: mask
|= FD_CLOSE
; break;
827 WSAAsyncSelect(socket
->m_fd
, hWin
, socket
->m_msgnumber
, mask
);
830 LRESULT CALLBACK
_GSocket_Internal_WinProc(HWND hWnd
,
837 GSocketCallback cback
;
839 if (uMsg
>= WM_USER
&& uMsg
<= (WM_USER
+ MAXSOCKETS
- 1))
841 EnterCriticalSection(&critical
);
842 socket
= socketList
[(uMsg
- WM_USER
)];
846 /* Check that the socket still exists (it has not been
847 * destroyed) and for safety, check that the m_fd field
848 * is what we expect it to be.
850 if ((socket
!= NULL
) && (socket
->m_fd
== wParam
))
852 switch WSAGETSELECTEVENT(lParam
)
854 case FD_READ
: event
= GSOCK_INPUT
; break;
855 case FD_WRITE
: event
= GSOCK_OUTPUT
; break;
856 case FD_ACCEPT
: event
= GSOCK_CONNECTION
; break;
859 if (WSAGETSELECTERROR(lParam
) != 0)
862 event
= GSOCK_CONNECTION
;
865 case FD_CLOSE
: event
= GSOCK_LOST
; break;
869 cback
= socket
->m_cbacks
[event
];
872 /* OK, we can now leave the critical section because we have
873 * already obtained the callback address (we make no further
874 * accesses to socket->whatever)
876 LeaveCriticalSection(&critical
);
879 (cback
)(socket
, event
, socket
->m_data
[event
]);
884 return DefWindowProc(hWnd
, uMsg
, wParam
, lParam
);
888 /* _GSocket_Input_Timeout:
889 * For blocking sockets, wait until data is available or
890 * until timeout ellapses.
892 GSocketError
_GSocket_Input_Timeout(GSocket
*socket
)
896 if (!socket
->m_non_blocking
)
899 FD_SET(socket
->m_fd
, &readfds
);
900 if (select(0, &readfds
, NULL
, NULL
, &socket
->m_timeout
) == 0)
902 socket
->m_error
= GSOCK_TIMEDOUT
;
903 return GSOCK_TIMEDOUT
;
906 return GSOCK_NOERROR
;
909 /* _GSocket_Output_Timeout:
910 * For blocking sockets, wait until data can be sent without
911 * blocking or until timeout ellapses.
913 GSocketError
_GSocket_Output_Timeout(GSocket
*socket
)
917 if (!socket
->m_non_blocking
)
920 FD_SET(socket
->m_fd
, &writefds
);
921 if (select(0, NULL
, &writefds
, NULL
, &socket
->m_timeout
) == 0)
923 socket
->m_error
= GSOCK_TIMEDOUT
;
924 return GSOCK_TIMEDOUT
;
927 return GSOCK_NOERROR
;
930 int _GSocket_Recv_Stream(GSocket
*socket
, char *buffer
, int size
)
934 ret
= recv(socket
->m_fd
, buffer
, size
, 0);
936 if (ret
== SOCKET_ERROR
)
938 if (WSAGetLastError() != WSAEWOULDBLOCK
)
939 socket
->m_error
= GSOCK_IOERR
;
941 socket
->m_error
= GSOCK_WOULDBLOCK
;
949 int _GSocket_Recv_Dgram(GSocket
*socket
, char *buffer
, int size
)
951 struct sockaddr from
;
955 fromlen
= sizeof(from
);
957 ret
= recvfrom(socket
->m_fd
, buffer
, size
, 0, &from
, &fromlen
);
959 if (ret
== SOCKET_ERROR
)
961 if (WSAGetLastError() != WSAEWOULDBLOCK
)
962 socket
->m_error
= GSOCK_IOERR
;
964 socket
->m_error
= GSOCK_WOULDBLOCK
;
969 /* Translate a system address into a GSocket address */
972 socket
->m_peer
= GAddress_new();
975 socket
->m_error
= GSOCK_MEMERR
;
979 if (_GAddress_translate_from(socket
->m_peer
, &from
, fromlen
) != GSOCK_NOERROR
)
981 socket
->m_error
= GSOCK_MEMERR
;
982 GAddress_destroy(socket
->m_peer
);
989 int _GSocket_Send_Stream(GSocket
*socket
, const char *buffer
, int size
)
993 ret
= send(socket
->m_fd
, buffer
, size
, 0);
995 if (ret
== SOCKET_ERROR
)
997 if (WSAGetLastError() != WSAEWOULDBLOCK
)
998 socket
->m_error
= GSOCK_IOERR
;
1000 socket
->m_error
= GSOCK_WOULDBLOCK
;
1007 int _GSocket_Send_Dgram(GSocket
*socket
, const char *buffer
, int size
)
1009 struct sockaddr
*addr
;
1012 if (!socket
->m_peer
)
1014 socket
->m_error
= GSOCK_INVADDR
;
1018 if (!_GAddress_translate_to(socket
->m_peer
, &addr
, &len
))
1020 socket
->m_error
= GSOCK_MEMERR
;
1024 ret
= sendto(socket
->m_fd
, buffer
, size
, 0, addr
, len
);
1026 /* Frees memory allocated by _GAddress_translate_to */
1029 if (ret
== SOCKET_ERROR
)
1031 if (WSAGetLastError() != WSAEWOULDBLOCK
)
1032 socket
->m_error
= GSOCK_IOERR
;
1034 socket
->m_error
= GSOCK_WOULDBLOCK
;
1043 * -------------------------------------------------------------------------
1045 * -------------------------------------------------------------------------
1048 /* CHECK_ADDRESS verifies that the current family is either GSOCK_NOFAMILY
1049 * or GSOCK_*family*, and if it is GSOCK_NOFAMILY, it initalizes address
1050 * to be a GSOCK_*family*. In other cases, it returns GSOCK_INVADDR.
1052 #define CHECK_ADDRESS(address, family, retval) \
1054 if (address->m_family == GSOCK_NOFAMILY) \
1055 if (_GAddress_Init_##family(address) != GSOCK_NOERROR) \
1056 return address->m_error; \
1057 if (address->m_family != GSOCK_##family) \
1059 address->m_error = GSOCK_INVADDR; \
1064 GAddress
*GAddress_new()
1068 if ((address
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1071 address
->m_family
= GSOCK_NOFAMILY
;
1072 address
->m_addr
= NULL
;
1078 GAddress
*GAddress_copy(GAddress
*address
)
1082 assert(address
!= NULL
);
1084 if ((addr2
= (GAddress
*) malloc(sizeof(GAddress
))) == NULL
)
1087 memcpy(addr2
, address
, sizeof(GAddress
));
1089 if (address
->m_addr
)
1091 addr2
->m_addr
= (struct sockaddr
*) malloc(addr2
->m_len
);
1092 if (addr2
->m_addr
== NULL
)
1097 memcpy(addr2
->m_addr
, address
->m_addr
, addr2
->m_len
);
1103 void GAddress_destroy(GAddress
*address
)
1105 assert(address
!= NULL
);
1110 void GAddress_SetFamily(GAddress
*address
, GAddressType type
)
1112 assert(address
!= NULL
);
1114 address
->m_family
= type
;
1117 GAddressType
GAddress_GetFamily(GAddress
*address
)
1119 assert(address
!= NULL
);
1121 return address
->m_family
;
1124 GSocketError
_GAddress_translate_from(GAddress
*address
,
1125 struct sockaddr
*addr
, int len
)
1127 address
->m_realfamily
= addr
->sa_family
;
1128 switch (addr
->sa_family
)
1131 address
->m_family
= GSOCK_INET
;
1134 address
->m_family
= GSOCK_UNIX
;
1138 address
->m_family
= GSOCK_INET6
;
1143 address
->m_error
= GSOCK_INVOP
;
1148 if (address
->m_addr
)
1149 free(address
->m_addr
);
1151 address
->m_len
= len
;
1152 address
->m_addr
= (struct sockaddr
*) malloc(len
);
1154 if (address
->m_addr
== NULL
)
1156 address
->m_error
= GSOCK_MEMERR
;
1157 return GSOCK_MEMERR
;
1159 memcpy(address
->m_addr
, addr
, len
);
1161 return GSOCK_NOERROR
;
1164 GSocketError
_GAddress_translate_to(GAddress
*address
,
1165 struct sockaddr
**addr
, int *len
)
1167 if (!address
->m_addr
)
1169 address
->m_error
= GSOCK_INVADDR
;
1170 return GSOCK_INVADDR
;
1173 *len
= address
->m_len
;
1174 *addr
= (struct sockaddr
*) malloc(address
->m_len
);
1177 address
->m_error
= GSOCK_MEMERR
;
1178 return GSOCK_MEMERR
;
1181 memcpy(*addr
, address
->m_addr
, address
->m_len
);
1182 return GSOCK_NOERROR
;
1186 * -------------------------------------------------------------------------
1187 * Internet address family
1188 * -------------------------------------------------------------------------
1191 GSocketError
_GAddress_Init_INET(GAddress
*address
)
1193 address
->m_addr
= (struct sockaddr
*) malloc(address
->m_len
);
1194 if (address
->m_addr
== NULL
)
1196 address
->m_error
= GSOCK_MEMERR
;
1197 return GSOCK_MEMERR
;
1200 address
->m_len
= sizeof(struct sockaddr_in
);
1201 address
->m_family
= GSOCK_INET
;
1202 address
->m_realfamily
= PF_INET
;
1203 ((struct sockaddr_in
*)address
->m_addr
)->sin_family
= AF_INET
;
1204 ((struct sockaddr_in
*)address
->m_addr
)->sin_addr
.s_addr
= INADDR_ANY
;
1206 return GSOCK_NOERROR
;
1209 GSocketError
GAddress_INET_SetHostName(GAddress
*address
, const char *hostname
)
1212 struct in_addr
*addr
;
1214 assert(address
!= NULL
);
1216 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1218 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1220 addr
->s_addr
= inet_addr(hostname
);
1222 /* If it is a numeric host name, convert it now */
1223 if (addr
->s_addr
== INADDR_NONE
)
1225 struct in_addr
*array_addr
;
1227 /* It is a real name, we solve it */
1228 if ((he
= gethostbyname(hostname
)) == NULL
)
1230 address
->m_error
= GSOCK_NOHOST
;
1231 return GSOCK_NOHOST
;
1233 array_addr
= (struct in_addr
*) *(he
->h_addr_list
);
1234 addr
->s_addr
= array_addr
[0].s_addr
;
1236 return GSOCK_NOERROR
;
1239 GSocketError
GAddress_INET_SetHostAddress(GAddress
*address
,
1240 unsigned long hostaddr
)
1242 struct in_addr
*addr
;
1244 assert(address
!= NULL
);
1246 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1248 addr
= &(((struct sockaddr_in
*)address
->m_addr
)->sin_addr
);
1249 addr
->s_addr
= hostaddr
;
1251 return GSOCK_NOERROR
;
1254 GSocketError
GAddress_INET_SetPortName(GAddress
*address
, const char *port
,
1255 const char *protocol
)
1258 struct sockaddr_in
*addr
;
1260 assert(address
!= NULL
);
1261 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1265 address
->m_error
= GSOCK_INVPORT
;
1269 se
= getservbyname(port
, protocol
);
1272 if (isdigit(port
[0]))
1276 port_int
= atoi(port
);
1277 addr
= (struct sockaddr_in
*)address
->m_addr
;
1278 addr
->sin_port
= htons((u_short
) port_int
);
1279 return GSOCK_NOERROR
;
1282 address
->m_error
= GSOCK_INVPORT
;
1283 return GSOCK_INVPORT
;
1286 addr
= (struct sockaddr_in
*)address
->m_addr
;
1287 addr
->sin_port
= se
->s_port
;
1289 return GSOCK_NOERROR
;
1292 GSocketError
GAddress_INET_SetPort(GAddress
*address
, unsigned short port
)
1294 struct sockaddr_in
*addr
;
1296 assert(address
!= NULL
);
1297 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1299 addr
= (struct sockaddr_in
*)address
->m_addr
;
1300 addr
->sin_port
= htons(port
);
1302 return GSOCK_NOERROR
;
1305 GSocketError
GAddress_INET_GetHostName(GAddress
*address
, char *hostname
, size_t sbuf
)
1309 struct sockaddr_in
*addr
;
1311 assert(address
!= NULL
);
1312 CHECK_ADDRESS(address
, INET
, GSOCK_INVADDR
);
1314 addr
= (struct sockaddr_in
*)address
->m_addr
;
1315 addr_buf
= (char *)&(addr
->sin_addr
);
1317 he
= gethostbyaddr(addr_buf
, sizeof(addr
->sin_addr
), AF_INET
);
1320 address
->m_error
= GSOCK_NOHOST
;
1321 return GSOCK_NOHOST
;
1324 strncpy(hostname
, he
->h_name
, sbuf
);
1326 return GSOCK_NOERROR
;
1329 unsigned long GAddress_INET_GetHostAddress(GAddress
*address
)
1331 struct sockaddr_in
*addr
;
1333 assert(address
!= NULL
);
1334 CHECK_ADDRESS(address
, INET
, 0);
1336 addr
= (struct sockaddr_in
*)address
->m_addr
;
1338 return addr
->sin_addr
.s_addr
;
1341 unsigned short GAddress_INET_GetPort(GAddress
*address
)
1343 struct sockaddr_in
*addr
;
1345 assert(address
!= NULL
);
1346 CHECK_ADDRESS(address
, INET
, 0);
1348 addr
= (struct sockaddr_in
*)address
->m_addr
;
1349 return ntohs(addr
->sin_port
);
1353 * -------------------------------------------------------------------------
1354 * Unix address family
1355 * -------------------------------------------------------------------------
1358 GSocketError
_GAddress_Init_UNIX(GAddress
*address
)
1360 assert (address
!= NULL
);
1361 address
->m_error
= GSOCK_INVADDR
;
1362 return GSOCK_INVADDR
;
1365 GSocketError
GAddress_UNIX_SetPath(GAddress
*address
, const char *path
)
1367 assert (address
!= NULL
);
1368 address
->m_error
= GSOCK_INVADDR
;
1369 return GSOCK_INVADDR
;
1372 GSocketError
GAddress_UNIX_GetPath(GAddress
*address
, char *path
, size_t sbuf
)
1374 assert (address
!= NULL
);
1375 address
->m_error
= GSOCK_INVADDR
;
1376 return GSOCK_INVADDR
;
1380 #endif /* defined(__GSOCKET_STANDALONE__) || defined(wxUSE_SOCKETS) */
1385 /* Diferencias con la version Unix:
1386 * - El descriptor es SOCKET y no int
1387 * - Constantes -1 pasan a INVALID_SOCKET
1388 * - Errores en muchas funciones pasan de -1 o <0 a SOCKET_ERROR
1389 * - ioctl y close pasan a ioctlsocket y closesocket
1390 * - inet_addr en lugar de inet_aton
1391 * - Codigo de inicializacion y terminacion para inicializar y
1392 * terminar WinSocket y para la ventana interna.
1393 * - SetTimeout en la version MSW simplemente guarda el valor en
1394 * socket.m_timeout, por tanto no hay necesidad de llamar a
1395 * SetTimeout cada vez que se crea realmente un socket (no
1397 * - Lo mismo para SetNonBlocking.