我在下面有一个非常简单的代码。当我在Debian 7上运行它时,此代码始终通过127.0.0.1接口发送所有数据包。但我希望它通过192.168.0.103发送它。我哪里错了?
我在Google搜索解决方案直到过去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);
答案 0 :(得分: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);
}
可能还有其他问题(您的代码太大)尝试运行/修改上面链接中的示例。希望它们不会过时。