当前位置:   article > 正文

C/C++ 设置Socket的IP_TOS选项

C/C++ 设置Socket的IP_TOS选项

IP TOS选项是指示IP报文转发的优先级,QOS控制的一种,常规的IP协议TOS都为0,就是普通报文。

设置:

IPV4/TOS设置(Socket),IPTOS_LOWDELAY 表示FLASH优先级(一般用在游戏,即时通信这块,因为需要包转发要足够快)

  1. bool Socket::SetTypeOfService(int fd, int tos) noexcept {
  2. if (fd == -1) {
  3. return false;
  4. }
  5. if (tos < 0) {
  6. tos = IPTOS_LOWDELAY;
  7. }
  8. Byte b = tos; /* IPTOS_LOWDELAY */
  9. #if defined(_MACOS)
  10. return ::setsockopt(fd, IPPROTO_IP, IP_TOS, (char*)&b, sizeof(b)) == 0;
  11. #else
  12. return ::setsockopt(fd, SOL_IP, IP_TOS, (char*)&b, sizeof(b)) == 0;
  13. #endif
  14. }

设置

IPV4/IPV6 TOS设置(Socket

  1. void Socket::AdjustDefaultSocketOptional(int sockfd, bool in4) noexcept {
  2. if (sockfd != -1) {
  3. uint8_t tos = IPTOS_LOWDELAY;
  4. if (in4) {
  5. if (SOCKET_RESTRICTIONS_.IP_TOS_ON) {
  6. #if defined(_MACOS)
  7. ::setsockopt(sockfd, IPPROTO_IP, IP_TOS, (char*)&tos, sizeof(tos));
  8. #else
  9. ::setsockopt(sockfd, SOL_IP, IP_TOS, (char*)&tos, sizeof(tos));
  10. #endif
  11. }
  12. #if IP_DONTFRAGMENT
  13. int dont_frag = IP_PMTUDISC_DO;
  14. ::setsockopt(sockfd, IPPROTO_IP, IP_DONTFRAGMENT, (char*)&dont_frag, sizeof(dont_frag));
  15. #elif IP_PMTUDISC_WANT
  16. int dont_frag = IP_PMTUDISC_WANT;
  17. ::setsockopt(sockfd, IPPROTO_IP, IP_MTU_DISCOVER, &dont_frag, sizeof(dont_frag));
  18. #endif
  19. }
  20. else {
  21. // linux-user: Add missing IP_TOS, IPV6_TCLASS and IPV6_RECVTCLASS sockopts
  22. // QEMU:
  23. // https://patchwork.kernel.org/project/qemu-devel/patch/20170311195906.GA13187@ls3530.fritz.box/
  24. #if IPV6_TCLASS
  25. if (SOCKET_RESTRICTIONS_.IPV6_TCLASS_ON) {
  26. ::setsockopt(sockfd, IPPROTO_IPV6, IPV6_TCLASS, (char*)&tos, sizeof(tos)); /* SOL_IPV6 */
  27. }
  28. #endif
  29. #if IPV6_MTU_DISCOVER && IPV6_PMTUDISC_WANT
  30. int dont_frag = IPV6_PMTUDISC_WANT;
  31. ::setsockopt(sockfd, IPPROTO_IPV6, IPV6_MTU_DISCOVER, &dont_frag, sizeof(dont_frag));
  32. #endif
  33. }
  34. #if defined(SO_NOSIGPIPE)
  35. int no_sigpipe = 1;
  36. ::setsockopt(sockfd, SOL_SOCKET, SO_NOSIGPIPE, &no_sigpipe, sizeof(no_sigpipe));
  37. #endif
  38. }
  39. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号