如何发送到 PF_PACKET 的 IP 地址?

How do I send to an IP address with PF_PACKET?

我正在尝试学习如何编写基于 PACKET_MMAP 的应用程序,以便获得性能提升。我想从学习如何将数据包发送到指定的 IP 地址开始。我一直在通过从 https://sites.google.com/site/packetmmap/ 借用代码部分来学习,它使用 PF_PACKET 作为 socket().

的第一个参数

我设法编写了一个发送一个数据包的程序(我不知道发送到哪里)。 PF_PACKET如何设置发送的IP地址?

这是我目前的代码:

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>

static char * str_devname= NULL;
static int mode_loss     = 0;
static int c_packet_sz   = 150;
static int c_packet_nb   = 1000;
static int c_buffer_sz   = 1024*8;
static int c_buffer_nb   = 1024;
static int c_sndbuf_sz   = 0;
static int c_send_mask   = 127;
static int c_error       = 0;
static int mode_thread   = 0;

volatile int fd_socket;
volatile int data_offset = 0;
volatile struct tpacket_hdr * ps_header_start;
volatile struct sockaddr_ll *ps_sockaddr = NULL;
volatile int shutdown_flag = 0;
struct tpacket_req s_packet_req;

int main( int argc, char ** argv )
{
    uint32_t size;
    struct sockaddr_ll my_addr, peer_addr;
    int i_ifindex;
    int ec;
    struct ifreq s_ifr; /* points to one interface returned from ioctl */
    int tmp;

    fd_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if(fd_socket == -1)
    {
        perror("socket");
        return EXIT_FAILURE;
    }
    
    /* clear structure */
    memset(&my_addr, 0, sizeof(struct sockaddr_ll));
    my_addr.sll_family = PF_PACKET;
    my_addr.sll_protocol = htons(ETH_P_ALL);
    
    str_devname = "enp3s0";
    
    /* initialize interface struct */
    strncpy (s_ifr.ifr_name, str_devname, sizeof(s_ifr.ifr_name));
    
    /* Get the broad cast address */
    ec = ioctl(fd_socket, SIOCGIFINDEX, &s_ifr);
    if(ec == -1)
    {
        perror("iotcl");
        return EXIT_FAILURE;
    }
    
    /* update with interface index */
    i_ifindex = s_ifr.ifr_ifindex;
    
    /* set sockaddr info */
    memset(&my_addr, 0, sizeof(struct sockaddr_ll));
    my_addr.sll_family = AF_PACKET;
    my_addr.sll_protocol = ETH_P_ALL;
    my_addr.sll_ifindex = i_ifindex;
    
    /* bind port */
    if (bind(fd_socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll)) == -1)
    {
        perror("bind");
        return EXIT_FAILURE;
    }
    
    /* prepare Tx ring request */
    s_packet_req.tp_block_size = c_buffer_sz;
    s_packet_req.tp_frame_size = c_buffer_sz;
    s_packet_req.tp_block_nr = c_buffer_nb;
    s_packet_req.tp_frame_nr = c_buffer_nb;
    
    /* calculate memory to mmap in the kernel */
    size = s_packet_req.tp_block_size * s_packet_req.tp_block_nr;
    
    /* set packet loss option */
    tmp = mode_loss;
    if (setsockopt(fd_socket, SOL_PACKET, PACKET_LOSS, (char *)&tmp, sizeof(tmp))<0)
    {
        perror("setsockopt: PACKET_LOSS");
        return EXIT_FAILURE;
    }
 
    /* send TX ring request */
    if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *)&s_packet_req, sizeof(s_packet_req))<0)
    {
        perror("setsockopt: PACKET_TX_RING");
        return EXIT_FAILURE;
    }
    
    /* change send buffer size */
    if(c_sndbuf_sz) {
        printf("send buff size = %d\n", c_sndbuf_sz);
        if (setsockopt(fd_socket, SOL_SOCKET, SO_SNDBUF, &c_sndbuf_sz, sizeof(c_sndbuf_sz))< 0)
        {
            perror("getsockopt: SO_SNDBUF");
            return EXIT_FAILURE;
        }
    }
    
    /* get data offset */
    data_offset = TPACKET_HDRLEN - sizeof(struct sockaddr_ll);
    
    /* mmap Tx ring buffers memory */
    ps_header_start = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd_socket, 0);
    if (ps_header_start == (void*)-1)
    {
        perror("mmap");
        return EXIT_FAILURE;
    }
    
    int i,j;
    int i_index = 0;
    char * data;
    int first_loop = 1;
    struct tpacket_hdr * ps_header;
    int ec_send = 0;
 
    for(i=1; i <= c_packet_nb; i++)
    {
        int i_index_start = i_index;
        int loop = 1;
 
        /* get free buffer */
        do {
            ps_header = ((struct tpacket_hdr *)((void *)ps_header_start + (c_buffer_sz*i_index)));
            data = ((void*) ps_header) + data_offset;
            switch((volatile uint32_t)ps_header->tp_status)
            {
                case TP_STATUS_AVAILABLE:
                    /* fill data in buffer */
                    if(first_loop) {
                        for(j=0;j<c_packet_sz;j++)
                            data[j] = j;
                    }
                    loop = 0;
                break;
 
                case TP_STATUS_WRONG_FORMAT:
                    printf("An error has occured during transfer\n");
                    exit(EXIT_FAILURE);
                break;
 
                default:
                    /* nothing to do => schedule : useful if no SMP */
                    usleep(0);
                    break;
            }
        }
        while(loop == 1);
 
        i_index ++;
        if(i_index >= c_buffer_nb)
        {
            i_index = 0;
            first_loop = 0;
        }
 
        /* update packet len */
        ps_header->tp_len = c_packet_sz;
        /* set header flag to USER (trigs xmit)*/
        ps_header->tp_status = TP_STATUS_SEND_REQUEST;
 
        /* if smp mode selected */
        if(!mode_thread)
        {
            /* send all packets */
            if( ((i&c_send_mask)==0) || (ec_send < 0) || (i == c_packet_nb) )
            {
                /* send all buffers with TP_STATUS_SEND_REQUEST */
                /* Don't wait end of transfer */
                //ec_send = (int) task_send((void*)0);
            }
        }
        else if(c_error) {
 
            if(i == (c_packet_nb/2))
            {
                int ec_close;
                
                if(c_error == 1) {
                    ec_close = close(fd_socket);
                }
                if(c_error == 2) {
                    if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *)&s_packet_req, sizeof(s_packet_req))<0)
                    {
                        perror("setsockopt: PACKET_TX_RING");
                        //return EXIT_FAILURE;
                    }
                }
                break;
            }
        }
    }
    
    //int ec_send;
    static int total=0;
    int blocking = 1;
 
    do
    {   
        /* send all buffers with TP_STATUS_SEND_REQUEST */
        /* Wait end of transfer */
        ec_send = sendto(fd_socket,NULL,0,(blocking? 0 : MSG_DONTWAIT),(struct sockaddr *) ps_sockaddr,sizeof(struct sockaddr_ll));
        
        if(ec_send < 0) {
            perror("send");
            break;
        }
        else if ( ec_send == 0 ) {
            /* nothing to do => schedule : useful if no SMP */
            usleep(0);
        }
        else {
            total += ec_send/(c_packet_sz);
            printf("send %d packets (+%d bytes)\n",total, ec_send);
            fflush(0);
        }
 
    } while(blocking && !shutdown_flag);
    
    return 1;
}

