int main(int argc, char *argv[]) { signal(SIGTERM, &writeToDisk); signal(SIGINT, &writeToDisk); if(argc < 2) { std::cout << "no IP address specified, defaulting to loopback..." << std::endl; openGLSocket = setupSocket("127.0.0.1", 8999); } else { std::cout << "using provided address: " << argv[1] << std::endl; openGLSocket = setupSocket(argv[1], 8999); } init(); glutInit(&argc, argv); glutInitDisplayMode(GLUT_SINGLE | GLUT_RGBA); glutInitWindowSize((int) width, (int) height); wd = glutCreateWindow("Client Buffer" /* title */ ); glutDisplayFunc(display); glutKeyboardFunc(keyboardHandler); glutSpecialFunc(specialKeyHandler); glutReshapeFunc(reshape); glutIdleFunc(socketHandler); glutCloseFunc(glutWriteToDisk); #ifndef __APPLE__ glewInit(); #endif /* start the GLUT main loop */ glutMainLoop(); return 0; }
void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) { assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread()); if (sockets_.size() > 0) { throw std::invalid_argument( "cannot call useExistingSocket() on a " "AsyncServerSocket that already has a socket"); } for (auto fd: fds) { // Set addressFamily_ from this socket. // Note that the socket may not have been bound yet, but // setFromLocalAddress() will still work and get the correct address family. // We will update addressFamily_ again anyway if bind() is called later. SocketAddress address; address.setFromLocalAddress(fd); #if __linux__ if (noTransparentTls_) { // Ignore return value, errors are ok setsockopt(fd, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0); } #endif setupSocket(fd, address.getFamily()); sockets_.emplace_back(eventBase_, fd, this, address.getFamily()); sockets_.back().changeHandlerFD(fd); } }
void opimServer::bringOnline( void ) { _socket = setupSocket( _myAddr ); _online = true; cout << "Server is online!\n" << flush; }
Connection::Connection(const QString &host, qint32 port, QObject *parent) : QTcpSocket(parent), Endpoint(host, port), mReconnectTimerId(0), mOpLength(0) { mBuffer.clear(); setupSocket(); connect(&mAsserter,SIGNAL(fatalError()), SIGNAL(fatalError())); }
void enviarSolicitud(char* hostname, char* token,char* problema) { char request[1000]; setupSocket(hostname); connectToHost(hostname); sprintf(request,"GET /index.php?r=juego/solicitud&token=%s&problema=%s HTTP/1.1\r\nHost: %s\r\n\r\n",token,problema,hostname); //printf("se envia request: %s", request); if (send(sock, request, sizeof(request), 0) != (int)sizeof(request)) { printf( "Error sending request." ); exit(1); } getBuffer(); }
void enviarRespuesta(char* hostname,char* respuesta) { char request[1000]; setupSocket(hostname); connectToHost(hostname); sprintf(request,"GET /index.php?r=juego/respuesta&tokenSolicitud=%s&solucion=%s HTTP/1.1\r\nHost: %s\r\n\r\n",tokenSolicitud,respuesta,hostname); //http://hornero.fi.uncoma.edu.ar/index.php?r=juego/respuesta&&tokenSolicitud=76d7cadd3df99e06ae8c4aa580ca6900&solucion=-5933 printf("\nse envia request: %s\n", request); if (send(sock, request, sizeof(request), 0) != (int)sizeof(request)) { printf( "Error sending request." ); exit(1); } getBuffer(); }
int remoteTCPConnect::setup(int receiveBufferLength) { int newSock = 0; int rcvFlag = 0; int length = receiveBufferLength; char rcvBuffer[length]; std::string contents; struct sockaddr_storage their_addr; socklen_t sin_size; printf("\n\n\n"); mainSockID = setupSocket(); if(mainSockID == -1) { printf("error setting up socket \n"); return -1; } while(true) { sin_size = sizeof their_addr; newSock = accept(mainSockID, (struct sockaddr *)&their_addr, &sin_size); //std::cout<<"Connected.\n"; if(newSock == -1) { perror("accept"); continue; } //std::cout<<"Connection Confirmed.\n"; rcvFlag = recv(newSock, rcvBuffer, length-1, 0); //std::cout<<"Receiving...\n"; if(rcvFlag ==-1) { perror("receive"); exit(1); } printf("The remote server has received information from the remote server\n"); //std::cout<<"Reception confirmed.\n"; rcvBuffer[rcvFlag] = '\0'; contents=std::string(rcvBuffer); while(parse(contents)<0); close(newSock); if(disconnect) break; } close(mainSockID); }
int AsyncServerSocket::createSocket(int family) { int fd = fsp::socket(family, SOCK_STREAM, 0); if (fd == -1) { folly::throwSystemError(errno, "error creating async server socket"); } try { setupSocket(fd, family); } catch (...) { closeNoInt(fd); throw; } return fd; }
void TUIOSender::start() { Node::start(); frameSequenceNumber = 0; sourceId.setName(AppInfo::NAME); sourceId.setVersion(AppInfo::VERSION); setupSocket(); host.onChange.connect(boost::bind(&TUIOSender::setupSocket, this)); port.onChange.connect(boost::bind(&TUIOSender::setupSocket, this)); }
net::ssl::SSLConnection::SSLConnection(std::auto_ptr<net::Socket> socket, SSL_CTX * ctx, bool serverAuth, const std::string& host) : NetConnection(socket), mServerAuthentication(serverAuth) { mSSL = NULL; mBioErr = BIO_new_fp(stderr, BIO_NOCLOSE); mSSL = SSL_new(ctx); if(mSSL == NULL) { throw net::ssl::SSLException(Ctxt(FmtX("SSL_new failed"))); } setupSocket(host); }
void AsyncServerSocket::useExistingSockets(const std::vector<int>& fds) { assert(eventBase_ == nullptr || eventBase_->isInEventBaseThread()); if (sockets_.size() > 0) { throw std::invalid_argument( "cannot call useExistingSocket() on a " "AsyncServerSocket that already has a socket"); } for (auto fd: fds) { // Set addressFamily_ from this socket. // Note that the socket may not have been bound yet, but // setFromLocalAddress() will still work and get the correct address family. // We will update addressFamily_ again anyway if bind() is called later. SocketAddress address; address.setFromLocalAddress(fd); setupSocket(fd); sockets_.emplace_back(eventBase_, fd, this, address.getFamily()); sockets_.back().changeHandlerFD(fd); } }
/*-----------------------------------------------------------------------------*/ int main(int argc, char *argv[]) { Input input = validateInput(argc, argv); printf("awget:\n\tRequest: %s\n\t", input.URL); char ** fileLines = readFile(input.filename); printf("chainlist is\n\t"); for(int j = 1; fileLines[j] != NULL; j++) { printf("%s\n\t", fileLines[j]); } Packet * aPacket = buildPacket(fileLines, input.URL); int randStepNum = getRandStepNum(aPacket->chainFile[0]); //Get random stepping stone number char * steppingStone = fileLines[randStepNum]; //Get random stepping stone printf("next SS is %s\n\t", steppingStone); //Connect to stepping stone int socketfd = setupSocket(getIP(steppingStone), atoi(getPort(steppingStone))); //Remove stepping stone from file removeSS(randStepNum, aPacket); //Write to stepping stone socketfd = writeSocket(socketfd, aPacket); printf("waiting for file...\n..\n"); //Read the data char *filename = getFilename(input.URL); makeFile(socketfd, filename); printf("\tReceived file <%s>\n\tGoodbye!\n", filename); close(socketfd); free (aPacket); }
/** * The main function */ int main(int argc, char *argv[]) { int fd, opt; struct in_addr laddr, maddr; struct sockaddr_in sin; unsigned short port=0; char message[255]; laddr.s_addr = 0; maddr.s_addr = 0; /* check for command line switches */ while (1) { int option_index = 0; static const struct option long_options[] = { { "mcast", required_argument, NULL, 'm' }, { "bind", required_argument, NULL, 'b' }, { "port", required_argument, NULL, 'p' }, { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, { 0, 0, 0, 0 }, }; opt = getopt_long(argc, argv, "m:b:p:hv", long_options, &option_index); if (opt == -1) { break; } switch (opt) { case 'm': inet_pton(AF_INET, optarg, &maddr); break; case 'b': inet_pton(AF_INET, optarg, &laddr); break; case 'p': port = atoi(optarg); break; case 'h': printUsage(argv); exit(EXIT_SUCCESS); break; case 'v': printVersion(argv); exit(EXIT_SUCCESS); break; default: printUsage(argv); exit(EXIT_FAILURE); break; } } if (maddr.s_addr == 0 || port == 0) { printUsage(argv); exit(EXIT_FAILURE); } memset(&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = maddr.s_addr; sin.sin_port = htons(port); if (-1 == (fd = setupSocket(laddr, &sin))) { perror("setupSocket"); exit(EXIT_FAILURE); } while (1) { unsigned int sin_len = sizeof(sin); memset(message, 0, sizeof(message)); if (recvfrom(fd, message, sizeof(message), 0, (struct sockaddr *) &sin, &sin_len) == -1) { perror ("recvfrom"); } printf ("%s",message); } exit(EXIT_SUCCESS); }
int main(int argc, char** argv) { printf("************* Welcome to UCLA FPGA agent! **********\n"); #if SOCKET int listenfd = setupSocket( 5000 ); #endif struct cl_package clPackage = initFPGA("logistic_lpp.xclbin", "logistic"); float* weights = (float*)malloc(LABEL_SIZE*FEATURE_SIZE*sizeof(float)); float* data = (float*)malloc(PARTITION_SIZE*(FEATURE_SIZE+LABEL_SIZE)*sizeof(float)); float* gradient = (float*)malloc(LABEL_SIZE*FEATURE_SIZE*sizeof(float)); #if SOCKET while (1) #endif { #if SOCKET int connfd = acceptSocket(listenfd); #endif printf("************* Got a new task! *************\n"); //fread(A, n*n, sizeof(float), fin); //fread(B, n*n, sizeof(float), fin); size_t nbyte; int L; int D; int n; int cached; #if SOCKET timespec timer1 = tic( ); nbyte = recv(connfd, &L, sizeof(L), MSG_WAITALL); nbyte = recv(connfd, &D, sizeof(D), MSG_WAITALL); nbyte = recv(connfd, &n, sizeof(n), MSG_WAITALL); nbyte = recv(connfd, &cached, sizeof(cached), MSG_WAITALL); printf("parameter recieved --- "); toc( timer1 ); #else L = LABEL_SIZE; D = FEATURE_SIZE; if (argc > 1) n = atoi(argv[1]); else n = 100; #endif printf("# of labels: %d\n", L); printf("# of features: %d\n", D); printf("# of data points: %d\n", n); if(L>1024 || D>1024 || n > 65536) { printf("ERROR: too large data size!\n"); return 1; } memset((void*)gradient, 0, L*D*sizeof(float)); int i; #if SOCKET nbyte = recv_large_array(connfd, (char*)weights, L*D*sizeof(float)); printf("received weights for %d bytes --- ", nbyte); toc( timer1 ); #if SHOW_DATA printf("the first 10 elements are:\n"); for( i = 0; i < 10; i++ ) printf("%f\n", weights[i]); #endif if( cached == 0 ) { //nbyte = recv(connfd, data, n*(D+L)*sizeof(float), MSG_WAITALL); nbyte = recv_large_array( connfd, (char*)data, n*(D+L)*sizeof(float) ); printf("received training data for %d bytes --- ", nbyte); toc( timer1 ); } #if SHOW_DATA printf("the first 10 elements are:\n"); for( i = 0; i < 10; i++ ) printf("%f\n", data[i]); #endif #else for( i = 0; i < D; i++ ) weights[i]=0.; FILE* pFile = fopen("train_data.txt","r"); for( i = 0; i < n*(D+L); i++ ) fscanf(pFile, "%f", data+i); fclose(pFile); #endif printf("FPGA computation...\n"); //computeGradient(weights,data,gradient,L,D,n); computeGradientByFPGA(weights,data,gradient,L,D,n,clPackage); printf("FPGA computation finished! --- "); toc( timer1 ); #if SOCKET //for( int i = 0; i < 10; i++ ) gradient[i]=i; nbyte = send(connfd, gradient, L*D*sizeof(float), 0); //int temp = tr.tv_usec; //nbyte = send(connfd, &temp, sizeof(int), 0); printf("sent gradient for %d bytes --- ", nbyte); toc( timer1 ); printf("************* Task finished! *************\n"); #else for( i = 0; i < 10; i++ ) printf("%f\n",gradient[i]); #endif #if SOCKET close(connfd); #endif } free(weights); free(data); free(gradient); clReleaseMemObject(clPackage.d_weights); clReleaseMemObject(clPackage.d_data); clReleaseMemObject(clPackage.d_gradient); return 0; }
void AsyncServerSocket::bind(uint16_t port) { struct addrinfo hints, *res0; char sport[sizeof("65536")]; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE | AI_NUMERICSERV; snprintf(sport, sizeof(sport), "%u", port); // On Windows the value we need to pass to bind to all available // addresses is an empty string. Everywhere else, it's nullptr. constexpr const char* kWildcardNode = kIsWindows ? "" : nullptr; if (getaddrinfo(kWildcardNode, sport, &hints, &res0)) { throw std::invalid_argument( "Attempted to bind address to socket with " "bad getaddrinfo"); } SCOPE_EXIT { freeaddrinfo(res0); }; auto setupAddress = [&] (struct addrinfo* res) { int s = fsp::socket(res->ai_family, res->ai_socktype, res->ai_protocol); // IPv6/IPv4 may not be supported by the kernel if (s < 0 && errno == EAFNOSUPPORT) { return; } CHECK_GE(s, 0); try { setupSocket(s, res->ai_family); } catch (...) { closeNoInt(s); throw; } if (res->ai_family == AF_INET6) { int v6only = 1; CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only))); } // Bind to the socket if (fsp::bind(s, res->ai_addr, socklen_t(res->ai_addrlen)) != 0) { folly::throwSystemError( errno, "failed to bind to async server socket for port ", SocketAddress::getPortFrom(res->ai_addr), " family ", SocketAddress::getFamilyNameFrom(res->ai_addr, "<unknown>")); } #if __linux__ if (noTransparentTls_) { // Ignore return value, errors are ok setsockopt(s, SOL_SOCKET, SO_NO_TRANSPARENT_TLS, nullptr, 0); } #endif SocketAddress address; address.setFromLocalAddress(s); sockets_.emplace_back(eventBase_, s, this, address.getFamily()); }; const int kNumTries = 25; for (int tries = 1; true; tries++) { // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo // should return IPv6 first and then IPv4 addresses, but glibc's // getaddrinfo(nullptr) with AI_PASSIVE returns: // - 0.0.0.0 (IPv4-only) // - :: (IPv6+IPv4) in this order // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981 for (struct addrinfo* res = res0; res; res = res->ai_next) { if (res->ai_family == AF_INET6) { setupAddress(res); } } // If port == 0, then we should try to bind to the same port on ipv4 and // ipv6. So if we did bind to ipv6, figure out that port and use it. if (sockets_.size() == 1 && port == 0) { SocketAddress address; address.setFromLocalAddress(sockets_.back().socket_); snprintf(sport, sizeof(sport), "%u", address.getPort()); freeaddrinfo(res0); CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0)); } try { for (struct addrinfo* res = res0; res; res = res->ai_next) { if (res->ai_family != AF_INET6) { setupAddress(res); } } } catch (const std::system_error&) { // If we can't bind to the same port on ipv4 as ipv6 when using // port=0 then we will retry again before giving up after // kNumTries attempts. We do this by closing the sockets that // were opened, then restarting from scratch. if (port == 0 && !sockets_.empty() && tries != kNumTries) { for (const auto& socket : sockets_) { if (socket.socket_ <= 0) { continue; } else if (shutdownSocketSet_) { shutdownSocketSet_->close(socket.socket_); } else { closeNoInt(socket.socket_); } } sockets_.clear(); snprintf(sport, sizeof(sport), "%u", port); freeaddrinfo(res0); CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0)); continue; } throw; } break; } if (sockets_.size() == 0) { throw std::runtime_error( "did not bind any async server socket for port"); } }
int main(int argc, char **argv) { if (argc != 2) { perror("Illegal argument count\n"); exit(0); } /* server port */ int port = (int) strtol(argv[1], (char **)NULL, 10); /* ssl setup */ SSL_CTX *ssl_ctx; ssl_ctx = setupSSL(); /* socket setup */ int sockfd = setupSocket(port); fd_set rfds;//, temp_set; struct timeval tv; int retval;//, maxfd = sockfd; for (;;){ FD_ZERO(&rfds); FD_SET(sockfd, &rfds); tv.tv_sec = 5; tv.tv_usec = 0; retval = select(sockfd + 1, &rfds, NULL, NULL, &tv); if (retval == -1) { perror("accept()"); } else if (retval > 0) { if (FD_ISSET(sockfd, &rfds)) { printf("Someone is trying to connect!\n"); struct sockaddr_in addr; socklen_t len = sizeof(addr); printf("Accepting connection!\n"); int fd_client = accept(sockfd, (struct sockaddr*)&addr, &len); if (fd_client < 0) { perror("accept()"); exit(0); } SSL *ssl = SSL_new(ssl_ctx); SSL_set_fd(ssl, fd_client); printf("Accepting SSL connection!\n"); if (SSL_accept(ssl) < 0){ perror("SSL_accept()"); exit(0); } printf("Saying Hello!\n"); SSL_write(ssl, "Hello", sizeof("Hello")); printf("Stopping connection!\n"); SSL_free(ssl); close(fd_client); } } else { printf("No message in five seconds.\n"); } } close(sockfd); SSL_CTX_free(ssl_ctx); }
int main(int argc, char **argv) { int fd; int port_set = 0; printf("GTPing %s\n", version); argv0 = argv[0]; { /* handle GNU options */ int c; for (c = 1; c < argc; c++) { if (!strcmp(argv[c], "--")) { break; } else if (!strcmp(argv[c], "--help")) { usage(0); } else if (!strcmp(argv[c], "--version")) { printVersion(); } } } /* parse options */ { int c; unsigned int tmpu; while (-1 != (c=getopt(argc, argv, "46c:fhi:g:p:P:Q:r::s:t:T:vVw:"))) { switch(c) { case '4': options.af = AF_INET; break; case '6': options.af = AF_INET6; break; case 'c': options.count = strtoul(optarg, 0, 0); break; case 'f': options.flood = 1; /* if interval not alread set, set it to 0 */ if (0 > options.interval) { options.interval = 0; fprintf(stderr, "%s: invalid interval \"%s\", " "set to 0\n", argv0, optarg); } break; case 'g': tmpu = strtoul(optarg, 0, 0); if (tmpu < 1 || tmpu > 2) { fprintf(stderr, "%s: invalid GTP version %u. " "Supported: 1 & 2.", argv0, tmpu); } options.version = tmpu; break; case 'h': usage(0); break; case 'p': options.port = optarg; port_set = 1; break; case 'P': options.source_port = optarg; break; case 's': options.source = optarg; break; case 't': options.teid = strtoul(optarg, 0, 0); options.has_teid = 1; break; case 'T': options.ttl = strtoul(optarg, 0, 0); if (options.ttl > 255) { options.ttl = 255; } break; case 'v': options.verbose++; break; case 'V': printVersion(); case 'i': options.interval = atof(optarg); break; case 'w': options.wait = atof(optarg); break; case 'Q': if (-1 == (options.tos = string2Tos(optarg))) { fprintf(stderr, "%s: invalid ToS/DSCP \"%s\", " "left as-is.\n", argv0,optarg); fprintf(stderr, "%s: " "Valid are " "BE,EF,AF[1-4][1-3],CS[0-7] " "and numeric (0x for hex).\n", argv0); } break; case 'r': options.traceroute = 1; if (optarg) { options.traceroutehops = atoi(optarg); } break; case '?': default: usage(2); } } } if (0 > options.interval) { options.interval = DEFAULT_INTERVAL; } if (0 > options.wait) { options.wait = DEFAULT_WAIT; options.autowait = 1; if (options.verbose > 1) { fprintf(stderr, "%s: autowait is ON. " "Initial wait: %6.3f seconds\n", argv0, options.wait); } } if (optind + 1 != argc) { usage(2); } options.target = argv[optind]; if (SIG_ERR == signal(SIGINT, sigint)) { fprintf(stderr, "%s: signal(SIGINT, ...): %s\n", argv0, strerror(errno)); return 1; } if (0 > (fd = setupSocket())) { return 1; } if (options.traceroute) { return tracerouteMainloop(fd); } else { return pingMainloop(fd); } }
int main (int argc, char **argv) { int rc = 0; char c[4096]; getOsVer(); memset (&descriptors, '\0', sizeof(char *) * MAX_DESC); fd =setupSocket (); if (fd == -1) { fprintf(stderr,"Unable to continue without socket\n"); exit(1); } struct stat stbuf; fstat(1, &stbuf); if (stbuf.st_mode & S_IFCHR) { wantColors = 1; wantCurses = 1;} else {wantColors = 0; wantCurses = 0;} int arg = 1; for (arg = 1; arg < argc; arg++) { if (strcmp(argv[arg], "nc") == 0) wantCurses = 0; else if (strcmp(argv[arg], "once") == 0) {wantCurses = 0; wantOnce = 1; wantColors = 0;} else if (strcmp(argv[arg], "udp") == 0) { wantUDP = 1; wantTCP = 0;} else if (strcmp(argv[arg], "tcp") == 0) { wantTCP = 1; wantUDP = 0;} else { printHelp(); exit(2);} } nstat_msg_query_src_req qsreq; char ch; // Want both - we'll just filter int udpAdded = 0; int tcpAdded = 0 ; int gettingCounts = 0 ; int gotCounts = 0; addAll (fd, NSTAT_PROVIDER_TCP); if (wantCurses) { initscr(); cbreak(); noecho(); start_color(); nodelay (stdscr,1); } print_header(wantCurses); while (1) { //rc > 0) { if (wantCurses || wantOnce) { fd_set fds; struct timeval to; to.tv_sec = 0; to.tv_usec = DELAY; FD_ZERO (&fds); FD_SET (fd, &fds); // select on socket, rather than read.. rc = select(fd +1, &fds, NULL, NULL, &to); if (rc > 0) rc = read(fd,c,2048); else { // Timed out on select: now we can print if (wantOnce ) { print_descriptors(); exit(0);} else { qsreq.hdr.type= NSTAT_MSG_TYPE_QUERY_SRC ; // 1004 qsreq.srcref= 0xffffffff; //NSTAT_SRC_REF_ALL; qsreq.hdr.context = 1005; // This way I can tell if errors get returned for dead sources rc = write (fd, &qsreq, sizeof(qsreq)); } } } else rc = read (fd, c, 2048); // check rc. Meh. if (rc > 0) { nstat_msg_hdr *ns = (nstat_msg_hdr *) c; switch (ns->type) { case 10001: case 10002: case 10003: case 10004: rc = process_nstat_msg(c,rc); break; case 0: // Got all sources, or all counts // if we were getting sources, ask now for all descriptions if (!tcpAdded) { tcpAdded++; addAll (fd, NSTAT_PROVIDER_UDP); } else { if (!udpAdded) udpAdded++; } if (tcpAdded && udpAdded ) { if (!gettingCounts) { qsreq.hdr.type= NSTAT_MSG_TYPE_QUERY_SRC ; // 1004 qsreq.srcref= 0xffffffff; //NSTAT_SRC_REF_ALL; qsreq.hdr.context = 1005; // This way I can tell if errors get returned for dead sources rc = write (fd, &qsreq, sizeof(qsreq)); gettingCounts++; } else gotCounts++; } break; case 1: //Error message - these are usually for dead sources (context will be 1005) break; default: break; } } if (wantCurses) { ch = getch(); // could do lowercase instead of 'H'/'h', etc... if (ch != ERR) { if (ch == 'H' || ch =='h') printf("Too late now :-)\n"); if (ch == 'U' || ch =='u') {wantUDP = !wantUDP; setMessage(wantUDP ? "Showing UDP Sockets" :"Not showing UDP sockets"); } if (ch == 'T' || ch == 't') { wantTCP = !wantTCP; setMessage(wantTCP ? "Showing TCP Sockets" : "Not showing TCP sockets"); } if (ch == 'L' || ch == 'l') { wantListen= !wantListen; setMessage("Toggling TCP listeners"); } if (ch == 'P' || ch == 'p') { wantPackets = !wantPackets; setMessage(wantPackets ? "Showing Packets" : "Showing Bytes"); } if (ch == 'C' || ch == 'c') { wantColors = !wantColors; setMessage("Toggling color display"); } if (ch == 'K' || ch == 'k') { wantHumanReadable = !wantHumanReadable; } if (ch =='Q' || ch == 'q') { if (wantCurses) {endwin();}exit(0);} } } if (wantOnce > 1) exit(0); if (!wantOnce && gotCounts) { print_descriptors(); if (!wantCurses) memset (&descriptors, '\0', sizeof(char *) * MAX_DESC); } } // end while return (0); }
/* Main server routine */ void startServer(int port){ int socketDescriptor = setupSocket(port); if(socketDescriptor==-1) /* Return on failure, flag already set. */ return; /* Set timeout values */ struct timeval timeOut; timeOut.tv_sec = 0; timeOut.tv_usec = 0; fd_set master; /* Master socket descriptor set */ fd_set read_sds; /* Temporary socket descriptor set */ FD_ZERO(&master); FD_ZERO(&read_sds); int maxsd; /* Maximum descriptor number */ char buffer[MAX_BUFFER]; /* For incoming data storage */ /* Add current socket to master set */ FD_SET(socketDescriptor, &master); addToConnectionTable("broadcast",-1); /* Broadcast dummy user, to broadcast message */ maxsd = socketDescriptor; SERVER_SOCKET = socketDescriptor; std::cout<<"Server is ready for operations...\n"; /* Main server loop */ while(true){ memcpy(&read_sds, &master, sizeof(fd_set)); /* Make a temporary copy */ /* NULL for writefd and exceptfd (Not needed) */ int s = select(maxsd+1, &read_sds, NULL, NULL, &timeOut); if(s<0){ ERROR = E_SELECT; error_message = "Error using select."; #ifdef __DEBUG__ std::cout<<error_message<<std::endl; #endif continue; } /* Search for data to read */ for(int sock=0;sock<=maxsd;++sock){ if(FD_ISSET(sock, &read_sds)){ /* Pending read status found */ if(sock == socketDescriptor){ /* If match on socket descriptor of server */ int newSd = acceptConnection(socketDescriptor); if(newSd>-1){ FD_SET(newSd, &master); maxsd = std::max(maxsd, newSd); /* Update maximum descriptor */ } } else{ /* Handle data from client */ int nbytes = receiveData(sock, buffer); if(nbytes==-1){ removeFromConnectionTable(sock); close(sock); FD_CLR(sock, &master); /* Update the master socket descriptor set */ }else{ processRequest(sock, buffer); } } } } } }
void* rpmain(void* ctSock) { int sd, ct_sd, pc_sd; struct sockaddr_in replyaddr; ct_sd = *((int*)ctSock); if((pc_sd = getSockFromSock(ct_sd)) < 0) { printf("RP: Unable to receive socket to PC.\n"); pthread_exit(NULL); } if((sd = setupSocket(0)) < 0) { printf("RP: Unable to set up socket\n"); pthread_exit(NULL); } if(createAddr(htonl(INADDR_ANY), &replyaddr) == -1) { printf("RP: Unable to set up reply address\n"); pthread_exit(NULL); } while(1) { fd_set set; FD_ZERO(&set); FD_SET(ct_sd, &set); FD_SET(pc_sd, &set); if(select(((ct_sd > pc_sd) ? ct_sd : pc_sd) + 1, &set, NULL, NULL, NULL) == -1) { printf("Select error in RP\n"); close(sd); close(ct_sd); close(pc_sd); pthread_exit(NULL); } if(FD_ISSET(ct_sd, &set)) { switch(handleCommands(ct_sd)) { case 1: printf("rp shutting down.\n"); close(sd); close(ct_sd); close(pc_sd); pthread_exit(NULL); break; case -1: printf("RP:\tError while processing commands.\n"); close(sd); close(ct_sd); close(pc_sd); pthread_exit(NULL); break; } } if(FD_ISSET(pc_sd, &set)) { heartbeat* h; unsigned int len; h = getHeartbeatFromSock(pc_sd); if(h == NULL) { printf("RP:\tError while fetching heartbeat from PC\n"); close(sd); close(pc_sd); close(ct_sd); pthread_exit(NULL); } response* r = craftResponse(h); if(r == NULL) { printf("RP:\tError while crafting response\n"); close(sd); close(pc_sd); close(ct_sd); pthread_exit(NULL); } char* b = serializeResponse(r, &len); if(b == NULL) { printf("RP:\nError serializing response\n"); close(sd); close(pc_sd); close(ct_sd); pthread_exit(NULL); } ssize_t rc = sendto(sd, b, len, 0, (struct sockaddr*)&replyaddr, sizeof(replyaddr)); freeHeartbeat(h); free(r); free(b); if(rc < 0) { perror("sendto error"); close(sd); close(pc_sd); close(ct_sd); pthread_exit(NULL); } } } }
void ircbot::start() { int result; struct addrinfo hints; struct addrinfo *serverInfo; checkProperties(); //ensure that serverInfo is clear memset(&hints, 0, sizeof(hints)); // make sure the struct is empty //setup hints // don't care IPv4 or IPv6 hints.ai_family = AF_UNSPEC; // TCP stream sockets hints.ai_socktype = SOCK_STREAM; //Setup the structs if error print why if ((result = getaddrinfo(address.c_str(), port.c_str(), &hints, &serverInfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(result)); exit(-1); } //setup the socket setupSocket(serverInfo); //Connect openConnection(serverInfo); //Free the space used for serverInfo freeaddrinfo(serverInfo); //Receive some data int numbytes; char buf[MAXDATASIZE]; int count = 0; while (1) { count++; switch (count) { case 3: { //after 3 receives send data to server (as per IRC protacol) setNick(); setUser(); break; } case 4: { //Join a channel after we connect, this time we choose beaker string joinStr = "JOIN " + channel + "\r\n"; char *joinCStr = new char[ joinStr.length() + 1 ]; strcpy( joinCStr, joinStr.c_str() ); sendData(joinCStr); joinMessageSent = true; break; } default: { break; } } //Recv & print Data numbytes = recv(sock, buf, MAXDATASIZE - 1, 0); buf[numbytes] = '\0'; linesReceived++; fprintf(stderr, "%s", buf); //If Ping Recived, must respond with PONG otherwise connection will close if ( strstr(buf, "PING") != NULL ) { sendPong(buf); } // check for motd to verify connection status else if ( checkForMOTD(buf) ) { connected = true; } else if ( joinMessageSent && strstr(buf, "End of /NAMES list.") != NULL ) { joinedChannel = true; } else if ( joinMessageSent && !joinedChannel ) { string joinStr = "JOIN " + channel + "\r\n"; char *joinCStr = new char[ joinStr.length() + 1 ]; strcpy( joinCStr, joinStr.c_str() ); sendData(joinCStr); joinMessageSent = true; } else { msgHandle(buf); } //break if connection closed if (numbytes==0) { printf("CONNECTION CLOSED\n"); break; } } }
//Begins the connection void establishConnection(char *type, int *replay, char *ip) { //Ensure players cannot leave signal(SIGINT, leaveError); //Server variables struct sockaddr_in dataAddr; int clientSocket; struct sockaddr_in myAddr; int i, addrSize; char buffer[50]; //Game variables char o_phrase[40]; char my_phrase[40]; char h_o_phrase[40]; char h_my_phrase[40]; char board[1000]; board[0] = '\0'; char guess[80]; guess[0] = '\0'; int bytesRcv; int win = 0; //Server connect if (strcmp(type, "server") == 0) { setupSocket(&myListenSocket, &myAddr, type, ""); bindSocket(&myListenSocket, &myAddr); waitForConnection(&myListenSocket, &myAddr, &clientSocket, &dataAddr); //fix } //Client connect if (strcmp(type, "client") == 0) { setupSocket(&clientSocket, &dataAddr, type, ip); connectAsClient(&clientSocket, &dataAddr); } //Loop while the game is supposed to be played again while (*replay == 1) { //Creates the player's phrase, hides it and stores the unhidden phrase in the buffer game_createPhrase(my_phrase); game_toHidden(my_phrase, h_my_phrase); strcpy(buffer, my_phrase); //Send the phrase to the other player and wait for them to send back send(clientSocket, buffer, strlen(buffer), 0); fprintf(stdout, "Waiting for your opponent to create their secret phrase...\n"); //Store what was sent back in the opponent's phrase variable bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; strcpy(o_phrase, buffer); //Hide their phrase and create the board to print on screen game_toHidden(o_phrase, h_o_phrase); game_makeBoard(h_my_phrase, h_o_phrase, board); //Show the player their own phrase fprintf(stdout, "Your phrase: %s\n\n", my_phrase); //Counter to make the client go first initially i = 0; //Game loop while (1) { //Ensures that the client goes first if (i > 0 || strcmp(type, "server") == 0) { //Wait for opponent to guess and store guess in buffer fprintf(stdout, "Waiting for your opponent's guess...\n"); bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; strcpy(guess, buffer); //Compare guess with the actual phrase and check for win condition (1 = win, 0 = no win) game_guess(guess, my_phrase, h_my_phrase, &win); if (win == 1) { win = 0; //Wait to see if the opponent wants to play again fprintf(stdout, "Your opponent has won. Please wait while he decides he wants to play again...\n"); bytesRcv = recv(clientSocket, buffer, sizeof(buffer), 0); buffer[bytesRcv] = '\0'; //If opponent sends back "left", we need to do some things depending on if the opponent was the host or not if (strcmp(buffer, "left") == 0) { fprintf(stdout, "Your opponent left!\n"); //If you were the server and lost if (strcmp(type, "server") == 0) { //Re-setup the socket and listen for a new connection setupSocket(&clientSocket, &myAddr, type, ""); waitForConnection(&myListenSocket, &myAddr, &clientSocket, &dataAddr); i = 0; break; } //Close the client socket, change player type to server and listen for a new connection else { close(clientSocket); strcpy(type, "server"); setupSocket(&myListenSocket, &dataAddr, type, ""); waitForConnection(&clientSocket, &dataAddr, &myListenSocket, &myAddr); //TODO fix break; } *replay = -1; return; } //If they didn't send back "left", then they want to play again //So simply break out of the game loop to start a new game with new phrases else { system("clear"); fprintf(stdout, "Your opponent wants to play again, let's go!\n"); break; } } //Update the game board game_makeBoard(h_my_phrase, h_o_phrase, board); fprintf(stdout, "Your phrase: %s\n\n", my_phrase); fprintf(stdout, "Your opponent guessed: %s\n", guess); } //Ask for user input fprintf(stdout, "Guess a letter or the entire phrase.\n"); fgets(guess, sizeof(guess), stdin); guess[strlen(guess)-1] = '\0'; //Compare guess with the actual phrase and check for win condition (1 = win, 0 = no win), then update the game baord game_guess(guess, o_phrase, h_o_phrase, &win); game_makeBoard(h_my_phrase, h_o_phrase, board); fprintf(stdout, "Your phrase: %s\n\n", my_phrase); //Send the opponent what the user guessed strcpy(buffer, guess); send(clientSocket, buffer, strlen(buffer), 0); //If the user won, then see if they want to play again if (win == 1) { game_playAgain(replay); //Wants to play again if (*replay == 1) { strcpy(buffer, "stay"); send(clientSocket, buffer, strlen(buffer), 0); win = 0; break; } //Doesn't want to play again else { strcpy(buffer, "left"); send(clientSocket, buffer, strlen(buffer), 0); //Reset SIGINT to its default functionality signal(SIGINT, SIG_DFL); return; } } //Increment i allowing for the server to have a guess i++; } } //Close the final listen socket (never occurs) close(myListenSocket); }
JsonRpcTcpSocket::JsonRpcTcpSocket(QTcpSocket* socket) : m_socket(socket) { setupSocket(); }
void AsyncServerSocket::bind(uint16_t port) { struct addrinfo hints, *res, *res0; char sport[sizeof("65536")]; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; snprintf(sport, sizeof(sport), "%u", port); if (getaddrinfo(nullptr, sport, &hints, &res0)) { throw std::invalid_argument( "Attempted to bind address to socket with " "bad getaddrinfo"); } SCOPE_EXIT { freeaddrinfo(res0); }; auto setupAddress = [&] (struct addrinfo* res) { int s = socket(res->ai_family, res->ai_socktype, res->ai_protocol); // IPv6/IPv4 may not be supported by the kernel if (s < 0 && errno == EAFNOSUPPORT) { return; } CHECK_GE(s, 0); try { setupSocket(s); } catch (...) { closeNoInt(s); throw; } if (res->ai_family == AF_INET6) { int v6only = 1; CHECK(0 == setsockopt(s, IPPROTO_IPV6, IPV6_V6ONLY, &v6only, sizeof(v6only))); } SocketAddress address; address.setFromLocalAddress(s); sockets_.emplace_back(eventBase_, s, this, address.getFamily()); // Bind to the socket if (::bind(s, res->ai_addr, res->ai_addrlen) != 0) { folly::throwSystemError( errno, "failed to bind to async server socket for port"); } }; const int kNumTries = 25; for (int tries = 1; true; tries++) { // Prefer AF_INET6 addresses. RFC 3484 mandates that getaddrinfo // should return IPv6 first and then IPv4 addresses, but glibc's // getaddrinfo(nullptr) with AI_PASSIVE returns: // - 0.0.0.0 (IPv4-only) // - :: (IPv6+IPv4) in this order // See: https://sourceware.org/bugzilla/show_bug.cgi?id=9981 for (res = res0; res; res = res->ai_next) { if (res->ai_family == AF_INET6) { setupAddress(res); } } // If port == 0, then we should try to bind to the same port on ipv4 and // ipv6. So if we did bind to ipv6, figure out that port and use it, // except for the last attempt when we just use any port available. if (sockets_.size() == 1 && port == 0) { SocketAddress address; address.setFromLocalAddress(sockets_.back().socket_); snprintf(sport, sizeof(sport), "%u", address.getPort()); freeaddrinfo(res0); CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0)); } try { for (res = res0; res; res = res->ai_next) { if (res->ai_family != AF_INET6) { setupAddress(res); } } } catch (const std::system_error& e) { // if we can't bind to the same port on ipv4 as ipv6 when using port=0 // then we will try again another 2 times before giving up. We do this // by closing the sockets that were opened, then redoing the whole thing if (port == 0 && !sockets_.empty() && tries != kNumTries) { for (const auto& socket : sockets_) { if (socket.socket_ <= 0) { continue; } else if (shutdownSocketSet_) { shutdownSocketSet_->close(socket.socket_); } else { closeNoInt(socket.socket_); } } sockets_.clear(); snprintf(sport, sizeof(sport), "%u", port); freeaddrinfo(res0); CHECK_EQ(0, getaddrinfo(nullptr, sport, &hints, &res0)); continue; } throw; } break; } if (sockets_.size() == 0) { throw std::runtime_error( "did not bind any async server socket for port"); } }
JsonRpcTcpSocket::JsonRpcTcpSocket() : m_socket(new QTcpSocket(this)) { setupSocket(); }
int main (int argc, char **argv) { int rc = 0; char c[2048]; memset (&descriptors, '\0', sizeof(char *) * MAX_DESC); memset (&descriptorsModded, '\0', sizeof(int) * MAX_DESC); fd =setupSocket (); if (fd == -1) { fprintf(stderr,"Unable to continue without socket\n"); exit(1); } struct stat stbuf; fstat(1, &stbuf); if (stbuf.st_mode & S_IFCHR) { wantColors = 1; wantCurses = 1;} else {wantColors = 0; wantCurses = 0;} int arg = 1; for (arg = 1; arg < argc; arg++) { if (strcmp(argv[arg], "nc") == 0) wantCurses = 0; if (strcmp(argv[arg], "udp") == 0) { wantUDP = 1; wantTCP = 0;} if (strcmp(argv[arg], "tcp") == 0) { wantTCP = 1; wantUDP = 0;} } nstat_msg_query_src_req qsreq; nstat_msg_add_all_srcs aasreq; nstat_msg_get_src_description gsdreq; char ch; if (wantUDP) { aasreq.provider = 3; // aasreq.hdr.type = 1002; //NSTAT_MSG_TYPE_ADD_ALL_SRCS aasreq.hdr.context = 3; rc = write (fd, &aasreq, sizeof(aasreq)); } if (wantTCP) { aasreq.provider = 2 ; aasreq.hdr.type = 1002; //NSTAT_MSG_TYPE_ADD_ALL_SRCS aasreq.hdr.context = 2; rc = write (fd, &aasreq, sizeof(aasreq)); } if (wantCurses) { initscr(); cbreak(); noecho(); start_color(); nodelay (stdscr,1); } print_header(wantCurses); while (1) { //rc > 0) { if (wantCurses) { fd_set fds; struct timeval to; to.tv_sec = 0; to.tv_usec = 100; FD_ZERO (&fds); FD_SET (fd, &fds); // select on socket, rather than read.. rc = select(fd +1, &fds, NULL, NULL, &to); if (rc > 0) rc = read(fd,c,2048); } else rc = read (fd, c, 2048); // check rc. Meh. if (rc > 0) { nstat_msg_hdr *ns = (nstat_msg_hdr *) c; switch (ns->type) { case 10001: { nstat_msg_src_added *nmsa = (nstat_msg_src_added *) (c); gsdreq.hdr.type= 1005; //NSTAT_MSG_TYPE_GET_SRC_DESC gsdreq.srcref=nmsa->srcref; gsdreq.hdr.context = 1005; // This way I can tell if errors get returned for dead sources rc = write (fd, &gsdreq, sizeof(gsdreq)); descriptorsModded[nmsa->srcref] = 1; break; } case 10002: { //struct nstat_msg_src_removed *rem; nstat_msg_src_removed *nmsr = (nstat_msg_src_removed *) (c); if(wantCurses) mvhline(nmsr->srcref + 2, 1, '-' , strlen(descriptors[nmsr->srcref])); descriptors[nmsr->srcref] = NULL; // or free.. descriptorsModded [nmsr->srcref] = 1; // or free.. break; } case 10003: rc = print_nstat_msg(c,rc); break; case 10004: rc = print_nstat_msg(c,rc); break; case 0: break; case 1: //Error message - these are usually for dead sources (context will be 1005) break; default: break; } } if (wantCurses) { int i; ch = getch(); if (ch != ERR) { if (ch == 'H' || ch =='h') printf("HELP\n"); if (ch == 'U' || ch =='u') {wantUDP = !wantUDP; setMessage("Toggling UDP sockets"); } if (ch == 'T' || ch == 't') { wantTCP = !wantTCP; setMessage("Toggling TCP sockets"); } if (ch == 'L' || ch == 'l') { wantListen= !wantListen; setMessage("Toggling TCP listeners"); } if (ch == 'C' || ch == 'c') { wantColors = !wantColors; setMessage("Toggling color display"); } wantRefresh = 1; } } print_descriptors(); } return (0); }