一个完整的Windows驱动程序示例(应用与内核通信)

驱动程序DriverEntry.c

#include <ntddk.h>

#define DEVICE_NAME		L"\\Device\\MyDDKDevice1"
#define SYMBOLIC_LINK_NAME	L"\\??\\MyDDKDevice1"
#define DEVICE_EX_SIZE		200

//读设备
#define READ_CTL_CODE CTL_CODE(FILE_DEVICE_UNKNOWN,0x830,METHOD_BUFFERED,FILE_READ_ACCESS)

//写设备
#define WRITE_CTL_CODE CTL_CODE(FILE_DEVICE_UNKNOWN,0x831,METHOD_BUFFERED,FILE_WRITE_ACCESS)

VOID DriverUnload(__in struct _DRIVER_OBJECT *DriverObject)
{
	UNICODE_STRING symbolLinkName;
	DbgPrint("DriverUnload\n");
	if (DriverObject->DeviceObject)
		IoDeleteDevice(DriverObject->DeviceObject);
	RtlInitUnicodeString(&symbolLinkName, SYMBOLIC_LINK_NAME);
	IoDeleteSymbolicLink(&symbolLinkName);
}

NTSTATUS OnCreateDevice(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	DbgPrint("OnCreateDevice\n");
	Irp->IoStatus.Status = status;
	Irp->IoStatus.Information = 0;
	IoCompleteRequest(Irp, IO_NO_INCREMENT);
	return status;
}

NTSTATUS OnReadDevice(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	PIO_STACK_LOCATION stack;
	ULONG wantRead;
	char* pData = "This data is from kernel.";
	int len = strlen(pData) + 1;

	DbgPrint("OnReadDevice\n");

	stack = IoGetCurrentIrpStackLocation(Irp);
	wantRead = stack->Parameters.Read.Length;//用户想要读取的字节数
	DbgPrint("App wants to read %d bytes\n", wantRead);

	// 完成IRP
	//设置IRP完成状态
	Irp->IoStatus.Status = status;

	//设置IRP操作了多少字节
	Irp->IoStatus.Information = len;

	DbgPrint("readBuf address:%p\n", Irp->AssociatedIrp.SystemBuffer);
	memcpy(Irp->AssociatedIrp.SystemBuffer, pData, len);

	//处理IRP
	IoCompleteRequest(Irp, IO_NO_INCREMENT);

	return status;
}

NTSTATUS OnWriteDevice(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	PIO_STACK_LOCATION stack;
	ULONG len;//App写到内核的数据量

	DbgPrint("OnWriteDevice\n");

	stack = IoGetCurrentIrpStackLocation(Irp);
	len = stack->Parameters.Write.Length;//App写到内核的数据量
	DbgPrint("writeBuf address:%p\n", Irp->AssociatedIrp.SystemBuffer);
	DbgPrint("Kernel recved %d bytes from App.The content is:%s\n", len, Irp->AssociatedIrp.SystemBuffer);

	// 完成IRP
	//设置IRP完成状态
	Irp->IoStatus.Status = status;

	//设置IRP操作了多少字节
	Irp->IoStatus.Information = 13;

	RtlZeroMemory(DeviceObject->DeviceExtension, DEVICE_EX_SIZE);
	memcpy(DeviceObject->DeviceExtension, Irp->AssociatedIrp.SystemBuffer, len);

	//处理IRP
	IoCompleteRequest(Irp, IO_NO_INCREMENT);

	return status;
}

NTSTATUS OnCloseDevice(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	DbgPrint("OnCloseDevice\n");
	Irp->IoStatus.Status = status;
	Irp->IoStatus.Information = 0;
	IoCompleteRequest(Irp, IO_NO_INCREMENT);
	return status;
}

NTSTATUS OnCleanupDevice(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	DbgPrint("OnCleanupDevice\n");
	Irp->IoStatus.Status = status;
	Irp->IoStatus.Information = 0;
	IoCompleteRequest(Irp, IO_NO_INCREMENT);
	return status;
}

