bool NetInputRecvBlocking( NetInputChannel *n, bool (*tryParseFunc)(UDPpacket *, void *), void *data) { UDPpacket packet; packet.data = n->buf; packet.maxlen = NET_INPUT_MAX_PACKET_LEN; int numrecv; do { numrecv = SDLNet_UDP_Recv(n->sock, &packet); if (numrecv < 0) { printf("SDLNet_UDP_Recv: %s\n", SDLNet_GetError()); return false; } else if (numrecv > 0) { if (!tryParseFunc(&packet, data)) { return false; } } } while (numrecv == 0); return true; }
int udpsend(UDPsocket sock, int channel, UDPpacket *out, UDPpacket *in, Uint32 delay, Uint8 expect, int timeout) { Uint32 t,t2; int err; in->data[0]=0; t=SDL_GetTicks(); do { t2=SDL_GetTicks(); if(t2-t>(Uint32) timeout) { printf("timed out\n"); return(0); } if(!SDLNet_UDP_Send(sock, channel, out)) { printf("SDLNet_UDP_Send: %s\n",SDLNet_GetError()); exit(1); } err=SDLNet_UDP_Recv(sock, in); if(!err) SDL_Delay(delay); } while(!err || (in->data[0]!=expect && in->data[0]!=ERROR)); if(in->data[0]==ERROR) printf("received error code\n"); return(in->data[0]==ERROR?-1:1); }
///-----------MAIN LOOP-------------- void Server::MainLoop() { while(serverIsRunning) { if (SDLNet_UDP_Recv(sock, input)) //Check if the server is receiving data from the clients { if(RECEIVED_KEY == LOG_IN_KEY) { string username = GetQueryArgument(input->data, 2); char logInStatus[1]; logInStatus[0] = profile.LogIn(username, GetQueryArgument(input->data, 3)); if(logInStatus[0] == LOG_IN_SUCCESS) AddNewClient(input->address.host, input->address.port, username, input->channel); SendData((Uint8*)logInStatus, sizeof(logInStatus)); } else if(RECEIVED_KEY == REGISTER_KEY) { char registerStatus[1]; registerStatus[0] = profile.Register(GetQueryArgument(input->data, 2), GetQueryArgument(input->data, 3)); SendData((Uint8*)registerStatus, sizeof(registerStatus)); cout << "New profile registered: " << GetQueryArgument(input->data, 2) << endl; } else if(RECEIVED_KEY == KICK_KEY) { KickClient(input->address.host); } Server::SendBack(); receivedData = ""; } } }
int UDP_Socket::receive(IPaddress &ip, const void * const &data, const Uint16 &num_bytes) { IPaddress ipaddress = {0, 0}; UDPpacket packet = { -1, reinterpret_cast<Uint8 *>(const_cast<void *>(data)), 0, num_bytes, 0, ipaddress }; int retval = SDLNet_UDP_Recv(sock, &packet); if(retval == -1) throw Socket_Closed(); else if(!retval) { packet.address.host = 0; packet.address.port = 0; } ip = packet.address; return packet.len; }
int game_host::waitForClient_test() { cout << "waiting for first player to connect...\n"; while(!(player1sd = SDLNet_TCP_Accept(sd))) //wait for first connection, with 50ms delay to keep CPU down SDL_Delay(50); string ipMess = ""; while(SDLNet_UDP_Recv(p1UDPsock, UDPpack1) == 0) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack1->address)); cout << this->recieveMessagep1() << "\n"; //on successful connect, client sends a message SDLNet_TCP_AddSocket(socketset, player1sd); //could error check here this->player1ip = SDLNet_TCP_GetPeerAddress(player1sd); //SDLNet_ResolveHost(&(UDPpack1->address), cl.c_str(), port); //player2ip->host = SDLNet_TCP_GetPeerAddress(player1sd)->host; //player2ip->port = port; //UDPpack1->address = *player1ip; sendtoP1_test("1SIG:START"); cout << "client connected, continuing...\n"; return 1; }
int NET::UDPRecv(UDPpacket * p, int channel, int timeout) { Uint32 t, t2; t = SDL_GetTicks(); t2 = SDL_GetTicks(); bool success = false; while (!success && t2 - t < (Uint32) timeout) { int retval = SDLNet_UDP_Recv(remote_socket, p); if (retval >= 1) { success = true; } t2=SDL_GetTicks(); } if (success) { datacounter_rx += p->len; return UDP_SUCCESS; } if (t2 - t >= (Uint32) timeout) { return UDP_TIMEOUT; } return UDP_FAILURE; }
// ZZZ: the socket listening thread loops in this function. It calls the registered // packet handler when it gets something. static int receive_thread_function(void*) { while(true) { // We listen with a timeout so we can shut ourselves down when needed. int theResult = SDLNet_CheckSockets(sSocketSet, 1000); if(!sKeepListening) break; if(theResult > 0) { theResult = SDLNet_UDP_Recv(sSocket, sUDPPacketBuffer); if(theResult > 0) { if(take_mytm_mutex()) { ddpPacketBuffer.protocolType = kPROTOCOL_TYPE; ddpPacketBuffer.sourceAddress = sUDPPacketBuffer->address; ddpPacketBuffer.datagramSize = sUDPPacketBuffer->len; // Hope the other guy is done using whatever's in there! // (As I recall, all uses happen in sPacketHandler and its progeny, so we should be fine.) memcpy(ddpPacketBuffer.datagramData, sUDPPacketBuffer->data, sUDPPacketBuffer->len); sPacketHandler(&ddpPacketBuffer); release_mytm_mutex(); } else fdprintf("could not take mytm mutex - incoming packet dropped"); } } } return 0; }
int udpListener(void* data) { UDPpacket *packetIn; packetIn = SDLNet_AllocPacket(16); short clientId=0, keysPressed=0; puts("udplistener startad."); while (1) { if (SDLNet_UDP_Recv(udpRecvSock,packetIn)) { if ((clientId = IdFromPort(packetIn->address.port,packetIn->address.host)) < 0 ) { printf("error packet/client conflict"); } //printf("data:%d\n",packetIn->data[0]); keysPressed = packetIn->data[0]; if ((keysPressed & 3) == 1) ships[clientId].angleVel=5; else if ((keysPressed & 3) == 2) ships[clientId].angleVel=-5; else ships[clientId].angleVel = 0; if ((keysPressed & 4) == 4) ships[clientId].acceleration=true; else ships[clientId].acceleration=false; if ((keysPressed & 8) == 8) ships[clientId].shooting=true; else ships[clientId].shooting=false; } SDL_Delay(5); } return 0; }
static boolean NET_SDL_RecvPacket(net_addr_t **addr, net_packet_t **packet) { int result; result = SDLNet_UDP_Recv(udpsocket, recvpacket); if (result < 0) { I_Error("NET_SDL_RecvPacket: Error receiving packet: %s", SDLNet_GetError()); } // no packets received if (result == 0) return false; // Put the data into a new packet structure *packet = NET_NewPacket(recvpacket->len); memcpy((*packet)->data, recvpacket->data, recvpacket->len); (*packet)->len = recvpacket->len; // Address *addr = NET_SDL_FindAddress(&recvpacket->address); return true; }
size_t I_GetPacket(packet_header_t* buffer, size_t buflen) { int checksum; size_t len; int status; status = SDLNet_UDP_Recv(udp_socket, udp_packet); len = udp_packet->len; if (buflen<len) len=buflen; if ( (status!=0) && (len>0) ) memcpy(buffer, udp_packet->data, len); sentfrom=udp_packet->channel; #ifndef SDL_NET_UDP_PACKET_SRC sentfrom_addr=udp_packet->address; #else sentfrom_addr=udp_packet->src; /* cph - allow for old SDL_net library */ #endif checksum=buffer->checksum; buffer->checksum=0; if ( (status!=0) && (len>0)) { byte psum = ChecksumPacket(buffer, udp_packet->len); /* fprintf(stderr, "recvlen = %u, stolen = %u, csum = %u, psum = %u\n", udp_packet->len, len, checksum, psum); */ if (psum == checksum) return len; } return 0; }
int cearthctx_connect(cearth_ctx *ctx, const char *usr, const char *tok) { /* Convert tok from hex to binary */ unsigned char tok_b[LOGIN_TOKENSIZE / 2]; for (int i = 0; i < LOGIN_TOKENSIZE / 2; i++) { sscanf(i * 2 + tok, "%hhx", tok_b + 1); } /* The auth packet */ buf_addint8 ( &ctx->b_in, MSG_SESS); buf_addint16 ( &ctx->b_in, 1); buf_addstring ( &ctx->b_in, "Haven"); buf_addint16 ( &ctx->b_in, PVER); buf_addstring ( &ctx->b_in, usr); buf_addbytes ( &ctx->b_in, tok_b); printf ("%d\n", ctx->b_in.data); ctx_send(ctx); /* TEST */ while(1) { /* TODO write ctx_recv */ UDPpacket pack; pack.channel = -1; pack.data = ctx->b_out.data; pack.maxlen = 65535; int recv = SDLNet_UDP_Recv(ctx->sk, &pack); if (recv) { printf("I got something!!!\n"); } } return 0; }
int network_udp_recv(UDPsocket udp, UDPpacket* packet) { int recv = 0; recv = SDLNet_UDP_Recv(udp, packet); if (recv == -1) { std::cerr << "Failed to recieve data over UDP: " << SDLNet_GetError() << "\n"; } return recv; }
static void IPX_ServerLoop() { UDPpacket inPacket; IPaddress tmpAddr; //char regString[] = "IPX Register\0"; Bit16u i; Bit32u host; Bits result; inPacket.channel = -1; inPacket.data = &inBuffer[0]; inPacket.maxlen = IPXBUFFERSIZE; result = SDLNet_UDP_Recv(ipxServerSocket, &inPacket); if (result != 0) { // Check to see if incoming packet is a registration packet // For this, I just spoofed the echo protocol packet designation 0x02 IPXHeader *tmpHeader; tmpHeader = (IPXHeader *)&inBuffer[0]; // Check to see if echo packet if(SDLNet_Read16(tmpHeader->dest.socket) == 0x2) { // Null destination node means its a server registration packet if(tmpHeader->dest.addr.byIP.host == 0x0) { UnpackIP(tmpHeader->src.addr.byIP, &tmpAddr); for(i=0;i<SOCKETTABLESIZE;i++) { if(!connBuffer[i].connected) { // Use prefered host IP rather than the reported source IP // It may be better to use the reported source ipconn[i] = inPacket.address; connBuffer[i].connected = true; host = ipconn[i].host; LOG_MSG("IPXSERVER: Connect from %d.%d.%d.%d", CONVIP(host)); ackClient(inPacket.address); return; } else { if((ipconn[i].host == tmpAddr.host) && (ipconn[i].port == tmpAddr.port)) { LOG_MSG("IPXSERVER: Reconnect from %d.%d.%d.%d", CONVIP(tmpAddr.host)); // Update anonymous port number if changed ipconn[i].port = inPacket.address.port; ackClient(inPacket.address); return; } } } } } // IPX packet is complete. Now interpret IPX header and send to respective IP address sendIPXPacket((Bit8u *)inPacket.data, inPacket.len); } }
void UDP_NetListener::threadFunc(UDP_NetListener * sh) { // Create UDP socket. UDPsocket socket = SDLNet_UDP_Open(LISTENER_PORT_NUMBER); if (socket == NULL) { NETMSG("Failed to open UDP socket: %s", SDLNet_GetError()); return; } // Create packet. UDPpacket * const packet = SDLNet_AllocPacket(MAX_PACKET_SIZE); if (packet == NULL) { NETMSG("Failed to create UDP packet: %s", SDLNet_GetError()); SDLNet_UDP_Close(socket); return; } sh->cond.lock(); while (!sh->cond.shouldExit()) { int result = SDLNet_UDP_Recv(socket, packet); if (result == 1) { //unlock to give signalExit() a chance in case we're receiving a large number of packets sh->cond.unlock(); /*if (packet->len > broadcastMsgPrefix.size() && memcmp(packet->data, broadcastMsgPrefix.c_str(), broadcastMsgPrefix.size()) == 0) { IPaddress addr; addr.host = packet->address.host; SDLNet_Write16(HOST_PORT_NUMBER, &addr.port); packet->data[packet->len - 1] = 0; //prevent buffer overflow on invalid data if (strlen(reinterpret_cast<char *>(packet->data)) > broadcastMsgPrefix.size()) { SDL_LockMutex(sp->sessionsMutex); sp->reportSession(addr, reinterpret_cast<char *>(packet->data) + broadcastMsgPrefix.size()); SDL_UnlockMutex(sp->sessionsMutex); } }*/ sh->cond.lock(); } else { if (result != 0) { NETMSG("UDP receive error"); } sh->cond.waitMs(SESSION_LISTENER_PERIOD); } } sh->cond.unlock(); SDLNet_FreePacket(packet); SDLNet_UDP_Close(socket); }
int main(void) { struct UDPsopa sopa = { .sop = NULL, .pap = NULL, .port = 0, // 0 = pick unused port .packet_size = 512, .packet_num = 0, .host_port = 4444 }; strcpy(sopa.host_name, "127.0.0.1"); if (udp_setup(&sopa) != 0) { udp_cleanup(&sopa); exit(EXIT_FAILURE); } // additional client setup if (SDLNet_ResolveHost(&(sopa.pap->address), sopa.host_name, sopa.host_port) != 0) { printf("SDLNet_ResolveHost(&(sopa.pap->address), sopa.host_name, sopa.host_port) != 0\n"); printf("SDLNet_GetError() = '%s'\n", SDLNet_GetError()); udp_cleanup(&sopa); exit(EXIT_FAILURE); } srand(123); for (;;) { sleep(1); // 1 second sprintf((char*)sopa.pap->data, "rand_num = %d", rand()); sopa.pap->len = strlen((char*)sopa.pap->data) + 1; const int channel = -1; // -1 = use packet's address as destination if (SDLNet_UDP_Send(sopa.sop, channel, sopa.pap) == 0) { printf("SDLNet_UDP_Send(sopa.sop, channel, sopa.pap) == 0\n"); printf("SDLNet_GetError() = '%s'\n", SDLNet_GetError()); udp_cleanup(&sopa); exit(EXIT_FAILURE); } switch (SDLNet_UDP_Recv(sopa.sop, sopa.pap)) { case -1: printf("SDLNet_UDP_Recv(sopa.sop, sopa.pap) == -1\n"); printf("SDLNet_GetError() = '%s'\n", SDLNet_GetError()); udp_cleanup(&sopa); exit(EXIT_FAILURE); case 0: printf("SDLNet_UDP_Recv(sopa.sop, sopa.pap) == 0 // no packets received\n"); break; case 1: sopa.packet_num++; udp_print(&sopa); break; } } // for(;;) udp_cleanup(&sopa); exit(EXIT_SUCCESS); }
static __inline__ int snUDPRecv(UDPsocket s, UDPpacket *p) { int val = 0; lockSDLNet(); val = SDLNet_UDP_Recv(s, p); unlockSDLNet(); return val; }
std::string net_ip_t::receive_now(){ inbound_packet->data[0] = '\0'; inbound_packet->len = 0; SDLNet_UDP_Recv(inbound->get_socket(),inbound_packet); if(inbound_packet->len != 0){ positive_to_negative_trick(&inbound_packet->data, inbound_packet->len); } return (char*)inbound_packet->data; //return reinterpret_cast<std::string>(inbound_packet->data); }
/* * network_udp_recv() - Receive packet data via UDP from the given socket * @udp: the socket to receive data from * @packet: the pointer to store that data at */ int network_udp_recv(UDPsocket udp, UDPpacket* packet) { int recv = 0; // Define whether data was received or not recv = SDLNet_UDP_Recv(udp, packet); // Attempt to receive the data if (recv == -1) { // If an error occured while receiving the data std::cerr << "Failed to receive data over UDP: " << SDLNet_GetError() << "\n"; // Output the error message return -1; // Return -1 on failure } return recv; // Return whether a packet was received: 1 on success, 0 for no packet }
void Peer::Update() { int toCheck = 0; if (sockets.size()) { toCheck = SDLNet_CheckSockets(watch, 0); // Print(toCheck); } if (toCheck) { for(auto & i: sockets) { if (SDLNet_SocketReady(i)) { UDPpacket * packet = SDLNet_AllocPacket(512); if (SDLNet_UDP_Recv(i, packet)) { if (packet != nullptr) { Print("PLEASE PROCESS THIS PACKET\n"); Print("%s:%s:%i %i\n", getIP(packet->address.host), std::to_string(SDLNet_Read16(&packet->address.port)), packet->channel, packet->data); // Print(getIP(packet->address.host), ":", std::to_string(SDLNet_Read16(&packet->address.port)), ":", packet->channel, packet->data); } } SDLNet_FreePacket(packet); } } } if (toCheck == -1) Print("toCheck getting errors in update\n"); /*if (bound) { UDPpacket *packet = SDLNet_AllocPacket(512); if (packet != nullptr) { int ans = SDLNet_UDP_Recv(sockets[0],packet); if (ans) { //TODO: add handling of sent time in packet //print(getIP(packet->address.host)<<":"<<std::to_string(SDLNet_Read16(packet->address.port))<<" ("<< packet->channel << "): " << packet->data); } else { if (ans == -1) { print("ERROR"); } } SDLNet_FreePacket(packet); } }//*/ }
void Client::MainLoop(void) { GLenum statusGL; SDL_Event event; Uint32 ticks0 = SDL_GetTicks(), ticks; float dt; char errorString[260]; while (!done) { #ifdef DEBUG // Check for openGL errors while ((statusGL = glGetError()) != GL_NO_ERROR) { GLErrorString(errorString, statusGL); fprintf (stderr, "GL Error during main loop: %s\n", errorString); } #endif // DEBUG // Handle all events in queue SDL_Event event; while (SDL_PollEvent (&event)) { HandleEvent (&event); } while(SDLNet_UDP_Recv(udp_socket, fromServer)) { if (fromServer->address.host == serverAddress.host && fromServer->address.port == serverAddress.port) { if(pScene) pScene->OnServerMessage (fromServer->data, fromServer->len); } } // determine how much time passed since last iteration: ticks = SDL_GetTicks(); dt = float(ticks - ticks0) / 1000; ticks0 = ticks; if (dt > 0.05f) dt = 0.05f; if (pScene) { pScene->Update (dt); pScene->Render (); } // Show whatever is rendered in the main window SDL_GL_SwapWindow (mainWindow); } }
int game_host::waitForClients() { cout << "waiting for first player to connect...\n"; while(!(player1sd = SDLNet_TCP_Accept(sd))) //wait for first connection, with 50ms delay to keep CPU down SDL_Delay(50); string ipMess = ""; while(SDLNet_UDP_Recv(p1UDPsock, UDPpack1) == 0) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack1->address)); cout << this->recieveMessagep1() << "\n"; //client sends its IP SDLNet_TCP_AddSocket(socketset, player1sd); //could error check here this->player1ip = SDLNet_TCP_GetPeerAddress(player1sd); //UDPpack1->address.port = player1ip.port; //UDPpack1->address.host = player1ip.host; cout << "waiting for second player to connect...\n"; while(!(player2sd = SDLNet_TCP_Accept(sd))) SDL_Delay(50); while(!SDLNet_UDP_Recv(p1UDPsock, UDPpack2)) SDL_Delay(5); SDLNet_UDP_Bind(p1UDPsock,10,&(UDPpack2->address)); //cout << this->recieveMessagep2() << "\n"; SDLNet_TCP_AddSocket(socketset, player2sd); //could error check here as well player2ip = SDLNet_TCP_GetPeerAddress(player2sd); //UDPpack2->address.port = player2ip.port; //UDPpack2->address.host = player2ip.host; if(SDLNet_TCP_Send(player1sd, "1SIG:START", 16 /* buff.length()+1*/) < 16) { cout << "Message to client 1 failed to send...\n"; return -1; } if(SDLNet_TCP_Send(player2sd, "2SIG:START", 16 /*buff.length()+1*/) < 16) { cout << "Message to client 2 failed to send...\n"; return -1; } cout << "both clients connected, continuing...\n"; return 1; }
static void NET_Get(void) { INT32 mystatus; INT32 newnode; mypacket.len = MAXPACKETLENGTH; if (!NET_CanGet()) { doomcom->remotenode = -1; // no packet return; } mystatus = SDLNet_UDP_Recv(mysocket,&mypacket); if (mystatus != -1) { if (mypacket.channel != -1) { doomcom->remotenode = mypacket.channel+1; // good packet from a game player doomcom->datalength = mypacket.len; return; } newnode = SDLNet_UDP_Bind(mysocket,-1,&mypacket.address); if (newnode != -1) { size_t i; newnode++; M_Memcpy(&clientaddress[newnode], &mypacket.address, sizeof (IPaddress)); DEBFILE(va("New node detected: node:%d address:%s\n", newnode, NET_GetNodeAddress(newnode))); doomcom->remotenode = newnode; // good packet from a game player doomcom->datalength = mypacket.len; for (i = 0; i < numbans; i++) { if (NET_cmpaddr(&mypacket.address, &banned[i])) { DEBFILE("This dude has been banned\n"); NET_bannednode[newnode] = true; break; } } if (i == numbans) NET_bannednode[newnode] = false; return; } else CONS_Printf("SDL_Net: %s",SDLNet_GetError()); } else if (mystatus == -1) { CONS_Printf("SDL_Net: %s",SDLNet_GetError()); } DEBFILE("New node detected: No more free slots\n"); doomcom->remotenode = -1; // no packet }
Transform* Server::update() { /* Wait a packet. UDP_Recv returns != 0 if a packet is coming */ if (SDLNet_UDP_Recv(sd, p)) { /* Quit if packet contains "quit" */ if (strcmp((char *)p->data, "quit") == 0) quit = 1; } return static_cast<Transform*>((void*)p->data); }
// returns negative on error // positive on success // zero for nothing int UdpSocket::Receive(std::string& pMessage, Address& pAddress) { int code = SDLNet_UDP_Recv(mSocket, mPacket); if(code < 0) { SDL_Log("[UdpSocket::Receive] Failed to receive a packet: %s", SDLNet_GetError()); } else if(code > 0) { pMessage = std::string((char*)mPacket->data, mPacket->len); } return code; }
int net_CheckForData(const char *msg) { int len=0; //printf("Check for data...\n"); // Check t see if there is a packet wauting for us... if ( SDLNet_UDP_Recv(gOurSocket, gPacket)) { printf( "\tData received : %d\n ", gPacket->len); strcpy(msg,gPacket->data); len=gPacket->len; } return len; }
// // PacketGet // void PacketGet(void) { int i, c, packets_read; doomdata_t* sw; packets_read = SDLNet_UDP_Recv(udpsocket, packet); if (packets_read < 0) I_Error("Error reading packet: %s", SDLNet_GetError()); if (packets_read == 0) { doomcom->remotenode = -1; return; } for (i = 0; i < doomcom->numnodes; ++i) if (packet->address.host == sendaddress[i].host && packet->address.port == sendaddress[i].port) break; if (i == doomcom->numnodes) { doomcom->remotenode = -1; return; } doomcom->remotenode = i; doomcom->datalength = packet->len; sw = (doomdata_t*)packet->data; netbuffer->checksum = net_to_host32(sw->checksum); netbuffer->player = sw->player; netbuffer->retransmitfrom = sw->retransmitfrom; netbuffer->starttic = sw->starttic; netbuffer->numtics = sw->numtics; for (c = 0; c < netbuffer->numtics; ++c) { netbuffer->cmds[c].forwardmove = sw->cmds[c].forwardmove; netbuffer->cmds[c].sidemove = sw->cmds[c].sidemove; netbuffer->cmds[c].angleturn = net_to_host16(sw->cmds[c].angleturn); netbuffer->cmds[c].consistancy = net_to_host16(sw->cmds[c].consistancy); netbuffer->cmds[c].chatchar = sw->cmds[c].chatchar; netbuffer->cmds[c].buttons = sw->cmds[c].buttons; } }
string game_host::recieveMessageUDP() { if(!p1UDPsock) { return "UDP Socket Not Set"; } if (SDLNet_UDP_Recv(this->p1UDPsock,UDPrpack)) { string retStr = (char *)UDPrpack->data; if(retStr != "") { return retStr; } } return "NO MESSAGE"; }
UDPNetworkSocket::Packet * UDPNetworkSocket::receive() { if (!isOpen()) return nullptr; #ifdef UTIL_HAVE_LIB_SDL2_NET UDPpacket * p = SDLNet_AllocPacket(data->maxPktSize + 1); if (p == nullptr) { std::cerr << "SDLNet_AllocPacket: " << SDLNet_GetError() << "\n"; return nullptr; } int r = SDLNet_UDP_Recv(data->udpsock, p); if (r <= 0) { SDLNet_FreePacket(p); return nullptr; } if (p->len == p->maxlen) { WARN("Maximum UDP packet size exceeded."); } auto myPacket = new Packet(p->data, p->len); myPacket->source = fromSDLIPv4Address(p->address); SDLNet_FreePacket(p); return myPacket; #elif defined(__linux__) || defined(__unix__) || defined(ANDROID) std::vector<uint8_t> buffer(data->maxPktSize + 1); sockaddr_in sockAddr; memset(&sockAddr, 0, sizeof(sockaddr_in)); socklen_t len = sizeof(sockAddr); const ssize_t bytesReceived = recvfrom(data->udpSocket, buffer.data(), buffer.size(), 0, reinterpret_cast<sockaddr *>(&sockAddr), &len); if (bytesReceived == -1) { int error = errno; if(error != EAGAIN && error != EWOULDBLOCK) WARN(std::string(strerror(error))); return nullptr; } if (bytesReceived == buffer.size()) { WARN("Maximum UDP packet size exceeded."); } else { buffer.resize(bytesReceived); } Packet * packet = new Packet(std::move(buffer)); packet->source = fromSockaddr(sockAddr); return packet; #else return nullptr; #endif }
void NET::Update() { if (remote_socket == NULL) return; int retval = SDLNet_UDP_Recv(remote_socket, pin); if (retval >= 1 && connected) { BufferPacket(pin); } if (retval >= 1 && !connected) { ServerHandshake(); } }
// wait for "timeout" milliseconds to receive a packet on socket "s" pack_t* sock_receive( sock_t* s, int timeout, unsigned long long* wait_ts ) { int res_cs, res_ur; assert( s ); timeout = timeout < 0 ? 0 : timeout; res_cs = SDLNet_CheckSockets( s->sset, timeout ); assert( res_cs != -1 ); if( wait_ts ) *wait_ts = get_t(); if( !res_cs ) return NULL; // no_activity pack_t* pck = pack_create( NULL, -1 ); res_ur = SDLNet_UDP_Recv( s->sock, pck->p ); if( res_ur == -1 ){printf("[E] Error receiving UDP packet");pack_destroy(pck);return NULL;} if( res_ur == 0 ){printf("[W] No UDP packet received on an active port");pack_destroy(pck);return NULL;} s->bytes_recv += pck->p->len; pck->type = streamer_rdint( pck->st ); return pck; }