在C程序中发送ICMP数据包

11

我正在尝试使用C语言创建一个ICMP ping测试程序,但是在成功发送数据包方面遇到了困难。虽然sendto函数返回了字节数和其他一切信息,但实际上没有任何数据包被发送出去。我已经使用目标计算机上的WireShark进行验证。然而,在主机上进行普通的ping测试可以正常工作,并且在WireShark中显示。

以下是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>

unsigned short cksum(unsigned short *addr, int len);

int main(int argc, char *argv[])
{
    int sock;
    char send_buf[400], recv_buf[400], src_name[256], src_ip[15], dst_ip[15];
    struct ip *ip = (struct ip *)send_buf;
    struct icmp *icmp = (struct icmp *)(ip + 1);
    struct hostent *src_hp, *dst_hp;
    struct sockaddr_in src, dst;
    struct timeval t;
    int on;
    int num = 10;
    int failed_count = 0;
    int bytes_sent, bytes_recv;
    int dst_addr_len;
    int result;
    fd_set socks;

    /* Initialize variables */
    on = 1;
    memset(send_buf, 0, sizeof(send_buf));

    /* Check for valid args */
    if(argc < 2)
    {
        printf("\nUsage: %s <dst_server>\n", argv[0]);
        printf("- dst_server is the target\n");
        exit(EXIT_FAILURE);
    }

    /* Check for root access */
    if (getuid() != 0)
    {
        fprintf(stderr, "%s: This program requires root privileges!\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* Get source IP address */
    if(gethostname(src_name, sizeof(src_name)) < 0)
    {
        perror("gethostname() error");
        exit(EXIT_FAILURE);
    }
    else
    {
        if((src_hp = gethostbyname(src_name)) == NULL)
        {
            fprintf(stderr, "%s: Can't resolve, unknown source.\n", src_name);
            exit(EXIT_FAILURE);
        }
        else
            ip->ip_src = (*(struct in_addr *)src_hp->h_addr);
    }

    /* Get destination IP address */
    if((dst_hp = gethostbyname(argv[1])) == NULL)
    {
        if((ip->ip_dst.s_addr = inet_addr(argv[1])) == -1)
        {
            fprintf(stderr, "%s: Can't resolve, unknown destination.\n", argv[1]);
            exit(EXIT_FAILURE);
        }
    }
    else
    {
        ip->ip_dst = (*(struct in_addr *)dst_hp->h_addr);
        dst.sin_addr = (*(struct in_addr *)dst_hp->h_addr);
    }
    
    sprintf(src_ip, "%s", inet_ntoa(ip->ip_src));
    sprintf(dst_ip, "%s", inet_ntoa(ip->ip_dst));
    printf("Source IP: '%s' -- Destination IP: '%s'\n", src_ip, dst_ip);

    /* Create RAW socket */
    if((sock = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
    {
        perror("socket() error");

        /* If something wrong, just exit */
        exit(EXIT_FAILURE);
    }

    /* Socket options, tell the kernel we provide the IP structure */
    if(setsockopt(sock, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0)
    {
        perror("setsockopt() for IP_HDRINCL error");
        exit(EXIT_FAILURE);
    }

    /* IP structure, check the ip.h */
    ip->ip_v = 4;
    ip->ip_hl = 5;
    ip->ip_tos = 0;
    ip->ip_len = htons(sizeof(send_buf));
    ip->ip_id = htons(321);
    ip->ip_off = htons(0);
    ip->ip_ttl = 255;
    ip->ip_p = IPPROTO_ICMP;
    ip->ip_sum = 0;

    /* ICMP structure, check ip_icmp.h */
    icmp->icmp_type = ICMP_ECHO;
    icmp->icmp_code = 0;
    icmp->icmp_id = 123;
    icmp->icmp_seq = 0;
    
    /* Set up destination address family */
    dst.sin_family = AF_INET;
    
    /* Loop based on the packet number */
    for(int i = 1; i <= num; i++)
    {
        /* Header checksums */
        icmp->icmp_cksum = 0;
        ip->ip_sum = cksum((unsigned short *)send_buf, ip->ip_hl);
        icmp->icmp_cksum = cksum((unsigned short *)icmp,
                           sizeof(send_buf) - sizeof(struct icmp));
        
        /* Get destination address length */
        dst_addr_len = sizeof(dst);
        
        /* Set listening timeout */
        t.tv_sec = 5;
        t.tv_usec = 0;
    
        /* Set socket listening descriptors */
        FD_ZERO(&socks);
        FD_SET(sock, &socks);
        
        /* Send packet */
        if((bytes_sent = sendto(sock, send_buf, sizeof(send_buf), 0,
                         (struct sockaddr *)&dst, dst_addr_len)) < 0)
        {
            perror("sendto() error");
            failed_count++;
            printf("Failed to send packet.\n");
            fflush(stdout);
        }
        else
        {
            printf("Sent %d byte packet... ", bytes_sent);
            
            fflush(stdout);
            
            /* Listen for the response or timeout */
            if((result = select(sock + 1, &socks, NULL, NULL, &t)) < 0)
            {
                perror("select() error");
                failed_count++;
                printf("Error receiving packet!\n");
            }
            else if (result > 0)
            {
                printf("Waiting for packet... ");
                fflush(stdout);
                
                if((bytes_recv = recvfrom(sock, recv_buf,
                     sizeof(ip) + sizeof(icmp) + sizeof(recv_buf), 0,
                     (struct sockaddr *)&dst,
                     (socklen_t *)&dst_addr_len)) < 0)
                {
                    perror("recvfrom() error");
                    failed_count++;
                    fflush(stdout);
                }
                else
                    printf("Received %d byte packet!\n", bytes_recv);
            }
            else
            {
                printf("Failed to receive packet!\n");
                failed_count++;
            }
            
            fflush(stdout);
            
            icmp->icmp_seq++;
        }
    }
    
    /* Display success rate */
    printf("Ping test completed with %d%% success rate.\n",
           (((num - failed_count) / num) * 100));
    
    /* close socket */
    close(sock);

    return 0;
}

/* One's Complement checksum algorithm */
unsigned short cksum(unsigned short *addr, int len)
{
    int nleft = len;
    int sum = 0;
    unsigned short *w = addr;
    unsigned short answer = 0;

    while (nleft > 1)
    {
      sum += *w++;
      nleft -= 2;
    }

    if (nleft == 1)
    {
      *(unsigned char *)(&answer) = *(unsigned char *)w;
      sum += answer;
    }

    sum = (sum >> 16) + (sum & 0xffff);
    sum += (sum >> 16);
    answer = ~sum;
    
    return (answer);
}

有没有想法我做错了什么?校验和没问题吗?两个都用0可以吗?
编辑:好的,所以多亏下面的人,我成功地发送了数据包!目标计算机会发送回显响应。但是现在,我的程序无法接收到回复。select()函数总是超时。我已经更新了上面的代码。
编辑2:好的,我搞定了!我需要将套接字协议设置为IPPROTO_ICMP而不是IPPROTO_RAW,然后它就很好用了!再次感谢你们评论过的人!真的帮了我大忙了!看起来我只能标记一个正确的答案,但你们所有人都帮助解决了这个问题。 :)
3个回答

3

我注意到了一件事情...

你有这个:

 struct ip *ip = (struct ip *)send_buf;

然后,您正在分配目标字段:

ip->ip_dst = (*(struct in_addr *)dst_hp->h_addr)

然后你使用memset来擦除它(因为send_buff指向同一个东西):
memset(send_buf, 0, sizeof(send_buf));

所以,当您在此处尝试获取ip_dst时:
dst.sin_addr = ip->ip_dst;

您得到的是0,而不是之前设置的数值。


谢谢,我完全忽略了这个!我把memset调用移到了顶部,现在我可以从WireShark看到数据包进来了。它作为ping回显请求进来,但没有回复发送回主机,而且select调用超时了。有什么线索吗? - Zac

2
乍一看:在select()之后,您不能依赖于time struct。您还应该设置usec。
因此,在代码中,将t值的规范包含在for循环内部:
for (i = 1; i <= num; i++) {
    t.tv_sec = 5;
    t.tv_usec = 0;
    ...

否则,当您进行第二次迭代时,t(可能已经)发生了变化。

在您的sprintf(src_ip,...)和dst_ip中,您省略了格式。


2
除了ebutusov的回复之外,
ip->ip_sum = 0;
icmp->icmp_cksum = htons(~(ICMP_ECHO << 8));

两者都是错误的。
您需要正确计算校验和(它是相同的算法,但覆盖了不同的字段)。


是的,正确计算校验和解决了问题!回显响应已经发送回来。但是即使有回复,选择函数仍然超时。那个设置有问题... - Zac
你没有绑定你的套接字。因此,操作系统没有理由将ICMP回复传递给你。在原始套接字中,它不会查看你发送的内容,因此它无法知道接收到的ICMP是对其的回复。 - ugoren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接