C语言 RAW 套接字发送不起作用



嗨,我正在尝试借助简单的RAW套接字功能向电路板发送一些命令。这是我正在使用的界面设置。在命令行中,我将接口作为 eth0 传递。我的代码如下:

int CreateRawSocket(int proto)
{
    int i;
    struct timeval timeout;
    printf("n creating a raw socket for protocol %d",proto);
    if((rawsock=socket(PF_PACKET,SOCK_RAW,htons(proto)))==-1)
    {
        perror("n cannot create socket");
        return -1;
    }
    printf("n setting the timeout for the raw socket equal to one microsecond");
    timeout.tv_sec = 0;
    timeout.tv_usec =1;
    setsockopt(rawsock, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout));
    setsockopt(rawsock, SOL_SOCKET, SO_SNDTIMEO, &timeout, sizeof(timeout));
    i = 1;
    setsockopt(rawsock, SOL_SOCKET, SO_DONTROUTE, &i, sizeof(i));
    return rawsock;
}
int BindRawSocketToInterface(char *device,int proto)
{
    struct sockaddr_ll sll;
    struct ifreq ifr;
    printf("n initiating  socket address and interface address to null");
    bzero(&sll,sizeof(sll));
    bzero(&ifr,sizeof(ifr));
    printf("n setting up the interface to bind");
    strcpy((char *)ifr.ifr_name, device);
    if((ioctl(rawsock,SIOGIFINDEX, &ifr))==-1)
    {
        printf("n something went wrong while resetting the interface with name");
        return -1;
    }
    //setting up the flags and index in one step-ifr.ifr_flags = 0;
    strcpy((char *)ifr.ifr_name, device);
    ifr.ifr_flags = ifr.ifr_flags || IFF_PROMISC || IFF_BROADCAST;
    printf("n setting up the socket for this interface and protocol");
    sll.sll_family = AF_PACKET;
    sll.sll_ifindex =ifr.ifr_ifindex;
    sll.sll_protocol=htons(proto);
    printf("running ioctl");
    if((ioctl(rawsock,SIOGIFINDEX, &ifr))==-1)
    {
        printf("n something went wrong while setting flags");
        return -1;
    }
    printf("running bind");
    int r;
    if((r = bind(rawsock, (struct sockaddr *)&sll, sizeof(sll)))==-1)
    {
        printf("n socket is not binding properly");
        return -1;
    }
    return r;
   /*you can use this command to make it non blocking
   r = fcntl(rawsock, F_SETFL, fl | O_NDELAY);*/
}

Everthing工作正常,发送返回我30是正确的,但我在wireshark中看不到数据包。我确定铁丝鲨设置没问题。有什么建议吗?

我看到另一个有类似问题:原始套接字未发送

"数据包确实正在发送,但Wireshark只能在6分钟左右的间隔后显示它们"。

您可以尝试通过抛出HTTP请求来检查Wireshark的延迟。

最新更新