1
我正在使用一個類似netcat的工具(主要用於自我教育)。我想發送IP和UDP頭,我通過SOCK_RAW
套接字構造的數據包。我在Debian VM上運行以下代碼以通過套接字發送數據包。SOCK_RAW數據包不發送某個源地址
/* header must already have source IP, destination IP, and protocol number filled in */
int send_ip_packet(ipheader_t *header, char *buf, int numbytes)
{
int sizeofpacket = sizeof(ipheader_t) + numbytes;
if(sizeofpacket > MAX_PCKT_LEN)
{
printf("Cannot send ip packet of len %i. Too large. - FAIL\n", sizeofpacket);
return -1;
}
/* open a raw socket */
int sd;
sd = socket(PF_INET, SOCK_RAW, header->ip_p);
if(sd < 0)
{
perror("socket()");
printf("socket() call - FAIL\n");
return -1;
}
else
{
printf("socket() call - SUCCESS\n");
}
char packet[sizeofpacket];
memset(packet, 0, sizeofpacket);
/* set remaining ip header */
header->ip_hl = 5; /* header length is 5 32-bit octets */
header->ip_v = 4; /* IPv4 */
header->ip_tos = 16; /* low delay */
header->ip_len = sizeofpacket;
header->ip_id = htons(54321); /* identifier used for fragmentation */
header->ip_off = 0; /* fragmentation options */
header->ip_ttl = 64; /* max num hops */
header->ip_sum = csum((unsigned short*)packet, sizeofpacket);
/* fill packet */
memcpy(packet, (char*) header, sizeof(ipheader_t));
memcpy(packet + sizeof(ipheader_t), (char*) buf, numbytes);
/* setup socket addresses */
struct sockaddr_in sin, din;
sin.sin_family = AF_INET;
din.sin_family = AF_INET;
memcpy(&sin.sin_addr.s_addr, &header->ip_src, sizeof(in_addr_t));
memcpy(&din.sin_addr.s_addr, &header->ip_dst, sizeof(in_addr_t));
/* send out the packet */
int one = 1;
int *val = &one;
if(setsockopt(sd, IPPROTO_IP, IP_HDRINCL, val, sizeof(one)))
{
perror("setsockopt()");
printf("setsockopt() call - FAIL\n");
return -1;
}
else
{
printf("setsockopt() call - SUCCESS\n");
}
if(sendto(sd, packet, header->ip_len, 0, (struct sockaddr *) &sin, sizeof(sin)) < 0)
{
perror("sendto()");
printf("sendto() call - FAIL\n");
return -1;
}
else
{
printf("Message sent! - SUCCESS\n");
}
return 0;
}
代碼成功,只要發送可見的數據包在Wireshark的,因爲我提供的不是列爲我的「真」 IP,當我運行ifconfig
源IP。任何人都可以告訴我爲什麼這可能是或如何修復它(除了不使用SOCK_RAW
)?我會假設操作系統專門處理數據包,但爲什麼?
哇。這是一個愚蠢的錯字。非常感謝! – tapman90