【问题标题】:RAW Socket send not workingRAW Socket发送不起作用
【发布时间】:2012-06-25 08:44:50
【问题描述】:

您好,我正在尝试借助简单的 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);*/
}

一切正常,发送返回 30,这是正确的,但我没有在 Wireshark 中看到数据包。我确定wireshark设置没问题。 有什么建议吗?

【问题讨论】:

  • 您在发送以太网帧吗?或者是其他东西?也许wireshark设置为丢弃非以太网帧?
  • 一件事,你应该使用 |结合标志而不是||。
  • 在第二个 ioctl() 中,你需要 SIOCSIFFLAGS 而不是 SIOCGIFINDEX,显然(而不是 SIOGIFNDEX,这是一个碰巧起作用的错字:)。另外,我不完全确定 SIOCGIFINDEX 是否真的会给你标志。要更改标志,我宁愿先做一个 SIOCGIFFLAGS。
  • 你向这个套接字发送什么?您的数据包应以 14 字节以太网标头(目标、源、类型)开头。

标签: c sockets send


【解决方案1】:

我看到另一个有类似问题的: Raw socket NOT sending

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

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

【讨论】:

    猜你喜欢
    • 2012-12-14
    • 2022-11-13
    • 2017-03-08
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多