From e5cd66313a68634d20e9ac670f4c0a5400295ce9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 2 May 2013 16:28:19 -0700 Subject: [PATCH] check the number of sscanf matches, store sending socket for device to reply --- pairing-server/src/main.cpp | 50 +++++++++++++++++++++---------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/pairing-server/src/main.cpp b/pairing-server/src/main.cpp index 0586bb9411..4383efe1ad 100644 --- a/pairing-server/src/main.cpp +++ b/pairing-server/src/main.cpp @@ -18,6 +18,7 @@ const int MAX_PACKET_SIZE_BYTES = 1400; struct PairableDevice { char identifier[64]; char name[64]; + sockaddr_in sendingSocket; sockaddr_in localSocket; }; @@ -34,40 +35,47 @@ int indexOfFirstOccurenceOfCharacter(char* haystack, char needle) { int main(int argc, const char* argv[]) { UDPSocket serverSocket(PAIRING_SERVER_LISTEN_PORT); - sockaddr deviceAddress; + sockaddr_in deviceAddress; char deviceData[MAX_PACKET_SIZE_BYTES] = {}; ssize_t receivedBytes = 0; std::vector devices; while (true) { - if (serverSocket.receive(&deviceAddress, &deviceData, &receivedBytes)) { + if (serverSocket.receive((sockaddr *)&deviceAddress, &deviceData, &receivedBytes)) { // create a new PairableDevice PairableDevice newDevice = {}; int addressBytes[4]; int socketPort = 0; - sscanf(deviceData, "A %s %d.%d.%d.%d:%d %s", - newDevice.identifier, - &addressBytes[3], - &addressBytes[2], - &addressBytes[1], - &addressBytes[0], - &socketPort, - newDevice.name); + int numMatches = sscanf(deviceData, "A %s %d.%d.%d.%d:%d %s", + newDevice.identifier, + &addressBytes[3], + &addressBytes[2], + &addressBytes[1], + &addressBytes[0], + &socketPort, + newDevice.name); - // setup the localSocket for the pairing device - newDevice.localSocket.sin_family = AF_INET; - newDevice.localSocket.sin_addr.s_addr = (addressBytes[3] | - addressBytes[2] << 8 | - addressBytes[1] << 16 | - addressBytes[0] << 24); - newDevice.localSocket.sin_port = socketPort; - - // push this new device into the vector - printf("Adding device %s (%s) to list\n", newDevice.identifier, newDevice.name); - devices.push_back(newDevice); + if (numMatches >= 6) { + // if we have fewer than 6 matches the packet wasn't properly formatted + + // setup the localSocket for the pairing device + newDevice.localSocket.sin_family = AF_INET; + newDevice.localSocket.sin_addr.s_addr = (addressBytes[3] | + addressBytes[2] << 8 | + addressBytes[1] << 16 | + addressBytes[0] << 24); + newDevice.localSocket.sin_port = socketPort; + + // store this device's sending socket so we can talk back to it + newDevice.sendingSocket = deviceAddress; + + // push this new device into the vector + printf("Adding device %s (%s) to list\n", newDevice.identifier, newDevice.name); + devices.push_back(newDevice); + } } }