【问题标题】:C creating a raw UDP packetC 创建原始 UDP 数据包
【发布时间】:2018-07-20 05:46:49
【问题描述】:

我有兴趣创建一个 DNS(使用 UDP 协议发送)响应数据包,但是我发现如何创建自己的数据包的信息有限。

大部分教程都是这样https://opensourceforu.com/2015/03/a-guide-to-using-raw-sockets/

他们使用结构来填充字段并将它们连接成 1 个序列。但我担心编译器会填充结构,使其“损坏”(使数据包更长)

我完全知道有结构属性,不允许编译器填充结构,但我不想使用它们

谁能给我一些关于数据包创建的资源。我可以使用 Libpcap 和原始套接字

【问题讨论】:

  • 大多数编译器都有pack结构的功能,所以它没有被填充。对您使用的编译器进行一些研究。
  • 我写过我知道这些属性,但是我正在寻找替代方法
  • “Portable C”方法不会使用非标准编译器功能来控制struct 打包,而是使用您自己的char[] 缓冲区并手动复制字节。我建议只使用char(字节)大小的操作,因为使用更大的类型(例如int)会遇到小/大端问题。

标签: c sockets libpcap packets


【解决方案1】:

你这样做:

// helper function to add uint32_t to a buffer
char *append_uint32(char *buf_position, uint32_t value) {
  // network protocols usually use network byte order for numbers,
  // htonl is POSIX function so you may have to make your own on other platform
  // http://pubs.opengroup.org/onlinepubs/9699919799/functions/htonl.html
  value = htonl(value);
  memcpy(buf_postion, &value, sizeof value);
  return buf_position + sizeof value;
}

// example code using the function:
// generate packet with numbers 0...9 in network byte order
void func() {
  char buf[sizeof(int32_t) * 10];
  char *bptr = buf;
  for(uint32_t i=0; i<10; ++i) {
    bptr = append_uint32(bptr, i);
  }
  // do something with buf (use malloc instead of stack if you want return it!)
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2015-06-21
    • 1970-01-01
    • 2011-05-10
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多