共用方式為


透過 Datagram Socket 傳送數據

在 Winsock Kernel (WSK) 應用程式將數據報套接字系結至本機傳輸地址之後,它可以透過套接字傳送數據報。 WSK 應用程式會呼叫 WskSendTo 函式,透過數據報套接字傳送數據報。

下列程式代碼範例示範 WSK 應用程式如何透過數據報套接字傳送數據報。

// Prototype for the send datagram IoCompletion routine
NTSTATUS
  SendDatagramComplete(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp,
    PVOID Context
    );

// Function to send a datagram
NTSTATUS
  SendDatagram(
    PWSK_SOCKET Socket,
    PWSK_BUF DatagramBuffer,
    PSOCKADDR RemoteAddress
    )
{
  PWSK_PROVIDER_DATAGRAM_DISPATCH Dispatch;
  PIRP Irp;
  NTSTATUS Status;

  // Get pointer to the provider dispatch structure
  Dispatch =
    (PWSK_PROVIDER_DATAGRAM_DISPATCH)(Socket->Dispatch);

  // Allocate an IRP
  Irp =
    IoAllocateIrp(
      1,
      FALSE
      );

  // Check result
  if (!Irp)
  {
    // Return error
    return STATUS_INSUFFICIENT_RESOURCES;
  }

  // Set the completion routine for the IRP
  IoSetCompletionRoutine(
    Irp,
    SendDatagramComplete,
    DatagramBuffer,  // Use the datagram buffer for the context
    TRUE,
    TRUE,
    TRUE
    );

  // Initiate the send operation on the socket
  Status =
    Dispatch->WskSendTo(
      Socket,
      DatagramBuffer,
      0,  // No flags
      RemoteAddress,
      0,
      NULL,  // No associated control info
      Irp
      );

  // Return the status of the call to WskSendTo()
  return Status;
}

// Send datagram IoCompletion routine
NTSTATUS
  SendDatagramComplete(
    PDEVICE_OBJECT DeviceObject,
    PIRP Irp,
    PVOID Context
    )
{
  UNREFERENCED_PARAMETER(DeviceObject);

  PWSK_BUF DatagramBuffer;
  ULONG ByteCount;

  // Check the result of the send operation
  if (Irp->IoStatus.Status == STATUS_SUCCESS)
  {
    // Get the pointer to the datagram buffer
    DatagramBuffer = (PWSK_BUF)Context;

    // Get the number of bytes sent
    ByteCount = (ULONG)(Irp->IoStatus.Information);

    // Re-use or free the datagram buffer
    ...
  }

  // Error status
  else
  {
    // Handle error
    ...
  }

  // Free the IRP
  IoFreeIrp(Irp);

  // Always return STATUS_MORE_PROCESSING_REQUIRED to
  // terminate the completion processing of the IRP.
  return STATUS_MORE_PROCESSING_REQUIRED;
}

如果 WSK 應用程式已為資料報套接字設定了固定的遠端傳輸位址或固定的目的地傳輸位址,則傳遞至 WskSendTo 函式的 RemoteAddress 參數是可選的,並且可以是 NULL。 如果 NULL,則數據報會傳送至固定遠端傳輸位址或固定目的地傳輸位址。 如果非NULL,則數據報會傳送至指定的遠端傳輸位址。

如需設定資料報套接字固定遠端傳輸地址的詳細資訊,請參閱 SIO_WSK_SET_REMOTE_ADDRESS

如需設定資料報套接字固定目標傳輸地址的詳細資訊,請參閱 SIO_WSK_SET_SENDTO_ADDRESS