| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- #include "hostthread.h"
- #include "qdebug.h"
- #include <QFile>
- #include <QString>
- #include <QTextStream>
- static bool modifyHostsFile(const QString &hostname, const QString &ipAddress)
- {
- QString hostsFilePath;
- #ifdef Q_OS_WIN
- hostsFilePath = "C:/Windows/System32/drivers/etc/hosts";
- #else
- hostsFilePath = "/etc/hosts";
- #endif
- // 打开hosts文件
- QFile file(hostsFilePath);
- if (!file.open(QIODevice::ReadWrite | QIODevice::Text)) {
- qWarning() << "无法打开文件" << hostsFilePath;
- return false;
- }
- // 读取文件内容
- QTextStream stream(&file);
- QString fileContent = stream.readAll();
- qDebug() << fileContent;
- // 检查是否已经包含该映射
- if (fileContent.contains(hostname)) {
- qDebug() << "该域名映射已经存在";
- file.close();
- return true;
- }
- // 添加新的映射
- file.seek(file.size()); // 将文件指针移动到文件末尾
- stream << "\n" << ipAddress << " " << hostname; // 添加映射
- file.close();
- qDebug() << "已成功修改 hosts 文件";
- return true;
- }
- HostThread::HostThread()
- {
- if (modifyHostsFile("example.com", "127.0.0.1")) {
- qDebug() << "Hosts 文件已成功更新。";
- } else {
- qDebug() << "修改失败。";
- }
- }
|