NTSTATUS OnDeviceIoControl(__in struct _DEVICE_OBJECT *DeviceObject, __inout struct _IRP *Irp)
{
	NTSTATUS status = STATUS_SUCCESS;
	ULONG_PTR Informaiton = 0;
	PVOID InputData = NULL;
	ULONG InputDataLength = 0;
	PVOID OutputData = NULL;
	ULONG OutputDataLength = 0;
	ULONG IoControlCode = 0;
	char* pData = NULL;
	int len = 0;

	PIO_STACK_LOCATION  IoStackLocation = IoGetCurrentIrpStackLocation(Irp);  //Irp堆栈  
	IoControlCode = IoStackLocation->Parameters.DeviceIoControl.IoControlCode;

	DbgPrint("OnDeviceIoControl\n");

	switch (IoControlCode)
	{
	case WRITE_CTL_CODE:
		InputData = Irp->AssociatedIrp.SystemBuffer;
		InputDataLength = IoStackLocation->Parameters.DeviceIoControl.InputBufferLength;
		DbgPrint("App write to kernel by DeviceIoControl %d bytes,the content is:%s\n", InputDataLength, InputData);
		Irp->IoStatus.Information = InputDataLength;
		break;

	case READ_CTL_CODE:
		OutputData = Irp->AssociatedIrp.SystemBuffer;
		OutputDataLength = IoStackLocation->Parameters.DeviceIoControl.OutputBufferLength;
		DbgPrint("App wants to read %d bytes from kernel by DeviceIoControl\n", OutputDataLength);
		pData = "Ring0 --> Ring3";
		len = strlen(pData) + 1;
		memcpy(OutputData, pData, len);
		Irp->IoStatus.Information = len;
		break;
	}

	Irp->IoStatus.Status = status;
	IoCompleteRequest(Irp, IO_NO_INCREMENT);
	return status;
}

NTSTATUS DriverEntry(__in struct _DRIVER_OBJECT  *DriverObject, __in PUNICODE_STRING  RegistryPath)
{
	NTSTATUS status = STATUS_SUCCESS;
	DEVICE_OBJECT* pdo;
	UNICODE_STRING devicename, symbolLinkName;
	RtlInitUnicodeString(&devicename, DEVICE_NAME);
	RtlInitUnicodeString(&symbolLinkName, SYMBOLIC_LINK_NAME);

	DbgPrint("DriverEntry\n");

	status = IoCreateDevice(DriverObject, DEVICE_EX_SIZE, &devicename, FILE_DEVICE_UNKNOWN, 0, TRUE, &pdo);
	if (!NT_SUCCESS(status))
	{
		DbgPrint("Create Device Object Failed:%x\n", status);
		return status;
	}
	pdo->Flags |= DO_BUFFERED_IO;

	status = IoCreateSymbolicLink(&symbolLinkName, &devicename);
	if (!NT_SUCCESS(status))
	{
		DbgPrint("Create SymbolicLink Name Failed:%x\n", status);
		IoDeleteDevice(pdo);
		return status;
	}

	DriverObject->MajorFunction[IRP_MJ_CREATE] = OnCreateDevice;
	DriverObject->MajorFunction[IRP_MJ_READ] = OnReadDevice;
	DriverObject->MajorFunction[IRP_MJ_WRITE] = OnWriteDevice;
	DriverObject->MajorFunction[IRP_MJ_CLOSE] = OnCloseDevice;
	DriverObject->MajorFunction[IRP_MJ_CLEANUP] = OnCleanupDevice;
	DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = OnDeviceIoControl;

	DriverObject->DriverUnload = DriverUnload;

	return status;
}


应用程序main.c

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <windows.h>

#define DEVICE_NAME "\\\\.\\MyDDKDevice1"

//读设备
#define READ_CTL_CODE CTL_CODE(FILE_DEVICE_UNKNOWN,0x830,METHOD_BUFFERED,FILE_READ_ACCESS)

//写设备
#define WRITE_CTL_CODE CTL_CODE(FILE_DEVICE_UNKNOWN,0x831,METHOD_BUFFERED,FILE_WRITE_ACCESS)

DWORD ReadMyDevice(HANDLE hDevice, char* buf, int len)
{
	DWORD dwRead = 0;
	DeviceIoControl(hDevice, READ_CTL_CODE, NULL, 0, buf, len, &dwRead, NULL);
	return dwRead;
}

