1

我有使用套接字在两个客户端之间传输数据的应用程序。它使用单个套接字来传递控制和数据流量(通过 UDP)。

IP 标头的 Qos 和 tos 字段可以使用更改

setsockopt(sockfd, IPPROTO_IP, IP_TOS,  &tos, toslen);
setsockopt(sockfd, SOL_SOCKET, SO_PRIORITY, &cos, coslen);

但是(对同一个套接字)的调用setsockopt次数太多了?例如,假设它将每 1ms 调用一次。

为了缩小问题范围,我问的是现代 linux 系统(一般解释更受欢迎)。

这是一个演示它的示例(这是应用程序的仅发送部分):

#include <stdlib.h>
#include <memory.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#define NPACK 10000
#define PORT 44444
#define BUFLEN 128

void diep(char *s) {
    perror(s);
    exit(1);
}

#define SRV_IP "12.34.56.78"

int main(void) {
    struct sockaddr_in si_other, si_me;
    int s, i, slen = sizeof(si_other);
    int toss[2] = { 56, 160 }, coss[] = { 1, 3 };
    char buf[BUFLEN];

    //Create UDP socket
    if ((s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
        diep("socket");

    //Create remote socket
    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    if (inet_aton(SRV_IP, &si_other.sin_addr) == 0) {
        fprintf(stderr, "inet_aton() failed\n");
        exit(1);
    }

    //Create local socket and bind to it.
    memset((char *) &si_me, 0, sizeof(si_me));
    si_me.sin_family = AF_INET;
    si_me.sin_port = htons(PORT);
    si_me.sin_addr.s_addr = htonl(INADDR_ANY);
    if (bind(s, &si_me, sizeof(si_me)) == -1)
        diep("bind");

    //Loop on number of packets
    for (i = 0; i < NPACK; i++) {
        sprintf(buf, "This is packet %d, %d\n", i, toss[i % 2]);
        printf("Sending packet %d. %s", i, buf);

        //Change tos and cos. odd packets high priority , even packets low priority.
        setsockopt(s, IPPROTO_IP, IP_TOS, &toss[i % 2], sizeof(int));
        setsockopt(s, SOL_SOCKET, SO_PRIORITY, &coss[i % 2], sizeof(int));

        //Send!
        if (sendto(s, buf, strlen(buf), 0, &si_other, slen) == -1)
            diep("sendto()");
    }

    close(s);
    return 0;
}

笔记:

  • 控制和数据都应该共享同一个套接字(同一个 UDP 源端口)。
  • 多个线程将使用同一个套接字(因此在 setsockopt 和 sendto 之间需要一些锁定机制;但这超出了问题的范围)。
  • SO_PRIORITY只是linux。
4

0 回答 0