PacketInfo Client::receivePacket( bool is_nonblocking ) { if ( udp_socket < 0 ) openSocket(); int flags = 0; if ( is_nonblocking ) flags |= MSG_DONTWAIT; sockaddr_in peer_address; socklen_t peer_address_size = sizeof( peer_address ); std::vector<uint8_t> receive_buffer( UDP_RECEIVE_BUFFER_SIZE ); int recv_size = recvfrom( udp_socket, receive_buffer.data(), UDP_RECEIVE_BUFFER_SIZE, flags, reinterpret_cast<sockaddr *>( &peer_address ), &peer_address_size ); if ( recv_size < 0 ) { int error_num = errno; if ( error_num == EAGAIN ) { PacketInfo info; return info; } std::perror( "cannot recv" ); throw SocketError( get_error_message( "cannot recv packet", error_num ) ); } PacketInfo info; info.source_address = convertAddressBinaryToString( peer_address.sin_addr ); info.source_port = ntohs( peer_address.sin_port ); info.payload = receive_buffer; return info; }
uint16_t Client::sendPacket( const WireFormat &data ) { if ( udp_socket < 0 ) openSocket(); return data.send( udp_socket, NULL, 0 ); }
/* * initExpprocSocket() * * Creates the listen socket for communication to Expproc fro other processes * * instead of signal handler etc, this routine create a thread to handle the accept * thus removing the need for socketfuncs.c and asyncIO.c * * Author greg Brissey 3/12/2006 */ int initExpprocSocket() { int status, ival; int applPort; void *AcceptConnection( void *arg); pApplSocket = createSocket( SOCK_STREAM ); if (pApplSocket == NULL) /* each call to program in */ return( -1 ); /* sockets.c sets errno */ ival = openSocket( pApplSocket ); if (ival != 0) return( -1 ); ival = bindSocketAnyAddr( pApplSocket ); if (ival != 0) { errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: bindSocketAnyAddr failed:" ); return( -1 ); } applPort = returnSocketPort( pApplSocket ); ival = listenSocket( pApplSocket ); if (ival != 0) { errLogSysRet(ErrLogOp,debugInfo,"initExpprocSocket: listenSocket failed:" ); return( -1 ); } savePortInfo( applPort ); pAcceptQueue = rngBlkCreate(128,"AcceptQ", 1); /* accepted socket queue */ /* create thread to handle the accept */ status = pthread_create (&AcceptThreadId, NULL, AcceptConnection, (void*) pApplSocket); return( 0 ); }
int main (int argc, char *argv[]) { char hostIPaddr[80], *cc, *pfft; int sd = 0; struct sockaddr_in si; printf("You can use ONLY for YOUR Messaging Server 3.6\n"); if (argc != 2) { printf("Usage: %s IPaddress \n",argv[0]); exit(1); } else strcpy (hostIPaddr, argv[1]); sd = openSocket(&si,hostIPaddr); if (sd < 1) { printf("failed!\n"); exit(-1); } sendRCPT2( sd ); close (sd); exit(0); }
int deliverMessage( char *interface, char *message ) { char tmpstring[ 256 ]; int ival1, ival2; int ival, mlen; MSG_Q_ID tmpMsgQ; if (interface == NULL) return( -1 ); if (message == NULL) return( -1 ); mlen = strlen( message ); if (mlen < 1) return( -1 ); ival = sscanf( interface, "%s %d %d\n", &tmpstring[ 0 ], &ival1, &ival2 ); /* * diagPrint(debugInfo,"Expproc deliverMessage ----> host: '%s', port: %d,(%d,%d) pid: %d\n", * tmpstring,ival1,0xffff & ntohs(ival1), 0xffff & htons(ival1), ival2); */ if (ival >= 3) { int replyPortAddr; char *hostname; Socket *pReplySocket; replyPortAddr = ival1; hostname = &tmpstring[ 0 ]; pReplySocket = createSocket( SOCK_STREAM ); if (pReplySocket == NULL) return( -1 ); ival = openSocket( pReplySocket ); if (ival != 0) return( -1 ); /* replyPortAddr is already in network order, * so switch back so sockets.c can switch back */ ival = connectSocket( pReplySocket, hostname, 0xFFFF & htons(replyPortAddr) ); if (ival != 0) return( -2 ); writeSocket( pReplySocket, message, mlen ); closeSocket( pReplySocket ); free( pReplySocket ); return( 0 ); } tmpMsgQ = openMsgQ( interface ); if (tmpMsgQ == NULL) return( -1 ); ival = sendMsgQ( tmpMsgQ, message, mlen, MSGQ_NORMAL, NO_WAIT ); closeMsgQ( tmpMsgQ ); return( ival ); }
rice::p2p::commonapi::Cancellable* org::mpisws::p2p::transport::networkinfo::NetworkInfoTransportLayer::getId(::java::net::InetSocketAddress* bootstrap, int8_t index, ::rice::Continuation* c, ::java::util::Map* options) { auto hdr = new ::int8_tArray(int32_t(2)); (*hdr)[int32_t(0)] = HEADER_ID_REQUEST_BYTE; (*hdr)[int32_t(1)] = index; auto ret = new ::rice::p2p::util::AttachableCancellable(); npc(ret)->attach(openSocket(bootstrap, hdr, new NetworkInfoTransportLayer_getId_2(this, c), options)); return ret; }
void KCrash::startDrKonqi(const char *argv[], int argc) { int socket = openSocket(); if(socket < -1) { startDirectly(argv, argc); return; } klauncher_header header; header.cmd = LAUNCHER_EXEC_NEW; const int BUFSIZE = 8192; // make sure this is big enough char buffer[BUFSIZE + 10]; int pos = 0; long argcl = argc; memcpy(buffer + pos, &argcl, sizeof(argcl)); pos += sizeof(argcl); for(int i = 0; i < argc; ++i) { int len = strlen(argv[i]) + 1; // include terminating \0 if(pos + len > BUFSIZE) { fprintf(stderr, "BUFSIZE in KCrash not big enough!\n"); startDirectly(argv, argc); return; } memcpy(buffer + pos, argv[i], len); pos += len; } long env = 0; memcpy(buffer + pos, &env, sizeof(env)); pos += sizeof(env); long avoid_loops = 0; memcpy(buffer + pos, &avoid_loops, sizeof(avoid_loops)); pos += sizeof(avoid_loops); header.arg_length = pos; write_socket(socket, (char *)&header, sizeof(header)); write_socket(socket, buffer, pos); if(read_socket(socket, (char *)&header, sizeof(header)) < 0 || header.cmd != LAUNCHER_OK) { startDirectly(argv, argc); return; } long pid; read_socket(socket, buffer, header.arg_length); pid = *((long *)buffer); alarm(0); // Seems we made it.... for(;;) { if(kill(pid, 0) < 0) _exit(253); sleep(1); // the debugger should stop this process anyway } }
int initClient ( int pPort, const char *pHost ) { // local variables int socketFile; // open socket and connect to host socketFile = openSocket ( ); connectSocket ( socketFile, pPort, pHost ); return socketFile; }
bool ProtocolUDP::init_derived() { int optval = 1; char buf[SOCKADDR_SIZE]; struct sockaddr *sa = (struct sockaddr *)buf; socklen_t sa_len; SocketAddress *addr = NULL; if (!localIface) { HAGGLE_ERR("%s Could not create UDP socket, no local interface\n", getName()); return false; } #if defined(ENABLE_IPv6) addr = localIface->getAddress<IPv6Address>(); #endif if (!addr) addr = localIface->getAddress<IPv4Address>(); if (!addr) { HAGGLE_ERR("%s Could not create UDP socket, no IP address\n", getName()); return false; } sa_len = addr->fillInSockaddr(sa); if (!openSocket(AF_INET, SOCK_DGRAM, 0, true)) { HAGGLE_ERR("%s Could not open UDP socket\n", getName()); return false; } // For application IPC socket we need a large receive buffer. if (!multiplyReceiveBufferSize(2)) { HAGGLE_ERR("%s Could not increase receive buffer size.\n", getName()); } if (!setSocketOption(SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))) { closeSocket(); HAGGLE_ERR("%s setsockopt SO_REUSEADDR failed\n", getName()); return false; } if (!setSocketOption(SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval))) { closeSocket(); HAGGLE_ERR("%s setsockopt SO_BROADCAST failed\n", getName()); return false; } if (!bind(sa, sa_len)) { closeSocket(); return false; } return true; }
org::mpisws::p2p::transport::SocketRequestHandle* org::mpisws::p2p::transport::networkinfo::NetworkInfoTransportLayer::openSocket(::java::net::InetSocketAddress* i, ::org::mpisws::p2p::transport::SocketCallback* deliverSocketToMe, ::java::util::Map* options) { if(npc(logger)->level <= ::rice::environment::logging::Logger::INFO - int32_t(50)) npc(logger)->log(::java::lang::StringBuilder().append(u"openSocket("_j)->append(static_cast< ::java::lang::Object* >(i)) ->append(u","_j) ->append(static_cast< ::java::lang::Object* >(deliverSocketToMe)) ->append(u","_j) ->append(static_cast< ::java::lang::Object* >(options)) ->append(u")"_j)->toString()); return openSocket(i, HEADER_PASSTHROUGH_, deliverSocketToMe, options); }
uint16_t Client::sendPacket( const uint8_t *data, uint16_t size ) { if ( udp_socket < 0 ) openSocket(); int sent_size = send( udp_socket, data, size, 0 ); if ( sent_size < 0 ) { std::string msg = "cannot send to " + parameters.address + ":" + boost::lexical_cast<std::string>( parameters.port ); throw SocketError( get_error_message( msg, errno ) ); } return sent_size; }
int initServer ( int pPort ) { // local variables int socketFile; // open / bind / listen on socket socketFile = openSocket ( ); bindSocket ( socketFile, pPort ); listen ( socketFile, NETWORK_BACKLOG_QUEUE ); return socketFile; }
bool ProtocolRFCOMM::initbase() { struct sockaddr_bt localAddr; if (isConnected()) { // Nothing to do return true; } if (!openSocket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM, isServer())) { HAGGLE_ERR("Could not create RFCOMM socket\n"); return false; } memset(&localAddr, 0, sizeof(struct sockaddr_bt)); localAddr.bt_family = AF_BLUETOOTH; localAddr.bt_channel = channel & 0xff; #ifndef OS_WINDOWS if (localIface) { BluetoothAddress *addr = localIface->getAddress<BluetoothAddress>(); if (addr) { // Binding RFCOMM sockets to a hardware address does not // seem to work in Windows BDADDR_swap(&localAddr.bt_bdaddr, addr->getRaw()); } } #endif if (isServer()) { localAddr.bt_channel = channel & 0xff; /* If this is a server we bing to a specific channel to listen on */ if (!bind((struct sockaddr *)&localAddr, sizeof(localAddr))) { closeSocket(); #ifdef OS_WINDOWS HAGGLE_ERR("Bind failed for local address WSA error=%s\n", StrError(WSAGetLastError())); #endif HAGGLE_ERR("Could not bind local address for RFCOMM socket\n"); return false; } HAGGLE_DBG("Bound RFCOMM server to channel=%d\n", channel); } else { HAGGLE_DBG("Created RFCOMM client on channel=%d\n", channel); } return true; }
/* * Host constructor: opens a socket on the specified port * and listens for and accepts connections (on separate thread if specified). */ tcpSocket::tcpSocket(int port, bool threaded) { std::cout << "opening port " << port << std::endl; this->port = port; this->threaded = threaded; openSocket(); startListening(); std::thread t(&tcpSocket::acceptConnections, this); t.detach(); }
void setListeningConnection(Connection *conn, const struct sockaddr_in laddr) { if (getConnectionState(conn) != RUSP_CLOSED) ERREXIT("Cannot setup listening connection: connection not closed."); conn->sock.fd = openSocket(); setSocketReusable(conn->sock.fd); bindSocket(conn->sock.fd, &laddr); setConnectionState(conn, RUSP_LISTEN); }
/* DEPS: * Global: nameList, NUM_SERVERS */ int* initReduce(){ // make an array for all of our sockets int sockIDs[NUM_SERVERS]; int i; // setup all the sockets we need for (i = 0; i < NUM_SERVERS; i++){ sockIDs[i] = openSocket(); printf("connecting.... %s\n", nameList[i]); makeConnection(sockIDs[i], nameList[i], PORT); } return sockIDs; }
// Find 64k id's that all point to the specified worker void runTestsWithPrefix(char* prefix, char* serverIp) { printf("Running tests against prefix %s\n", prefix); int clientNum=0; char clientIdStr[20]; for (clientNum=0; clientNum < TEST_CONNS; clientNum++) { snprintf(clientIdStr, 20, "%s%d", prefix, clientNum); int worker = findWorker(clientIdStr); openSocket(worker, clientIdStr, serverIp); if (!(clientNum%1000)) { printf("%s\n", clientIdStr); } } printf ("Opened all\n"); }
int main(int argc, char **argv) { int a,b,c,res; float d; daveInterface * di; daveConnection * dc; _daveOSserialType fds; daveSetDebug(daveDebugPrintErrors); if (argc<2) { printf("Usage: testISO_TCP IP-Address of CP\n"); exit(-1); } fds.rfd=openSocket(102, argv[1]); fds.wfd=fds.rfd; if (fds.rfd>0) { di =daveNewInterface(fds,"IF1",0, daveProtoISOTCP, daveSpeed187k); daveSetTimeout(di,5000000); dc =daveNewConnection(di,2,0, 2); // insert your rack and slot here if (0==daveConnectPLC(dc)) { printf("Connected.\n"); res=daveReadBytes(dc,daveFlags,0,0,16,NULL); if (0==res) { a=daveGetU32(dc); b=daveGetU32(dc); c=daveGetU32(dc); d=daveGetFloat(dc); printf("FD0: %d\n",a); printf("FD4: %d\n",b); printf("FD8: %d\n",c); printf("FD12: %f\n",d); } else printf("failed! (%d)\n",res); printf("Finished.\n"); return 0; } else { printf("Couldn't connect to PLC.\n"); return -2; } } else { printf("Couldn't open TCP port. \nPlease make sure a CP is connected and the IP address is ok. \n"); return -1; } }
/************************************************************** * * sendAsync - Send a Message to a Vnmr style Async Message Socket * * RETURNS: * 1 on success or -1 on failure * * Author Greg Brissey 10/6/94 */ int sendAsync(char *machine,int port,char *message) { Socket *SockId; int i,result; if ( (SockId = createSocket( SOCK_STREAM )) == NULL) { return( -1 ); } /* --- try several times then fail --- */ for (i=0; i < 5; i++) { result = openSocket(SockId); /* open * setup */ if (result != 0) { /* perror("sendacq(): socket"); */ errLogSysRet(ErrLogOp,debugInfo,"sendAsync(): Error, could not create socket\n"); return(-1); } if ((result = connectSocket(SockId, machine, port)) != 0) { /* errLogSysRet(ErrLogOp,debugInfo,"connect: "); */ /* --- Is Socket queue full ? --- */ if (errno != ECONNREFUSED && errno != ETIMEDOUT) { /* NO, some other error */ errLogSysRet(ErrLogOp,debugInfo,"sendAsync():aborting, connect error"); return(-1); } } else /* connection established */ { break; } errLogRet(ErrLogOp,debugInfo,"sendAsync(): Socket queue full, will retry %d\n",i); closeSocket(SockId); sleep(5); } if (result != 0) /* tried MAXRETRY without success */ { errLogRet(ErrLogOp,debugInfo,"sendAsync(): Max trys Exceeded, aborting send\n"); return(-1); } writeSocket(SockId,message,strlen(message)); closeSocket(SockId); return(1); }
static pid_t startFromKdeinit(int argc, const char *argv[]) { int socket = openSocket(); if( socket < -1 ) return 0; klauncher_header header; header.cmd = LAUNCHER_EXEC_NEW; const int BUFSIZE = 8192; // make sure this is big enough char buffer[ BUFSIZE + 10 ]; int pos = 0; long argcl = argc; memcpy( buffer + pos, &argcl, sizeof( argcl )); pos += sizeof( argcl ); for( int i = 0; i < argc; ++i ) { int len = strlen( argv[ i ] ) + 1; // include terminating \0 if( pos + len >= BUFSIZE ) { fprintf( stderr, "BUFSIZE in KCrash not big enough!\n" ); return 0; } memcpy( buffer + pos, argv[ i ], len ); pos += len; } long env = 0; memcpy( buffer + pos, &env, sizeof( env )); pos += sizeof( env ); long avoid_loops = 0; memcpy( buffer + pos, &avoid_loops, sizeof( avoid_loops )); pos += sizeof( avoid_loops ); header.arg_length = pos; write_socket(socket, (char *) &header, sizeof(header)); write_socket(socket, buffer, pos); if( read_socket( socket, (char *) &header, sizeof(header)) < 0 || header.cmd != LAUNCHER_OK ) { return 0; } long pid; read_socket(socket, buffer, header.arg_length); pid = *((long *) buffer); return static_cast<pid_t>(pid); }
int main(int argc, char * argv[]) { char * serverPort = DEFAULT_PORT; int ch; while((ch = getopt(argc, argv, "p:h")) != -1) { switch(ch) { // Set the server port. If not given, DEFAULT_PORT is used. case 'p': serverPort = optarg; break; case 'h': default: usage(); } } int sd = openSocket(NULL, serverPort, SERVER); if (!sd) { fprintf(stderr, "Unable to create server socket.\n"); exit(EXIT_FAILURE); } printf("Waiting for connections...\n"); // Wait for a client to connect then pass off the socket descriptor to a // new thread to deal with it. Go back to wait for another client. while (1 == 1) { // TODO: Catch cntr-c. Then we can set a flag and check for it in // this loop. Maybe accept stdin as well? // If the user wants to exit, if no clients connected, let them exit. // Otherwise ask if they are sure. pthread_t tid; int cd = waitForConnection(sd); if (cd == -1) { fprintf(stderr, "Could not accept client connection.\n"); continue; } pthread_create(&tid, NULL, handleConnection, &cd); } close(sd); }
SocketServer::SocketServer(const QString s, QObject *parent) : QThread(parent), _session(s) { qRegisterMetaType<QAbstractSocket::SocketError> ("QAbstractSocket::SocketError"); _tcpServer = new QTcpServer; connect(_tcpServer, SIGNAL(newConnection()), SLOT(onNewConnection())); connect(_tcpServer, SIGNAL(disconnected()), SLOT(onDisconnect())); // connect(_socket, SIGNAL(readyRead()), SLOT(onReadyRead())); connect(_tcpServer, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onError(QAbstractSocket::SocketError))); _port = 4244; openSocket(); }
//Constructor UDPClient::UDPClient(int32_t v4_port, int32_t v6_port, const IPAddress& address): addr(address),myIP(myIPAddress::singleton()) { if(address.isIPv6()) slen=sizeof(ipv6_addr); else slen=sizeof(ipv4_addr); active = false; connected = false; intIPv4_Port = v4_port; intIPv6_Port = v6_port; conTrack = 0; resetVal = 15; broadcast = false; openSocket(); }
void sendPacket(std::vector<void*> &headers, std::vector<unsigned int> &sizes) { int index = 0; struct Ethernet::header_s *eth = NULL; bool isFirst = true; total_size = 0; bzero(buffer, 65535); for (std::vector<void*>::iterator it = headers.begin(); it != headers.end(); ++it) { if (isFirst) { isFirst = false; eth = (struct Ethernet::header_s*)(*it); } memcpy(buffer + total_size, *it, sizes.at(index)); total_size += sizes.at(index); ++index; } openSocket(); initPacket(eth->src_mac_address); start(); }
/* executes continuously after setup() runs */ void loop() { static system_tick_t last = 0; ssize_t s = udp.receivePacket(buf, sizeof(buf)); if (s > 0) { char tmp[IP_ADDR_STRLEN_MAX] = {}; auto ip = udp.remoteIP(); Log.trace("Received %d bytes from %s#%u", s, inet_inet_ntop(AF_INET6, ip.raw().ipv6, tmp, sizeof(tmp)), udp.remotePort()); } if ((millis() - last) >= PERIOD) { size_t len = random(1, sizeof(buf)); rng.gen((char*)buf, len); auto r = udp.sendPacket(buf, len, mcastAddr, PORT); Log.trace("Sent %u bytes to %s#%u : %d %d", len, MULTICAST_ADDR, PORT, r, errno); last = millis(); if (r < 0) { openSocket(); } } }
int sendSspd(const char * socketName, const char * uuid, const char * location, const char * server) { int s = openSocket(socketName); if (s < 0) { printf("Error: unable to open socket %s\n", socketName); return -1; } char buffer[2048]; snprintf(buffer, sizeof(buffer), "%s::upnp:rootdevice", uuid); submitDevice(s, "upnp:rootdevice", buffer, server, location); submitDevice(s, uuid, uuid, server, location); snprintf(buffer, sizeof(buffer), "%s::urn:schemas-upnp-org:device:Basic:1", uuid); submitDevice(s, "urn:schemas-upnp-org:device:Basic:1", buffer, server, location); close(s); return 0; }
int main() { connection conn; package p; if( openSocket( &conn ) != 1 ) printf("Erro ao abrir socket!"); do { getPackage( &conn, &p ); if( !verifyIntegrity( &p ) ) printf("Mensagem com erro!"); executeCommand( &p ); } while(1); return 1; }
//FBO analyse frame on the server once a while // port is 5000 // WARNING this routine is not thread safe int analyse_video(uint8_t* frame, int width, int height, int size){ static int call_count = 0; static int init_callback_done=0; static int sockfd = 0; //FBO DO THE JOB HERE //fprintf(stderr,"Calling sample_video (call count = %d)\n",call_count); jakopter_com_write_int(com_out, 0, call_count); // in all cases need to return the call back instance if (init_callback_done){ call_count++; int doit = jakopter_com_read_int(com_in, 28); if (doit) { copyDataInBuffer(imageBuffer,frame,IMAGE_TO_ANALYZE,width,height,width); sendLargeData(sockfd,imageBuffer,IMAGE_BUFFER_SIZE); receiveLargeData(sockfd, resultBuffer, ANALYSIS_BUFFER_SIZE); int coord_i_min = *((int *) &(resultBuffer[0])); int coord_j_min = *((int *) &(resultBuffer[4])); double valx = *((double *) &(resultBuffer[8])); int samplenum = *((int *) &(resultBuffer[16])); // show it on the video also //printf("server answer sample %d result %d %d %f\n",samplenum, coord_i_min, coord_j_min, valx); //Return result and status here jakopter_com_write_int(com_out, 4, samplenum); jakopter_com_write_int(com_out, 8, coord_i_min); jakopter_com_write_int(com_out, 12, coord_j_min); jakopter_com_write_float(com_out, 16, valx); } } else { call_count = 0; init_callback_done = 1; // Open the socket sockfd = openSocket((char *) "localhost",5000); jakopter_com_write_int(com_out, 4, -1); jakopter_com_write_int(com_out, 8, 0); jakopter_com_write_int(com_out, 12, 0); jakopter_com_write_float(com_out, 16, 0.0); } return 0; }
int initServer(char * servidor,int numPort,int longMax){ if(daemonizar(servidor)==ERROR){ printf("Error al daemonizar\n"); return ERROR; } if((socketId = openSocket())<0){ printf("Error al crear el socket\n"); exit(ERROR); } if(assignSocket(socketId,numPort)<0){ printf("Error al asignar el puerto al socket\n"); exit(ERROR); } //abrira la cola de procesos if(openQueue(socketId,longMax) !=0){ printf("Error al abrir la cola\n"); exit(ERROR); } return OK; }
NetSocket Net::openListenPort(U16 port) { if(Journal::IsPlaying()) { U32 ret; Journal::Read(&ret); return NetSocket(ret); } NetSocket sock = openSocket(); if (sock == InvalidSocket) { Con::errorf("Unable to open listen socket: %s", strerror(errno)); return InvalidSocket; } if (bind(sock, port) != NoError) { Con::errorf("Unable to bind port %d: %s", port, strerror(errno)); ::closesocket(sock); return InvalidSocket; } if (listen(sock, 4) != NoError) { Con::errorf("Unable to listen on port %d: %s", port, strerror(errno)); ::closesocket(sock); return InvalidSocket; } setBlocking(sock, false); addPolledSocket(sock, Listening); if(Journal::IsRecording()) Journal::Write(U32(sock)); return sock; }