Windows中的UDP套接字编程

时间:2010-10-13 11:08:46

标签: windows udp

我开发了从端口接收udp数据包的代码。但是在调用recvfrom()后没有任何事情发生。以下是我的代码和输出。

#include "udpSocket.h"

int main(void)
{
 SOCKET sockID;
 WSADATA wsaData = {0};
 FILE *udp;

 char buf[512];

 static int recvData;
    int iResult = 0;
 int sock_len = sizeof(fepAddr);
 int recvResult;
 int seqNo = 0;
 static int outOfSeqCnt = 0;

 FILE *fp = fopen("outOfSeq.txt","a");

 if((udp = fopen("udpData.txt","w")) == 0)
  printf("udpData.txt not opened\n");

 printf("\n-------------------------------------\n");
    printf("\tUDP Packet Receiver\n");
    printf("-------------------------------------\n");

    printf("\n Enter Destination FEP IP Address : ");
    scanf_s("%s",inputData.destIPAddr,16);

    printf("\n Enter Destination port from which to receive data : "); 
    scanf_s("%d",&inputData.portNo,5);

 printf("\n Enter No.of iterations : "); 
    scanf_s("%d",&inputData.noIteration,2);

    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
 if(iResult < 0)
 {
  printf("windows socket startup error\n");
 } 

 sockID = socket(PF_INET, SOCK_DGRAM, 0);
 if(sockID < 0)
 {
  printf("Socket creation error\n");
        WSACleanup();
 }
 else
 {
  printf("Socket Created\n");
 }

 fepAddr.sin_family = AF_INET;
 fepAddr.sin_port = htons(inputData.portNo);
 //fepAddr.sin_addr.s_addr = inet_addr(inputData.destIPAddr);
 fepAddr.sin_addr.s_addr = htonl(INADDR_ANY);

 if(bind(sockID, (struct sockaddr *)&fepAddr, sizeof(struct sockaddr)) < 0)
 {
  printf("bind() failed: %ld.\n", WSAGetLastError());
  closesocket(sockID);
  return 0;
 }

 else
 {
  printf("bind() is OK!\n");
 }

 memset(udpBuf, 0, sizeof(udpBuf));

 recvData = 1;

 while (recvData)
 {
  printf("receiving data\n");
  recvResult =  recvfrom(sockID, udpBuf, sizeof(udpBuf), 0,(struct sockaddr *)&fepAddr, &sock_len); 

  if (recvResult <= 0) {
   printf("Socket receive()-error\n");
   goto exit;
  }
  else
   printf("Sock success\n");

  printf("completed rx data\n");

  //puts(udpBuf);
  fprintf(udp, "%s", udpBuf);
  //fwrite(udpBuf, sizeof(udpBuf), 1, udp);

    }

 inputData.noIteration--;
 if (inputData.noIteration <= 0)*/
  recvData-- ;


 }

exit:
    if(udp) 
    {
         fclose(udp);
         udp = 0; 
    }

    //shutdown socket
    closesocket(sockID); 
 fclose(udp);

 return 0;
}

- 输出::::


UDP数据包接收器

输入目的地FEP IP地址:192.168.13.25

输入接收数据的目标端口:2013

输入迭代次数: 0 插槽创建 bind()没关系! 接收数据

1 个答案:

答案 0 :(得分:1)

好吧,首先关闭bind来电应使用sizeof(fepAddr)(我假设为struct sockaddr_in)而不是sizeof(struct sockaddr),以使其有机会实际绑定到正确的recvfrom地址。

其次,你确定有人在向你发送数据吗?否则{{1}}将默认阻止。