参考博客:
QT5修改windows电脑IP地址_fangye945a的博客-CSDN博客_qt 修改ip
1、创建一个QWidget项目,更改UI界面为
2、.pro中加上:
QT += network
#-------------------------------------------------
#
# Project created by QtCreator 2022-10-27T15:16:17
#
#-------------------------------------------------QT += core gui
QT += networkgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = ChangeIP
TEMPLATE = app# The following define makes your compiler emit warnings if you use
# any feature of Qt which has been marked as deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \main.cpp \mainwindow.cppHEADERS += \mainwindow.hFORMS += \mainwindow.ui
3、.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H#include <QMainWindow>namespace Ui {
class MainWindow;
}class MainWindow : public QMainWindow
{Q_OBJECTpublic:explicit MainWindow(QWidget *parent = 0);~MainWindow();private slots:void on_showIPButton_clicked();void on_changeIPButton_clicked();private:Ui::MainWindow *ui;
};#endif // MAINWINDOW_H
4、.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QProcess>
#include <QDebug>
#include <QHostAddress>
#include <QNetworkInterface>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_showIPButton_clicked()
{QList<QNetworkInterface> network = QNetworkInterface::allInterfaces(); // 获取所有的接口foreach(QNetworkInterface net, network){QString netName = net.humanReadableName(); // 获取网络名称QList<QNetworkAddressEntry> list = net.addressEntries(); // 获取IP地址与子网掩码等foreach(QNetworkAddressEntry address,list){if(address.ip().protocol() == QAbstractSocket::IPv4Protocol) // 获取IPv4的地址{qDebug() << "网卡名:"<< netName<< " IPv4:" << address.ip().toString()<< " 子网掩码:" << address.netmask().toString();}}}
}void MainWindow::on_changeIPButton_clicked()
{//netsh interface ip set address \"以太网\" static 192.168.10.4 255.255.255.0 192.168.10.1QProcess *process = new QProcess();QString cmd = "netsh interface ip set address ";cmd += "\""; //网卡名称要加双引号cmd += ui->networkNameEdit->text();cmd += "\" ";cmd += "static ";cmd += ui->ipEdit->text(); //IPcmd += " ";cmd += ui->netmaskEdit->text(); //子网掩码cmd += " ";cmd += ui->gatewayEdit->text(); //网关qDebug()<< "cmd = " << cmd;process->start(cmd); //执行dos命令process->waitForFinished(); //等待执行完成delete process;
}
5、运行
先点击“显示本机IP”查看当前电脑IP等信息;
再点击“更改IP”
最后再点击“显示本机IP”查看更改后的电脑IP等信息;