Pinger.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. GNU General Public License version 3 notice
  3. Copyright (C) 2012 Mihawk <luiz@netdome.biz>. All rights reserved.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation, either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see < http://www.gnu.org/licenses/ >.
  14. */
  15. #include "Pinger.h"
  16. #include <QUdpSocket>
  17. #include <QTime>
  18. #include <QTimerEvent>
  19. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  20. Pinger::Pinger(const QHostAddress &host, quint16 port, QObject *parent) :
  21. QObject(parent),
  22. mySocket(new QUdpSocket(this)),
  23. myHost(host),
  24. myPort(port),
  25. myTimerID(-1)
  26. {
  27. mySocket->connectToHost(host, port);
  28. }
  29. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  30. void Pinger::ping()
  31. {
  32. mySocket->write("\xff\xff\xff\xffk\n");
  33. mySocket->waitForBytesWritten(500);
  34. myTime.start();
  35. myTimerID = startTimer(1000);
  36. connect(mySocket, SIGNAL(readyRead()), SLOT(pong()));
  37. }
  38. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  39. void Pinger::pong()
  40. {
  41. emit finished(myHost, myPort, myTime.elapsed());
  42. disconnect(mySocket, SIGNAL(readyRead()), this, SLOT(pong()));
  43. killTimer(myTimerID);
  44. myTimerID = -1;
  45. }
  46. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  47. void Pinger::timerEvent(QTimerEvent *e)
  48. {
  49. if(e->timerId() != myTimerID)
  50. return;
  51. emit finished(myHost, myPort, myTime.elapsed());
  52. disconnect(mySocket, SIGNAL(readyRead()), this, SLOT(pong()));
  53. killTimer(myTimerID);
  54. myTimerID = -1;
  55. }