gpt4 book ai didi

c++ - 发送到 : no error code [was: raw socket error with sendto: no such device] 的原始套接字错误

转载 作者:太空狗 更新时间:2023-10-29 12:19:56 26 4
gpt4 key购买 nike

我坚持发送原始以太网帧。

[编辑]
我发现了一些错误。
1. socket调用中必须是AF_PACKET。
2. AF_PACKET 没有 SOCK_PACKET 选项,但是 SOCK_DGRAM 和 SOCK_RAW

使用 SOCK_DGRAM,wireshark 捕获格式错误的 LLC 数据包。
但是使用 SOCK_RAW 没有错误消息,也没有捕获数据包。

我没发现哪里出了问题。
[/编辑]

代码:

if ((ethernet_socket = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1)
cout << "Ethernet Socket: "<< strerror(errno) << endl;

struct sockaddr_ll socket_address;
socket_address.sll_family = PF_PACKET;
socket_address.sll_protocol = htons(ETH_P_IP);
socket_address.sll_ifindex=if_nametoindex("eth0");
socket_address.sll_hatype = 1; // ARPHRD_ETHER
socket_address.sll_pkttype = PACKET_OTHERHOST;
socket_address.sll_halen = ETH_ALEN;
memcpy(socket_address.sll_addr,dest_mac_addr,ETH_ALEN);

int send_result = 0;

char *opt=(char*)malloc(4*sizeof(char));
strcpy(opt,"eth0");

if(setsockopt(ethernet_socket, SOL_SOCKET, SO_BINDTODEVICE, opt, 4)==-1)
cout << "Could not bind socket to device: " << strerror(errno) << endl;

if ((send_result
= sendto(ethernet_socket, &buffer, sizeof(buffer), 0,
(struct sockaddr*)&socket_address, sizeof(socket_address)))==-1){
cout << "sendto error: "<< strerror(errno) << endl;
return send_result;
}

问候查

最佳答案

我找到了解决方案。我看了一下 Linux 程序 PackEth 的源代码。

以下代码适用于我。

if ((ethernet_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1)
cout << "Ethernet Socket: "<< strerror(errno) << endl; //errorhandling

memset(&ifr, 0, sizeof(ifr));
strncpy (ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
ifr.ifr_name[sizeof(ifr.ifr_name)-1] = '\0';


if (ioctl(ethernet_socket, SIOCGIFINDEX, &ifr) == -1) {
cout << "No such interface:"<< strerror(errno) << endl;
close(ethernet_socket);
}

ioctl(ethernet_socket, SIOCGIFFLAGS, &ifr);
if ( (ifr.ifr_flags & 0x1) == 0) {
cout << "Interface is down: "<< strerror(errno) << endl;
close(ethernet_socket);
}

ioctl(ethernet_socket, SIOCGIFINDEX, &ifr);


memset(&socket_address, 0, sizeof (socket_address));
socket_address.sll_family = AF_PACKET;
socket_address.sll_ifindex = ifr.ifr_ifindex;
socket_address.sll_protocol = htons(ETH_P_ALL);

if ((raw_send = sendto(ethernet_socket, buffer, size_payload+14,0,(struct sockaddr*)
&socket_address, sizeof(socket_address)))==-1){
cout << "sendto error: "<< strerror(errno) << endl;
return raw_send;
}

关于c++ - 发送到 : no error code [was: raw socket error with sendto: no such device] 的原始套接字错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com