C语言连接成功MySQL后需要监听端口发来的消息,最后使用NetAssist测试
![](https://img-blog.csdnimg.cn/img_convert/d69312ec0c9f4ab79445eb7d9d97cb47.png)
服务端输出界面
![](https://img-blog.csdnimg.cn/img_convert/1cc287e5e3914bbb90547d992ff88cc5.png)
注意,这里需要改成你虚拟机的ip和端口
![](https://img-blog.csdnimg.cn/img_convert/49a6c86f341b4d038e8bbab0e731f9fe.png)
完整代码,点赞收藏不迷路:
#include <stdio.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/socket.h>
#include <stdlib.h>
#include "/usr/include/linux/socket.h"
#include <string.h>
#include <arpa/inet.h>
#include <time.h>
#include <netinet/tcp.h>
#include <sys/types.h>
#include <ctype.h>
#include <signal.h>
#include <stdbool.h>
#include <fcntl.h>
#include <stdarg.h>
#include </usr/local/mysql/include/mysql.h>
void monitor()
{
// 1. 创建监听的套接字
int lfd = socket(AF_INET, SOCK_STREAM, 0);
printf("创建监听的套接字\n");
if(lfd == -1)
{
perror("socket");
exit(0);
}
// 2. 将socket()返回值和本地的IP端口绑定到一起
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(5555); // 大端端口
// INADDR_ANY代表本机的所有IP, 假设有三个网卡就有三个IP地址
// 这个宏可以代表任意一个IP地址
// 这个宏一般用于本地的绑定操作
addr.sin_addr.s_addr = INADDR_ANY; // 这个宏的值为0 == 0.0.0.0
inet_pton(AF_INET, "192.168.154.141", &addr.sin_addr.s_addr);
int ret = bind(lfd, (struct sockaddr*)&addr, sizeof(addr));
printf("IP端口绑定\n");
if(ret == -1)
{
perror("bind");
exit(0);
}
// 3. 设置监听
ret = listen(lfd, 128);
printf("设置监听\n");
if(ret == -1)
{
perror("listen");
exit(0);
}
// 4. 阻塞等待并接受客户端连接
struct sockaddr_in cliaddr;
int clilen = sizeof(cliaddr);
int cfd = accept(lfd, (struct sockaddr*)&cliaddr, &clilen);
printf("阻塞等待并接受客户端连接\n");
if(cfd == -1)
{
perror("accept");
exit(0);
}
// 打印客户端的地址信息
char ip[24] = {0};
printf("客户端的IP地址: %s, 端口: %d\n",
inet_ntop(AF_INET, &cliaddr.sin_addr.s_addr, ip, sizeof(ip)),
ntohs(cliaddr.sin_port));
// 5. 和客户端通信
while(1)
{
// 接收数据
char buf[1024];
memset(buf, 0, sizeof(buf));
int len = read(cfd, buf, sizeof(buf));
if(len > 0)
{
printf("客户端say: %s\n", buf);
printf("%d",sizeof(buf));
write(cfd, buf, len);
}
else if(len == 0)
{
printf("客户端断开了连接...\n");
break;
}
else
{
perror("read\n");
break;
}
}
close(cfd);
close(lfd);
printf("监听结束\n");
return 0;
}
int main(int argc, const char *argv[])
{
char DeleteById[12], UpdateById[12], SelectById[12], InsertById[12], Name[7],Sex[7],Age[7],StudyDate[7],Major[7],Class[7],Address[7],Tel[7];
MYSQL mysql_con;
MYSQL *mysql = mysql_init(&mysql_con);
if (mysql == NULL)
{
printf("init err! 数据库初始化错误!\n");
}
if (mysql_real_connect(mysql, "192.168.154.141", "root", "123456", "school", 3306, NULL, 0) == NULL)
{
printf(" connect err!数据库连接失败!\n");
return -1;
}
printf("%s", mysql_error(mysql));
printf("数据库连接测试成功!\n");
monitor();
}
点赞收藏不迷路