驱动开发:内核封装WSK网络通信接口( 二 )

对于客户端来说,只需要创建套接字并连接到指定地址即可,这个过程大体上可以总结为如下;

  • CreateSocket 创建套接字
  • Bind 绑定套接字
  • Connect 链接服务端驱动
  • Send 发送数据到服务端
  • Receive 接收数据到服务端
// 署名权// right to sign one's name on a piece of work// PowerBy: LyShark// Email: me@lyshark.com#include "LySocket.hpp"VOID UnDriver(PDRIVER_OBJECT driver){ // 卸载并关闭Socket库 WSKCleanup();}NTSTATUS DriverEntry(IN PDRIVER_OBJECT Driver, PUNICODE_STRING RegistryPath){ DbgPrint("hello lyshark.com \n"); // 初始化 WSKStartup(); NTSTATUSstatus = STATUS_SUCCESS; SOCKADDR_INLocalAddress = { 0, }; SOCKADDR_INRemoteAddress = { 0, }; // 创建套接字 PWSK_SOCKET TcpSocket = CreateSocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, WSK_FLAG_CONNECTION_SOCKET); if (TcpSocket == NULL) {Driver->DriverUnload = UnDriver;return STATUS_SUCCESS; } LocalAddress.sin_family = AF_INET; LocalAddress.sin_addr.s_addr = INADDR_ANY; status = Bind(TcpSocket, (PSOCKADDR)&LocalAddress); // 绑定失败则关闭驱动 if (!NT_SUCCESS(status)) {CloseSocket(TcpSocket);Driver->DriverUnload = UnDriver;return STATUS_SUCCESS; } // 初始化服务端地址与端口信息 ULONG address[4] = { 127, 0, 0, 1 }; RemoteAddress.sin_family = AF_INET; RemoteAddress.sin_addr.s_addr = change_uint(address[0], address[1], address[2], address[3]); RemoteAddress.sin_port = HTON_SHORT(8888); status = Connect(TcpSocket, (PSOCKADDR)&RemoteAddress); // 连接服务端,如果失败则关闭驱动 if (!NT_SUCCESS(status)) {CloseSocket(TcpSocket);Driver->DriverUnload = UnDriver;return STATUS_SUCCESS; } // 发送数据 char send_buffer[2048] = "hello lyshark.com A"; Send(TcpSocket, send_buffer, strlen(send_buffer), 0); // 接收数据 CHAR* read_buffer = (CHAR*)ExAllocatePoolWithTag(NonPagedPool, 2048, "read"); memset(read_buffer, 0, 1024); Receive(TcpSocket, read_buffer, 2048, 0); DbgPrint("[内核B] => %s \n", read_buffer); // 发送确认包 Send(TcpSocket, "ok", 2, 0); // 释放内存 ExFreePool(read_buffer); CloseSocket(TcpSocket); Driver->DriverUnload = UnDriver; return STATUS_SUCCESS;}编译两个驱动程序,首先运行server.sys驱动,运行后该驱动会在后台等待客户端连接,接着运行client.sys屏幕上可输出如下提示,说明通信已经建立了 。
驱动开发:内核封装WSK网络通信接口

文章插图

经验总结扩展阅读