1

我在下面有一个非常简单的代码。当我在 Debian 7 上运行它时,此代码总是通过 127.0.0.1 接口发送所有数据包。但我希望它通过 192.168.0.103 发送。我哪里错了?

我在谷歌中搜索了解决方案,直到过去 16 小时,但没有找到答案:(。

当然,我可以通过路由表修复它。但是 ping 和 traceroute 效果很好。为什么我的代码不起作用?

int rawSocket;

char buffer[PACKET_LENGTH];

struct IPHeader *ipHeader = (struct IPHeader *) buffer;
struct UDPHeader *udpHeader = (struct UDPHeader *) (buffer + sizeof(struct IPHeader));

struct sockaddr_in sin, din;
int one = 1;
const int *val = &one;

memset(buffer, 0, PACKET_LENGTH);

rawSocket = socket(PF_INET, SOCK_RAW, IPPROTO_UDP);
if (rawSocket < 0) {
    printf("socket() error");
    exit(-1);
}

sin.sin_family = AF_INET;
din.sin_family = AF_INET;

sin.sin_port = htons(atoi(srcPort));
din.sin_port = htons(atoi(dstPort));

sin.sin_addr.s_addr = inet_addr(realSrcIP);
din.sin_addr.s_addr = inet_addr(dstIP);

ipHeader->iph_ihl = 5;
ipHeader->iph_ver = 4;
ipHeader->iph_tos = 16; // Low delay
ipHeader->iph_len = sizeof(struct IPHeader) + sizeof(struct UDPHeader);
ipHeader->iph_ident = htons(54321);
ipHeader->iph_ttl = 64; // hops
ipHeader->iph_protocol = 17; // UDP
// spoof please lol =P
ipHeader->iph_sourceip = inet_addr(srcIP);
ipHeader->iph_destip = inet_addr(dstIP);

udpHeader->udph_srcport = htons(atoi(srcPort));
udpHeader->udph_destport = htons(atoi(dstPort));
udpHeader->udph_len = htons(sizeof(struct UDPHeader));
ipHeader->iph_chksum = csum((unsigned short *)buffer, sizeof(struct IPHeader) + sizeof(struct UDPHeader));

if(setsockopt(rawSocket, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)) < 0)
{
    perror("setsockopt() error");
    exit(-1);
}

struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "eth0");
if (setsockopt(rawSocket, SOL_SOCKET, SO_BINDTODEVICE, (void *)&ifr, sizeof(ifr)) < 0) {
    printf("HUJ\n");
}

int errorCode = sendto(rawSocket, buffer, ipHeader->iph_len, 0, (struct sockaddr *)&sin, sizeof(sin));
if(errorCode < 0)
{
    perror("sendto() error");
    exit(-1);
}

close(rawSocket);
4

1 回答 1

3

我不认为你设置ifr正确。

您需要调用ioctl(rawsocket, SIOCGIFINDEX, &ifr)以设置设备的索引。名字还不够。您的索引保留为零,这是第一个恰好是环回的设备。

这是来自C Language Examples of IPv4 and IPv6 Raw Sockets for Linux的一段代码:

// Use ioctl() to look up interface index which we will use to
// bind socket descriptor sd to specified interface with setsockopt() since
// none of the other arguments of sendto() specify which interface to use.
memset (&ifr, 0, sizeof (ifr));
snprintf (ifr.ifr_name, sizeof (ifr.ifr_name), "%s", interface);
if (ioctl (sd, SIOCGIFINDEX, &ifr) < 0) {
   perror ("ioctl() failed to find interface ");
   return (EXIT_FAILURE);
}

可能还有其他问题(您的代码太大)尝试运行/修改上面链接中的示例。希望它们不会过时。

于 2013-09-19T23:36:29.313 回答