我在下面有一个非常简单的代码。当我在 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);