dlsym()//系统的
dlopen()//第三方库
#define _GNU_SOURCE
#include <dlfcn.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <mysql.h>
typedef int(*connect_t)(int, const struct sockaddr *, socklen_t);
connect_t connect_f;
typedef ssize_t(*read_t)(int, void *, size_t);
read_t read_f;
typedef ssize_t(*recv_t)(int sockfd, void *buf, size_t len, int flags);
recv_t recv_f;
typedef ssize_t(*write_t)(int, const void *, size_t);
write_t write_f;
typedef ssize_t(*send_t)(int sockfd, const void *buf, size_t len, int flags);
send_t send_f;
int connect(int sockfd, const struct sockaddr *addr, socklen_t len) {
printf("connect\n");
return connect_f(sockfd, addr, len);
}
ssize_t read(int fd, void *buffer, size_t len) {
printf("read\n");
return read_f(fd, buffer, len);
}
ssize_t recv(int sockfd, void *buf, size_t len, int flags) {
printf("recv\n");
return recv_f(sockfd, buf, len, flags);
}
ssize_t write(int fd, const void *buf, size_t len) {
printf("write\n");
return write_f(fd, buf, len);
}
ssize_t send(int sockfd, const void *buf, size_t len, int flags) {
printf("send\n");
return send_f(sockfd, buf, len, flags);
}
static int init_hook() {
connect_f = dlsym(RTLD_NEXT, "connect");//拿到系统调用connect的入口,截获系统的connect,调用自己实现的connect,返回值是系统的connect接口;动态库,静态库都可以劫持
read_f = dlsym(RTLD_NEXT, "read");
recv_f = dlsym(RTLD_NEXT, "recv");
write_f = dlsym(RTLD_NEXT, "write");
send_f = dlsym(RTLD_NEXT, "send");
}
int main() {
init_hook();
MYSQL* m_mysql = mysql_init(NULL);
if (!m_mysql) {
printf("mysql_init failed\n");
return 0;
}
if (!mysql_real_connect(m_mysql,
"192.168.96.12", "Ting", "123456",
"TING_DB", 3306,
NULL, CLIENT_FOUND_ROWS)) {
printf("mysql_real_connect failed: %s\n", mysql_error(m_mysql));
return 0;
} else{
printf("mysql_real_connect success\n");
}
}
编译:
运行结果:
内存泄露问题查证,可以用hook截获malloc,自己实现的malloc可以加打印信息