Linux AIO是否支持RAW套接字?

时间:2016-06-21 15:10:18

标签: linux sockets recv raw-sockets aio

我正在努力让AIO在Linux(版本3.19)上工作以接收RAW套接字上的数据包,但无济于事。我已成功将AIO用于UDP和TCP套接字,但无法使其适用于RAW套接字。我尝试过IPv4和IPv6。

有人知道AIO是否支持RAW套接字吗?

以下是我的应用程序中的一些代码段:

void readCallback(sigval_t sigval) {
    debug(LOG_DEBUG, "RAW packet received\n");
}

int main(int argc, char *argv[]) {
    int sock = socket(domain, SOCK_RAW, IPPROTO_RAW);
    if (-1 == sock) {
    debug(LOG_CRIT, "FAILED to create raw socket\n");
    return 1;
    }

    char *iface = "eth0";
    ifreq ifr;
    memset (&ifr, 0, sizeof(ifr));
    snprintf (ifr.ifr_name, sizeof(ifr.ifr_name), "%s", iface);
    if (ioctl (sock, SIOCGIFINDEX, &ifr) < 0) {
    debug(LOG_CRIT, "FAILED to query interface '%s' index\n", iface);
    return 1;
    }

    // Set flag so socket expects us to provide IP header.
    const int on = 1;
    if (setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0) {
    debug(LOG_CRIT, "FAILED to configure raw socket on '%s'\n", iface);
    return 1;
    }

    // Bind socket to interface index.
    if (setsockopt(sock, SOL_SOCKET, SO_BINDTODEVICE, &ifr, sizeof(ifr)) < 0) {
    debug(LOG_CRIT, "FAILED to bind socket to %s/%u\n", iface, ifr.ifr_ifindex);
    return 1;
    }

    // listen for packets
    struct aiocb aio;
    char buf[MAX_PACKET];
    bzero((char*)&aio, sizeof(struct aiocb));
    aio.aio_fildes = sock;
    aio.aio_buf = &buf;
    aio.aio_nbytes = MAX_PACKET;
    aio.aio_offset = 0;
    aio.aio_sigevent.sigev_notify = SIGEV_THREAD;
    aio.aio_sigevent.sigev_notify_function = readCallback;
    aio.aio_sigevent.sigev_notify_attributes = NULL;
    aio.aio_sigevent.sigev_value.sival_ptr = buf;
    if (!RequestAioRead(&aio)) {
    debug(LOG_DEBUG, "FAILED to listen on raw socket...\n");
    return 1;
    }
    debug(LOG_DEBUG, "Listening on raw socket...\n");

    // main loop
    while (true) {
    usleep(100000);
    }
    close(sock);
    return 0;
}

1 个答案:

答案 0 :(得分:0)

原来我的socket()协议错了。正确的协议似乎是htons(0x0800):

socket(AF_PACKET, SOCK_RAW, htons(0x0800));

有了这个,aio似乎工作正常。