必须填充以太网、ip 和 tcp headers。这是我想出的:

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <linux/if_packet.h>
#include <net/ethernet.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/tcp.h>    //Provides declarations for tcp header
#include <netinet/ip.h> //Provides declarations for ip header
#include <netinet/ether.h>

static char * str_devname= NULL;
static int mode_loss     = 0;
static int c_packet_sz   = 150;
static int c_packet_nb   = 1000;
static int c_buffer_sz   = 1024*8;
static int c_buffer_nb   = 1024;
static int c_sndbuf_sz   = 0;
static int c_send_mask   = 127;
static int c_error       = 0;
static int c_mtu         = 0;
static int mode_thread   = 0;

volatile int fd_socket;
volatile int data_offset = 0;
volatile struct tpacket_hdr * ps_header_start;
volatile struct sockaddr_ll *ps_sockaddr = NULL;
volatile int shutdown_flag = 0;
int done = 0;
struct tpacket_req s_packet_req;

/* 
    96 bit (12 bytes) pseudo header needed for tcp header checksum calculation 
*/
struct pseudo_header
{
    u_int32_t source_address;
    u_int32_t dest_address;
    u_int8_t placeholder;
    u_int8_t protocol;
    u_int16_t tcp_length;
};

/*
    Generic checksum calculation function
*/
unsigned short csum(unsigned short *ptr,int nbytes) 
{
    register long sum;
    unsigned short oddbyte;
    register short answer;

    sum=0;
    while(nbytes>1) {
        sum+=*ptr++;
        nbytes-=2;
    }
    if(nbytes==1) {
        oddbyte=0;
        *((u_char*)&oddbyte)=*(u_char*)ptr;
        sum+=oddbyte;
    }

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


int main( int argc, char ** argv )
{
    uint32_t size;
    struct sockaddr_ll my_addr, peer_addr;
    int i_ifindex;
    int ec;
    struct ifreq s_ifr; /* points to one interface returned from ioctl */
    int tmp;
    FILE * fp;
    char server[254];

    while (!done)
    {
        fp = fopen(argv[1], "r");
        if (!fp)
            exit(EXIT_FAILURE);

    fd_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
    if(fd_socket == -1)
    {
        perror("socket");
        return EXIT_FAILURE;
    }
    
    /* clear structure */
    memset(&my_addr, 0, sizeof(struct sockaddr_ll));
    my_addr.sll_family = PF_PACKET;
    my_addr.sll_protocol = htons(ETH_P_ALL);
    
    str_devname = "enp3s0";
    
    /* initialize interface struct */
    strncpy (s_ifr.ifr_name, str_devname, sizeof(s_ifr.ifr_name));
    
    /* Get the broad cast address */
    ec = ioctl(fd_socket, SIOCGIFINDEX, &s_ifr);
    if(ec == -1)
    {
        perror("iotcl");
        return EXIT_FAILURE;
    }
    
    /* update with interface index */
    i_ifindex = s_ifr.ifr_ifindex;
    
    s_ifr.ifr_mtu = 7200;
    /* update the mtu through ioctl */
    ec = ioctl(fd_socket, SIOCSIFMTU, &s_ifr);
    if(ec == -1)
    {
        perror("iotcl");
        return EXIT_FAILURE;
    }
    
    /* set sockaddr info */
    memset(&my_addr, 0, sizeof(struct sockaddr_ll));
    my_addr.sll_family = AF_PACKET;
    my_addr.sll_protocol = ETH_P_ALL;
    my_addr.sll_ifindex = i_ifindex;
    
    /* bind port */
    if (bind(fd_socket, (struct sockaddr *)&my_addr, sizeof(struct sockaddr_ll)) == -1)
    {
        perror("bind");
        return EXIT_FAILURE;
    }
    
    /* prepare Tx ring request */
    s_packet_req.tp_block_size = c_buffer_sz;
    s_packet_req.tp_frame_size = c_buffer_sz;
    s_packet_req.tp_block_nr = c_buffer_nb;
    s_packet_req.tp_frame_nr = c_buffer_nb;
    
    /* calculate memory to mmap in the kernel */
    size = s_packet_req.tp_block_size * s_packet_req.tp_block_nr;
    
    /* set packet loss option */
    tmp = mode_loss;
    if (setsockopt(fd_socket, SOL_PACKET, PACKET_LOSS, (char *)&tmp, sizeof(tmp))<0)
    {
        perror("setsockopt: PACKET_LOSS");
        return EXIT_FAILURE;
    }
 
    /* send TX ring request */
    if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *)&s_packet_req, sizeof(s_packet_req))<0)
    {
        perror("setsockopt: PACKET_TX_RING");
        return EXIT_FAILURE;
    }
    
    /* change send buffer size */
    if(c_sndbuf_sz) {
        printf("send buff size = %d\n", c_sndbuf_sz);
        if (setsockopt(fd_socket, SOL_SOCKET, SO_SNDBUF, &c_sndbuf_sz, sizeof(c_sndbuf_sz))< 0)
        {
            perror("getsockopt: SO_SNDBUF");
            return EXIT_FAILURE;
        }
    }
    
    /* get data offset */
    data_offset = TPACKET_HDRLEN - sizeof(struct sockaddr_ll);
    
    /* mmap Tx ring buffers memory */
    ps_header_start = mmap(0, size, PROT_READ|PROT_WRITE, MAP_SHARED, fd_socket, 0);
    if (ps_header_start == (void*)-1)
    {
        perror("mmap");
        return EXIT_FAILURE;
    }
    
    
    int i,j;
    int i_index = 0;
    char * data;
    int first_loop = 1;
    struct tpacket_hdr * ps_header;
    int ec_send = 0;
 
    for(i=1; i <= c_packet_nb; i++)
    {
        int i_index_start = i_index;
        int loop = 1;
 
        /* get free buffer */
        do {
            ps_header = ((struct tpacket_hdr *)((void *)ps_header_start + (c_buffer_sz*i_index)));
            data = ((void*) ps_header) + data_offset;
            switch((volatile uint32_t)ps_header->tp_status)
            {
                case TP_STATUS_AVAILABLE:
                    /* fill data in buffer */
                    if(first_loop) {
                        //Datagram to represent the packet
                        char datagram[4096] , source_ip[32] , *data2, *pseudogram;
    
                        //zero out the packet buffer
                        memset (datagram, 0, 4096);
    
                        //Ethernet header
                        struct ether_header *eh = (struct ether_header *) datagram;
        
                        //IP header
                        struct iphdr *iph = (struct iphdr *) (datagram + sizeof (struct ether_header));
    
                        //TCP header
                        struct tcphdr *tcph = (struct tcphdr *) (datagram + sizeof (struct ether_header) + sizeof (struct ip));
                        struct sockaddr_in sin;
                        struct pseudo_header psh;
    
                        //Data part
                        data2 = datagram + sizeof(struct ether_header) + sizeof(struct iphdr) + sizeof(struct tcphdr);
                        strcpy(data2 , "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    
                        //some address resolution
                        strcpy(source_ip , "192.168.1.70");
                        sin.sin_family = AF_INET;
                        sin.sin_port = htons(80);
                        if (fscanf(fp, "%253s", server) == 1)
                            sin.sin_addr.s_addr = inet_addr (server);   
                        else
                        {
                            done = 1;
                            break;
                        }
                        
                        //Fill in the Ethernet Header
                        eh->ether_dhost[0] = 0x70;
                        eh->ether_dhost[1] = 0x97;
                        eh->ether_dhost[2] = 0x41;
                        eh->ether_dhost[3] = 0x4b;
                        eh->ether_dhost[4] = 0x1e;
                        eh->ether_dhost[5] = 0xc2;
                        eh->ether_shost[0] = 0xc4;
                        eh->ether_shost[1] = 0x65;
                        eh->ether_shost[2] = 0x16;
                        eh->ether_shost[3] = 0x24; 
                        eh->ether_shost[4] = 0xd5;
                        eh->ether_shost[5] = 0x9a;
                        eh->ether_type = 0x0008;
    
                        //Fill in the IP Header
                        iph->ihl = 5;
                        iph->version = 4;
                        iph->tos = 0;
                        iph->tot_len = sizeof (struct iphdr) + sizeof (struct tcphdr) + strlen(data);
                        iph->id = htonl (54321);    //Id of this packet
                        iph->frag_off = 0;
                        iph->ttl = 255;
                        iph->protocol = IPPROTO_TCP;
                        iph->check = 0;     //Set to 0 before calculating checksum
                        iph->saddr = inet_addr ( source_ip );   //Spoof the source ip address
                        iph->daddr = sin.sin_addr.s_addr;
    
                        //Ip checksum
                        iph->check = csum ((unsigned short *) datagram, iph->tot_len);
    
                        //TCP Header
                        tcph->source = htons (1234);
                        tcph->dest = htons (80);
                        tcph->seq = 0;
                        tcph->ack_seq = 0;
                        tcph->doff = 5; //tcp header size
                        tcph->fin=0;
                        tcph->syn=1;
                        tcph->rst=0;
                        tcph->psh=0;
                        tcph->ack=0;
                        tcph->urg=0;
                        tcph->window = htons (5840);    // maximum allowed window size 
                        tcph->check = 0;    //leave checksum 0 now, filled later by pseudo header
                        tcph->urg_ptr = 0;

                        //Now the TCP checksum
                        psh.source_address = inet_addr( source_ip );
                        psh.dest_address = sin.sin_addr.s_addr;
                        psh.placeholder = 0;
                        psh.protocol = IPPROTO_TCP;
                        psh.tcp_length = htons(sizeof(struct tcphdr) + strlen(data) );
    
                        int psize = sizeof(struct pseudo_header) + sizeof(struct tcphdr) + strlen(data);
                        pseudogram = malloc(psize);
    
                        memcpy(pseudogram , (char*) &psh , sizeof (struct pseudo_header));
                        memcpy(pseudogram + sizeof(struct pseudo_header) , tcph , sizeof(struct tcphdr) + strlen(data));
    
                        tcph->check = csum( (unsigned short*) pseudogram , psize);
                        
                        memcpy(data, datagram, 4096);
//                      for(j=0;j<c_packet_sz;j++)
//                          data[j] = j;
                    }
                    loop = 0;
                break;
 
                case TP_STATUS_WRONG_FORMAT:
                    printf("An error has occured during transfer\n");
                    exit(EXIT_FAILURE);
                break;
 
                default:
                    /* nothing to do => schedule : useful if no SMP */
                    usleep(0);
                    break;
            }
        }
        while(loop == 1);
 
        i_index ++;
        if(i_index >= c_buffer_nb)
        {
            i_index = 0;
            first_loop = 0;
        }
 
        /* update packet len */
        ps_header->tp_len = c_packet_sz;
        /* set header flag to USER (trigs xmit)*/
        ps_header->tp_status = TP_STATUS_SEND_REQUEST;
 
        /* if smp mode selected */
        if(!mode_thread)
        {
            /* send all packets */
            if( ((i&c_send_mask)==0) || (ec_send < 0) || (i == c_packet_nb) )
            {
                /* send all buffers with TP_STATUS_SEND_REQUEST */
                /* Don't wait end of transfer */
                //ec_send = (int) task_send((void*)0);
            }
        }
        else if(c_error) {
 
            if(i == (c_packet_nb/2))
            {
                int ec_close;
                
                if(c_error == 1) {
                    ec_close = close(fd_socket);
                }
                if(c_error == 2) {
                    if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *)&s_packet_req, sizeof(s_packet_req))<0)
                    {
                        perror("setsockopt: PACKET_TX_RING");
                        //return EXIT_FAILURE;
                    }
                }
                break;
            }
        }
    }
    
    //int ec_send;
    static int total=0;
    int blocking = 1;
        
    /* send all buffers with TP_STATUS_SEND_REQUEST */
    /* Wait end of transfer */
    ec_send = sendto(fd_socket,NULL,0,(blocking? 0 : MSG_DONTWAIT),(struct sockaddr *) ps_sockaddr,sizeof(struct sockaddr_ll));
        
    if(ec_send < 0) {
        perror("send");
    }
    else if ( ec_send == 0 ) {
        /* nothing to do => schedule : useful if no SMP */
        usleep(0);
    }
    else {
        total += ec_send/(c_packet_sz);
        printf("send %d packets (+%d bytes)\n",total, ec_send);
        fflush(0);
    }
    
    close(fd_socket);
 
    }
    return 1;
}