如何在C中使用UDP监听数据包?

时间:2015-12-18 18:31:30

标签: c networking network-programming udp

我写了这个udp接收C代码来监听正在流式传输的数据包,看起来代码没有进入while循环:代码的输出如下,然后它停在那里没有错误,虽然端口和ip都正确定义并发送数据工作:

初始化Winsock ...已初始化。 这是创建的套接字:128 套接字已创建。 连接到套接字;它然后留在这里并没有进入循环..

代码:

#include<stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <winsock2.h>
#include <fcntl.h>

#pragma comment(lib, "Ws2_32.lib")
#pragma comment(lib, "wsock32.lib")

  int main(int argc , char *argv[])
  {
      printf("started \n");
      WSADATA wsa;
      SOCKET s;
      struct sockaddr_in server, client_addr;
      int recv_size =8192;// 2000000;
      char ser[recv_size] ;
      int count = 0;
      int addr_len;
      int bytes;
      char *message , server_reply[recv_size];

      printf("\nInitialising Winsock...");
      if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
      { 
        printf("Failed. Error Code : %d",WSAGetLastError());
        return 1; 
      }

      printf("Initialised.\n");

      if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
      { printf("Could not create socket : %d" , WSAGetLastError());
      }else{ printf("This is the socket that was created:  %d \n", s); }

      printf("Socket created.\n");

      server.sin_addr.s_addr = inet_addr("192.168.10.103");
      server.sin_family = AF_INET;
      server.sin_port = htonl(25000);
      addr_len = sizeof(struct sockaddr);

      if (connect(s, (struct sockaddr *)&server, sizeof(server))<0)
      { puts("connect error");return 1 ;
      }else {puts("connects to the socket"); }
      while(1) {
//        if ((recv_size = recv(s, server_reply, recv_size, 0)) == SOCKET_ERROR) {
//            puts("failed at receive");
//        }
        puts("receiving from microzed");
        bytes = recvfrom(s,ser,recv_size,0,(struct sockaddr *)&client_addr,&addr_len);
        //ser[bytes] = '\0';
        write(1,ser,bytes);

//        printf("count: %d \n ",count = count+ 1);
//        printf("data received: %d \n",ser);

      }
  puts("works \n");

 // server_reply[recv_size] = '\0';
 // printf("This is what the message reply is : %d, \n ",server_reply);

      printf("finished \n");
      return 0;
  }

1 个答案:

答案 0 :(得分:1)

我会认为这是某种“竞争条件”。在puts()和recv()之间,由于没有其他东西出现,很明显recvfrom()是阻塞的,否则,你会看到输出的其余部分(即&#34;工作) \ n&#34;。)

一种简单的测试方法,即将套接字的模式设置为NON_BLOCKING。

我尝试使用MS Visual 2015运行代码,它运行没有问题。 输出:

  

开始

     

初始化Winsock ...已初始化。这是插座   created:创建了200个套接字。连接到接收的插座   microzed