/*************************************************************************** * networking.c * * Sat Jul 15 16:07:17 2006 * Copyright 2006 Emanuele Madeo IZ0ETE * Email ****************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include "networking.h" #include "global.h" int init_network (char *data) { struct hostent *he; struct sockaddr_in their_addr; char hostname[30]; GError *error = NULL; strcpy(hostname,xwota_settings.server_wotadb); //strcpy(hostname,"localhost"); if ((he=gethostbyname(hostname)) == NULL) { herror("gethostbyname"); return -1; } if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { perror("socket"); return -1; } their_addr.sin_family = AF_INET; their_addr.sin_port = htons(atoi(xwota_settings.port)); their_addr.sin_addr = *((struct in_addr *)he->h_addr); bzero(&(their_addr.sin_zero), 8); if (connect(sockfd, (struct sockaddr *)&their_addr, \ sizeof(struct sockaddr)) == -1) { perror("connect"); exit(1); } printf("Connected.\n"); readchan = g_io_channel_unix_new (sockfd); g_io_channel_set_encoding (readchan, NULL, &error); g_io_channel_set_flags (readchan, G_IO_FLAG_NONBLOCK, &error); net_event_id = g_io_add_watch(readchan,G_IO_IN,rx,NULL); // printf("Event ID: %d\n",net_event_id); return 1; // 1 = connected } int disconnect_network (int sockfd,GIOChannel *readchan) { printf("Disconnecting...\n"); g_io_channel_shutdown(readchan,TRUE,NULL); g_io_channel_unref(readchan); g_source_remove(net_event_id); close(sockfd); return 0; } guint rx (GIOChannel *readchan,GIOCondition cond,gpointer data) { gchar buf[1024]; gsize numbytes; GIOStatus res = G_IO_STATUS_NORMAL; GError *err = NULL; //printf("received...\n"); do res = g_io_channel_read_chars (readchan, buf, 1024, &numbytes, &err); while (res == G_IO_STATUS_AGAIN); buf[numbytes] = '\0'; //printf("<- %s\n",buf); decode_msg(buf); return TRUE; } guint tx (GIOChannel *readchan,gchar *datatosend) { GIOStatus res = G_IO_STATUS_NORMAL; gsize numbytes; GError *err = NULL; // printf("-> Send :%s\n",datatosend); do g_io_channel_write_chars(readchan,datatosend,-1,&numbytes,&err); while (res == G_IO_STATUS_AGAIN); g_io_channel_flush(readchan,&err); return TRUE; }