WSASendTo WSARecvFrom在msdn上的代码的错误

这个错误让我深深的迷惑了好长时间
我们看一下源代码
#include <stdio.h>
#include "winsock2.h"

void main() {

  //---------------------------------------------
  // Declare and initialize variables
  WSADATA wsaData;
  WSABUF DataBuf;
  WSAOVERLAPPED Overlapped;
  SOCKET SendSocket;
  sockaddr_in RecvAddr;
  sockaddr_in LocalAddr;
  int RecvAddrSize = sizeof(RecvAddr);
  int LocalAddrSize = sizeof(LocalAddr);
  int Port = 27015;
  char *ip;
  char SendBuf[1024] = "Data buffer to send";
  int BufLen = 1024;
  DWORD BytesSent = 0, Flags = 0;

  //---------------------------------------------
  // Initialize Winsock
  WSAStartup(MAKEWORD(2,2), &wsaData);

  //---------------------------------------------
  // Create a socket for sending data
  SendSocket = WSASocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP, NULL, 0, WSA_FLAG_OVERLAPPED);

  //---------------------------------------------
  // Set up the RecvAddr structure with the IP address of
  // the receiver (in this example case "123.123.123.1")
  // and the specified port number.
  RecvAddr.sin_family = AF_INET;
  RecvAddr.sin_port = htons(Port);
  RecvAddr.sin_addr.s_addr = inet_addr("123.123.123.1");

  //---------------------------------------------
  // Set up the LocalAddr structure with the local IP address
  // and the specified port number.
  hostent* localHost;
  localHost = gethostbyname("");
  ip = inet_ntoa (*(struct in_addr *)*localHost->h_addr_list);

  LocalAddr.sin_family = AF_INET;
  LocalAddr.sin_addr.s_addr = inet_addr(ip);
  LocalAddr.sin_port = htons(Port);

  //---------------------------------------------
  // Bind the sending socket to the LocalAddr structure
  // that has the internet address family, local IP address
  // and specified port number.  
  bind(SendSocket, (sockaddr*) &LocalAddr, LocalAddrSize);

  //---------------------------------------------
  // Send a datagram to the receiver
  printf("Sending a datagram...\n");
  DataBuf.len = BufLen;
  DataBuf.buf = SendBuf;
  WSASendTo(SendSocket, 
    &DataBuf, 
    1,
    &BytesSent,
    Flags,
    (SOCKADDR*) &RecvAddr,
    RecvAddrSize,
    &Overlapped,
    NULL);

  //---------------------------------------------
  // When the application is finished sending, close the socket.
  printf("Finished sending. Closing socket.\n");
  closesocket(SendSocket);
  printf("Exiting.\n");
  
  //---------------------------------------------
  // Clean up and quit.
  WSACleanup();
  return;
}
这是微软的源代码 我直接粘贴编译 返回永远是socketerror并且getlasterror之后,永远都是6(句柄无效)
需要对
Overlapped.m_hevent进行赋值,然而默认值是无效的
Overlapped.m_hevent = CreateEvent(NULL,TRUE,FALSE,NULL) ;
使之变成有效值



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值