g_io_add_watch and non-blocking io on windows



Hello! I am trying to discover how to use non-blocking io with glib on
windows. I am trying such program:

/* -*- Mode: C; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */

#include <glib.h>

#ifdef G_OS_WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

gboolean
connect_cb (GIOChannel *io_channel, GIOCondition condition, gpointer data)
{
   switch (condition) {
   case G_IO_OUT:
       g_debug ("Connected.");
       break;
   case G_IO_ERR:
       g_debug ("Error!");
       break;
   }

   return FALSE;
}

int
main (int argc, char *argv[])
{
#ifdef G_OS_WIN32
   int ret;
   WSADATA wsaData;
   SOCKET  sd;
   struct sockaddr_in target;
   struct hostent    *hptr;
   u_long             mode = 1;
   GMainLoop         *loop;
   GIOChannel        *io_channel;
   GSource           *source;

   ret = WSAStartup (0x0202, &wsaData);
   if (ret) {
       g_error ("WSAStaroup failed with error %d", ret);
   }

   sd = socket (AF_INET, SOCK_STREAM, 0);
   if (sd == INVALID_SOCKET) {
       g_error ("socket failed with error %d", WSAGetLastError ());
   }

   target.sin_family = AF_INET;
   target.sin_port   = htons (80);
   if ( (hptr = gethostbyname ("somehost.com")) == NULL) {
       g_error ("gethostbyname () failed with error %d\n", WSAGetLastError
());
   }
   memcpy (&(target.sin_addr.s_addr), hptr->h_addr_list[0],
           sizeof (target.sin_addr.s_addr));

   if (ioctlsocket(sd, FIONBIO, &mode) == SOCKET_ERROR) {
       g_error("ioctlsocket() failed \n");
   }

   loop = g_main_loop_new (NULL, FALSE);
   io_channel = g_io_channel_win32_new_socket (sd);
   g_io_channel_set_encoding (io_channel, NULL, NULL);
   g_io_channel_set_buffered (io_channel, FALSE);
   g_io_add_watch (io_channel, G_IO_ERR | G_IO_OUT, connect_cb, NULL);

   g_debug ("Executing connect async...");
   ret = connect (sd, (const struct sockaddr *) &target, sizeof (target));
   if (ret == SOCKET_ERROR) {
       if (WSAGetLastError () != WSAEWOULDBLOCK)
           g_error ("connect () failed with error %d\n", WSAGetLastError
());
   }

   g_debug ("Starting GMainLoop...");
   g_main_loop_run (loop);

#endif

   return 0;
}

/* END */

My problem is that condition parameter in callback is always G_IO_OUT even
if target host:port is unreachable. How can I discover that connect was
unsuccessfull? Thanx.

// wbr Alexander



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]