DWORD WriteMyDevice(HANDLE hDevice,char* buf,int len)
{
	DWORD dwWrite = 0;
	DeviceIoControl(hDevice, WRITE_CTL_CODE, buf, len, NULL, 0, &dwWrite, NULL);
	return dwWrite;
}

void main()
{
	system("pause"); 
	HANDLE hDevice = CreateFileA(DEVICE_NAME, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
		NULL, OPEN_EXISTING, FILE_ATTRIBUTE_DEVICE, NULL);
	if (hDevice == INVALID_HANDLE_VALUE)
	{
		printf("打开设备失败\n");
		system("pause");
		return;
	}

	char readBuf[50] = {0};
	char* pWriteBuf = "This Data is from App.";
	int len = strlen(pWriteBuf) + 1;

	DWORD dwRead = 0, dwWrite = 0;

	system("pause");
	if (ReadFile(hDevice, readBuf, sizeof(readBuf), &dwRead, NULL))
	{
		printf("readBuf地址为:%p\n",readBuf);
		printf("从设备读取了%d字节数据,内容为:%s\n", dwRead, readBuf);
	}

	system("pause");
	if (WriteFile(hDevice, pWriteBuf, len, &dwWrite, NULL))
	{
		printf("pWriteBuf地址为:%p\n", pWriteBuf);
		printf("实际写入设备%d字节\n", dwWrite);
	}

	printf("写设备\n");
	system("pause");
	dwWrite = 0;
	pWriteBuf = "Ring3 --> Ring0";
	len = strlen(pWriteBuf) + 1;
	dwWrite=WriteMyDevice(hDevice, pWriteBuf, len);
	printf("通过DeviceIoControl写入设备%d字节\n", dwWrite);

	printf("读设备\n");
	system("pause");
	memset(readBuf, 0, sizeof(readBuf));
	dwRead = 0;
	dwRead = ReadMyDevice(hDevice, readBuf, sizeof(readBuf));
	printf("通过DeviceIoControl读取设备%d字节,读取的内容为:%s\n", dwRead, readBuf);

	system("pause");
	CloseHandle(hDevice);

	system("pause");
}

makefile文件:

!INCLUDE $(NTMAKEENV)\makefile.def

sources文件

TARGETNAME=WinDDK1_Win7_X64
TARGETTYPE=DRIVER
SOURCES=DriverEntry.c

运行截图:
在这里插入图片描述

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Windows 驱动程序中编写网络通信代码是一项非常复杂的任务,因为它涉及到网络栈、驱动程序通信Windows 内核 API 的使用等多个方面。此外,由于驱动程序的安全限制,访问网络栈通常需要使用 Windows 内核的网络过滤器驱动程序或 WFP (Windows Filtering Platform)。 在这里,我提供一个简单的示例,该示例演示了如何使用 Winsock 2 API 在 Windows 驱动程序中创建和连接到一个 TCP/IP 套接字。 ```c #include <winsock2.h> #pragma comment(lib, "ws2_32.lib") // 定义套接字句柄 SOCKET s; // 定义 IP 地址和端口号 char* serverIP = "192.168.0.1"; int serverPort = 8080; // 初始化 Winsock 库 WSADATA wsaData; WSAStartup(MAKEWORD(2, 2), &wsaData); // 创建套接字 s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (s == INVALID_SOCKET) { // 处理错误 return; } // 设置服务器地址 SOCKADDR_IN serverAddr; memset(&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(serverPort); inet_pton(AF_INET, serverIP, &serverAddr.sin_addr); // 连接到服务器 int connectResult = connect(s, (SOCKADDR*)&serverAddr, sizeof(serverAddr)); if (connectResult == SOCKET_ERROR) { // 处理错误 return; } // 发送数据 char* buffer = "Hello, server!"; int sendResult = send(s, buffer, strlen(buffer), 0); if (sendResult == SOCKET_ERROR) { // 处理错误 return; } // 关闭套接字 closesocket(s); // 关闭 Winsock 库 WSACleanup(); ``` 需要注意的是,这段代码只是一个简单的示例,没有进行错误处理、异常处理和网络安全检查等。在实际开发中,您需要仔细阅读相关的文档和代码示例,并进行充分的测试和验证,以确保驱动程序的安全和稳定性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值