hostthread.cpp 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. #include "hostthread.h"
  2. #include "qdebug.h"
  3. #include <QFile>
  4. #include <QString>
  5. #include <QTextStream>
  6. static bool modifyHostsFile(const QString &hostname, const QString &ipAddress)
  7. {
  8. QString hostsFilePath;
  9. #ifdef Q_OS_WIN
  10. hostsFilePath = "C:/Windows/System32/drivers/etc/hosts";
  11. #else
  12. hostsFilePath = "/etc/hosts";
  13. #endif
  14. // 打开hosts文件
  15. QFile file(hostsFilePath);
  16. if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
  17. qWarning() << "无法打开文件" << hostsFilePath;
  18. return false;
  19. }
  20. // 读取文件内容
  21. QTextStream stream(&file);
  22. QString fileContent = stream.readAll();
  23. qDebug() << fileContent;
  24. // 检查是否已经包含该映射
  25. if (fileContent.contains(hostname)) {
  26. qDebug() << "该域名映射已经存在";
  27. file.close();
  28. return true;
  29. }
  30. // 添加新的映射
  31. file.seek(file.size()); // 将文件指针移动到文件末尾
  32. stream << "\n" << ipAddress << " " << hostname; // 添加映射
  33. file.close();
  34. qDebug() << "已成功修改 hosts 文件";
  35. return true;
  36. }
  37. HostThread::HostThread()
  38. {
  39. if (modifyHostsFile("example.com", "127.0.0.1")) {
  40. qDebug() << "Hosts 文件已成功更新。";
  41. } else {
  42. qDebug() << "修改失败。";
  43. }
  44. }