获取本地IP
void MainWindow::get_local_Ip()
{
QList<QHostAddress> ipAddressesList = QNetworkInterface::allAddresses();
// use the first non-localhost IPv4 address
QString ipAddress;
for (int i = 0; i < ipAddressesList.size(); ++i) {
qDebug()<<ipAddressesList.at(i);
if (ipAddressesList.at(i) != QHostAddress::LocalHost &&
ipAddressesList.at(i).toIPv4Address()) {
ipAddress = ipAddressesList.at(i).toString();
break;
}
}
// if we did not find one, use IPv4 localhost
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
qDebug()<<"IP为:"<<ipAddress;
}
获取客户端IP
myser = new QTcpServer(this);
//2.监听服务器对象
if(myser->listen(QHostAddress::Any,6666))
{
qDebug() << "绑定并监听成功\n";
}
else
{
qDebug() << "绑定并监听失败\n";
}
//3.关联链接请求信号
connect(myser,SIGNAL(newConnection()),this,SLOT(new_connect()));
this->setWindowTitle("服务器");
//新的链接槽函数
void MainWindow::new_connect()
{
qDebug() << "有新的客户端链接进来\n";
//接收客户端的链接请求
QTcpSocket *clien = new QTcpSocket(this);;
clien = myser->nextPendingConnection();
QString ip = clien->peerAddress().toString();
QString port = QString::number(clien->peerPort());
QString all = ip + ":" + port;
all = all.remove(0, 7);//客户端IP及端口号
connect(clien,SIGNAL(readyRead()),this,SLOT(show_data()));
//往客户端中写入5个字节的数据
clien->write("hello",5);
}