简体   繁体   English

侦听UDP端口

[英]Listening to a UDP port

I need to connect to port 500 and print the data that comes through. 我需要连接到端口500并打印通过的数据。 Can someone point me in the right direction? 有人可以指出我正确的方向吗? Maybe a sample program.. 也许是一个示例程序。

Missed out a part.. using boost asio.. 错过了一部分..使用boost asio ..

I used c/c++ with the following code : 我将c / c ++与以下代码结合使用:

  int z;
  struct sockaddr_in portList;
  int len_inet;
  int s;
  char dgram[512];
  time_t td;
  struct tm tm;
  s = socket(AF_INET,SOCK_DGRAM,0);
  if ( s == -1 ) {
    strerror(errno);
  }
  memset(&portList,0,sizeof portList);
  portList.sin_family = AF_INET;
  portList.sin_port = htons(500);
  portList.sin_addr.s_addr =  inet_addr("127.0.0.1");

  if ( portList.sin_addr.s_addr == INADDR_NONE ) {
    strerror(errno);
  }
  len_inet = sizeof portList;

  z = bind(s, (struct sockaddr *)&portList, len_inet);
  if ( z == -1 ) {
    strerror(errno);
  }

  for (;;) {
    z = recv(s, dgram, sizeof dgram, 0);
    if ( z < 0 ) {
      strerror(errno);
    }
    std::cout << dgram << std::endl;
  }

But all I get is garbage values like : 但是我得到的只是垃圾值,例如:

����҉

What was I doing wrong? 我做错了什么?

Look at beej's guide to socket programming 查看beej的套接字编程指南

http://beej.us/guide/bgnet/ http://beej.us/guide/bgnet/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM