int updateServer(char *hostName, char *portName, char *database) /* Send status message to server arnd report result. */ { char buf[256]; int sd = 0; int ret = 0; /* Put together command. */ sd = netConnect(hostName, atoi(portName)); if (sd >= 0) { safef(buf, ArraySize(buf), "update.%s", database); netSendString(sd, buf); for (;;) { if (netGetString(sd, buf) == NULL) { printf("Error reading status information from %s:%s",hostName,portName); ret = -1; break; } if (sameString(buf, "$end$")) break; else printf("%s\n", buf); } close(sd); } else { ret = -1; printf("Couldn't connect"); } return(ret); }
int main(int argc, char** argv) { const char* address = "127.0.0.1"; int port = 1234; int outgoingSocket; // register callbacks netRegisterReadCallback(onRead); netRegisterWriteCallback(onWrite); netRegisterErrorCallback(onError); // start network CHECK(netStartup()); // create outgoing connection to the server socket CHECK(netCreateSocket(&outgoingSocket)); // connect CHECK(netConnect(outgoingSocket, address, port)); // process events while (1) { CHECK(netWait(1000)); printf("tick\n"); } // shutdown network CHECK(netCleanup()); return 0; }
static int acceptNewClient(int fd) { FD *client; int clientFD; FD *f; FD *proxy; int proxyFD; clientFD = netAccept(fd); if (clientFD < 0) { fprintf(stderr, "netAccept failed\n"); return 0; } client = addFD(clientFD, readClientRequest); if (!client) { fprintf(stderr, "addFD failed\n"); return 0; } proxyFD = netConnect(NULL, (unsigned char *) PROXY_HOST, PROXY_PORT); if (proxyFD < 0) { fprintf(stderr, "netConnect to proxy %s:%d failed\n", PROXY_HOST, PROXY_PORT); return 0; } proxy = addFD(proxyFD, readProxyResponse); if (!proxy) { fprintf(stderr, "addFD failed\n"); return 0; } client->writeFD = proxyFD; proxy->writeFD = clientFD; f = table[fd]; client->logFile = f->logFile; proxy->logFile = f->logFile; client->id = id; proxy->id = id; id++; return 0; }
void debugInit() { struct sockaddr_in stSockAddr; SocketFD = netSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); memset(&stSockAddr, 0, sizeof stSockAddr); stSockAddr.sin_family = AF_INET; stSockAddr.sin_port = htons(DEBUG_PORT); inet_pton(AF_INET, DEBUG_IP, &stSockAddr.sin_addr); netConnect(SocketFD, (struct sockaddr *)&stSockAddr, sizeof stSockAddr); debugPrintf("network debug module initialized\n") ; debugPrintf("ready to have a lot of fun\n") ; }
/* * Add an output channel to <logger> that sends messages to a UDP socket on port * <port> on host <host>. If the host could not be found, -1 is returned and the * channel is not created. */ int logToUDP(Logger *logger, const char *host, int port) { int fd; if ((fd = udpSocket()) < 0 || netConnect(fd, host, port) != 0) return -1; else { pthread_mutex_lock(&logger->access); LOG_Output *out = log_create_output(logger, LOG_OT_UDP); out->u.fd = fd; pthread_mutex_unlock(&logger->access); return 0; } }
HTTP * httpProcess(App *app, URL *url, char *version, HTTPNameValue *headers) { HTTP *http; int port; int sock; port = -1; if (url->port == -1) { port = 80; } else { port = url->port; } if (!url->host) { fprintf(stderr, "url->host is NULL for %s\n", url->url ? (char *) url->url : "<NULL>"); return NULL; } sock = netConnect(app, url->host, port); if (sock == -1) { return NULL; } http = httpAlloc(); http->url = url; if (version) { http->version = (unsigned char *) version; } else { http->version = (unsigned char *) "HTTP/1.0"; } http->headers = headers; httpGetObject(app, http, sock); close(sock); return http; }
bool qbConnect(const char *hostname, unsigned short port) { if(!netInit(hostname,port)) { return false; } #if WIN32 server_thread=CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)serverThread,NULL,0,&server_thread_id); if(server_thread == NULL) { #else int ret = pthread_create(&server_thread, NULL, serverThread, NULL); if( ret != 0 ) { #endif qbLog("Could not create server thread"); netShutdown(); return false; } /*TODO use pthread_attribs to set higher priority*/ #ifdef WIN32 SetThreadPriority(server_thread,THREAD_PRIORITY_TIME_CRITICAL); #endif if(!netConnect()) { qbLog("Could not connect to server"); netShutdown(); return false; } qbSynchConsole("new"); while(!online) { qbLog("Precaching..."); Sleep(1000); } return true; } void qbBegin(void) { char s[64]; sprintf(s,"begin %d\n",login_key); qbSynchConsole(s); }
tcpcon_t * tcp_connect(const char *hostname, int port, char *errbuf, size_t errbufsize, int timeout, int ssl) { struct net_hostent *hp; char *tmphstbuf; int fd, r, err, herr, optval; const char *errtxt; struct sockaddr_in in; socklen_t errlen = sizeof(int); if(!strcmp(hostname, "localhost")) { if((fd = getstreamsocket(AF_INET, errbuf, errbufsize)) == -1) return NULL; memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; in.sin_port = htons(port); in.sin_addr.s_addr = htonl(INADDR_LOOPBACK); r = netConnect(fd, (struct sockaddr *)&in, sizeof(struct sockaddr_in)); } else { herr = 0; tmphstbuf = NULL; /* free NULL is a nop */ hp = netGetHostByName(hostname); if(hp == NULL) herr = h_errno; if(herr != 0) { switch(herr) { case HOST_NOT_FOUND: errtxt = "Unknown host"; break; case NO_ADDRESS: errtxt = "The requested name is valid but does not have an IP address"; break; case NO_RECOVERY: errtxt = "A non-recoverable name server error occurred"; break; case TRY_AGAIN: errtxt = "A temporary error occurred on an authoritative name server"; break; default: errtxt = "Unknown error"; break; } snprintf(errbuf, errbufsize, "%s", errtxt); free(tmphstbuf); return NULL; } else if(hp == NULL) { snprintf(errbuf, errbufsize, "Resolver internal error"); free(tmphstbuf); return NULL; } if((fd = getstreamsocket(hp->h_addrtype, errbuf, errbufsize)) == -1) { free(tmphstbuf); return NULL; } switch(hp->h_addrtype) { case AF_INET: memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; in.sin_port = htons(port); lv2_void* netaddrlist = (lv2_void*)(u64)hp->h_addr_list; memcpy(&in.sin_addr, (char*)(u64)netaddrlist[0], sizeof(struct in_addr)); r = netConnect(fd, (struct sockaddr *)&in, sizeof(struct sockaddr_in)); break; default: snprintf(errbuf, errbufsize, "Invalid protocol family"); free(tmphstbuf); return NULL; } free(tmphstbuf); } if(r < 0) { if(net_errno == NET_EINPROGRESS) { struct pollfd pfd; pfd.fd = fd; pfd.events = POLLOUT; pfd.revents = 0; r = netPoll(&pfd, 1, timeout); if(r == 0) { /* Timeout */ snprintf(errbuf, errbufsize, "Connection attempt timed out"); netClose(fd); return NULL; } if(r == -1) { snprintf(errbuf, errbufsize, "poll() error: %s", strerror(net_errno)); netClose(fd); return NULL; } netGetSockOpt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen); } else { err = net_errno; } } else { err = 0; } if(err != 0) { snprintf(errbuf, errbufsize, "%s", strerror(err)); netClose(fd); return NULL; } optval = 0; r = netSetSockOpt(fd, SOL_SOCKET, SO_NBIO, &optval, sizeof(optval)); if(r < 0) { snprintf(errbuf, errbufsize, "Unable to go blocking: %s", strerror(net_errno)); netClose(fd); return NULL; } tcpcon_t *tc = calloc(1, sizeof(tcpcon_t)); tc->fd = fd; htsbuf_queue_init(&tc->spill, 0); if(ssl) { #if ENABLE_POLARSSL if(1) { tc->ssl = malloc(sizeof(ssl_context)); if(ssl_init(tc->ssl)) { snprintf(errbuf, errlen, "SSL failed to initialize"); close(fd); free(tc->ssl); free(tc); return NULL; } tc->ssn = malloc(sizeof(ssl_session)); tc->hs = malloc(sizeof(havege_state)); havege_init(tc->hs); memset(tc->ssn, 0, sizeof(ssl_session)); ssl_set_endpoint(tc->ssl, SSL_IS_CLIENT ); ssl_set_authmode(tc->ssl, SSL_VERIFY_NONE ); ssl_set_rng(tc->ssl, havege_rand, tc->hs ); ssl_set_bio(tc->ssl, net_recv, &tc->fd, net_send, &tc->fd); ssl_set_ciphers(tc->ssl, ssl_default_ciphers ); ssl_set_session(tc->ssl, 1, 600, tc->ssn ); tc->read = polarssl_read; tc->write = polarssl_write; } else #endif { snprintf(errbuf, errlen, "SSL not supported"); tcp_close(tc); return NULL; } } else { tc->read = tcp_read; tc->write = tcp_write; } return tc; }
int main(int argc, char *argv[]) { int ret; //fuer getopt funktion char player = '3'; char gameId[15]; char *confDateiName = malloc(256); strcpy(confDateiName, "client.conf"); pid_t pid; //Config-Datei einlesen und struct betanken log_printf(LOG_DEBUG,"Using config-file %s\n",confDateiName); configstruct = get_config(confDateiName); log_printf(LOG_PRINTF,"\n"); //11-stellige Game-Id aus Kommandozeile auslesen if (argc < 2) { printf("Keine Game-Id angegeben!\n"); help(); exit(EXIT_FAILURE); } strcpy(gameId,argv[1]); if(strlen(gameId) != 11) { printf("Game-Id muss 11-stellig sein!\n"); help(); exit(EXIT_FAILURE); } //optional gewunschte Spielernummer, config Dateiname oder log Level einlesen while ((ret=getopt(argc, argv, "p:c:l:")) != -1) { switch (ret) { case 'p': player = optarg[0]; if (player!='0' && player != '1') { printf("Es gibt nur 2 Spieler! 0 oder 1 eingeben!\n"); help(); exit(EXIT_FAILURE); } break; case 'c': strcpy(confDateiName, optarg); break; case 'l': configstruct.loglevel = atoi(optarg); break; default: help(); exit(EXIT_FAILURE); } } //Shared-Memory erstellen //shmSegment() um die ID zu erstellen -> vor fork() int shmid = shmSegment(sizeof(struct shmInfos)); //shmAnbinden(shmid); um es an den Prozess zu binden shmPtr = shmAnbinden(shmid); //shm automatisch entfernen, wenn alle prozesse detached sind shmDelete(shmid); //Pipe anlegen int pipe_fd[2]; if(pipe(pipe_fd)<0){ log_printf(LOG_ERROR,"Fehler bei Pipe anlegen"); }; // zweiten Prozess erstellen. // Connector ist der Kindprozess // Thinker der Elternprozess switch (pid = fork ()) { case -1: log_printf (LOG_ERROR,"Fehler bei fork()\n"); break; case 0: // Connector shmPtr->pid1=pid; char *getText; //Verbindung mit Server herstellen netConnect(configstruct.port, configstruct.hostname); while (1) { getText = netReadLine(); if (strncmp(getText, "+ MNM ",6) == 0) { //+ MNM Gameserver v1.0 accepting connections sendVersion(); } else if (strncmp(getText, "+ Clie",6) == 0) { //+ Client version accepted - please send Game-ID to join sendGameId(gameId); } else if (strncmp(getText, "+ PLAY",6) == 0) { //+ PLAYING Quarto parseGamekind(getText, shmPtr); sendPlayer(player, shmPtr); } else if (strncmp(getText, "+ ENDP",6) == 0) { //+ ENDPLAYERS //noop } else if (strncmp(getText, "+ MOVE",6) == 0) { //+ MOVE 3000 parseMovetimeout(getText, shmPtr); } else if (strncmp(getText, "+ NEXT",6) == 0) { //+ NEXT 7 parseNext(getText, shmPtr); } else if (strncmp(getText, "+ FIEL",6) == 0) { //+ FIELD 4,4 parseField(getText); } else if (strncmp(getText, "+ ENDF",6) == 0) { //+ ENDFIELD if (shmPtr->gameover != 1) { sendThinking(); } } else if (strncmp(getText, "+ OKTH",6) == 0) { //Hier Zug erhalten und per sendMove(stein, naechsterstein) senden if(ueberwacheFd(pipe_fd,getText)==1){ log_printf(LOG_DEBUG,"Gandalf hat gesprochen und wurde vor dem ertrinken gerettet!\n"); sendMove(getText); } else{ log_printf(LOG_PRINTF,"Gandalf ist ersoffen\n"); } } else if (strncmp(getText, "+ WAIT",6) == 0) { //+ WAIT sendOkwait(); } else if (strncmp(getText, "+ GAME",6) == 0) { //+ GAMEOVER [[ hh Spielernummer des Gewinners ii hh Spielername des Gewinners ii ]] shmPtr->gameover = 1; parseGameover(getText); } else if (strncmp(getText, "+ QUIT",6) == 0) { //+ QUIT netDisconnect(); break; } else if (strncmp(getText, "-",1) == 0) { //Well, f**k. //aufraeumen + signal an parent schicken, damit der sich beendet netDisconnect(); free(confDateiName); kill(getppid(),SIGCHLD); break; } } break; default: // Thinker shmPtr->pid0=pid; //wenn das Signal kommt, dass er denken soll signal(SIGUSR1, signalHandler); //wenn das Signal vom Kind kommt, dass er sich beenden soll (wegen Fehler) signal(SIGCHLD, endHandler); while (1){ // Auf Signal warten pause(); log_printf(LOG_DEBUG,"thinker hat fertig gedacht\n"); // In die Pipe schreiben pipe_write(pipe_fd); } if (wait (NULL) != pid) { log_printf(LOG_ERROR,"Fehler beim Warten auf den Kindprozess\n"); return EXIT_FAILURE; } break; } return 0; }