packet mmap发送包格式

时间:2011-11-29 01:47:58

标签: linux sockets network-programming

我想提高数据包传输性能。在此之前我使用原始套接字,现在我研究packet_mmap。 我有来自另一台PC的内核模块捕获的数据包(帧),放到当前的PC上,现在我想通过以下转发将它们重新发送到本地接口。 我有packet_mmap的例子,将它集成到我的项目中,但是我发送了

fd_socket = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
memset(&my_addr, 0, sizeof(struct sockaddr_ll));
my_addr.sll_family = PF_PACKET;
my_addr.sll_protocol = htons(ETH_P_ALL);
strcpy(str_devname, "eth0");
strncpy(s_ifr.ifr_name, str_devname, sizeof(s_ifr.ifr_name));
ec = ioctl(fd_socket, SIOCGIFINDEX, &s_ifr);
i_ifindex = s_ifr.ifr_ifindex;
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(fd_socket, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_ll)
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;
size = s_packet_req.tp_block_size * s_packet_req.tp_block_nr;
if (setsockopt(fd_socket, SOL_PACKET, PACKET_TX_RING, (char *) &s_packet_req, sizeof(s_packet_req)) < 0) {
 perror("setsockopt: PACKET_TX_RING");
 return;
}

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");
  exit(1);
 }
}

data_offset = TPACKET_HDRLEN - sizeof(struct sockaddr_ll);
printf("data offset = %d bytes\n", data_offset);
ps_header_start = (tpacket_hdr *) mmap(0, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd_socket, 0);
if (ps_header_start == (void*) -1) {
 perror("mmap");
 exit(1);
}

然后我填写数据

ps_header = ((struct tpacket_hdr *) ((char *) ps_header_start + (c_buffer_sz * i_index)));
if (!ps_header) {
 perror("ps_header") ;
 return NULL;
}
data = ((char*) ps_header) + data_offset;
switch ((volatile uint32_t) ps_header->tp_status) {
  case TP_STATUS_AVAILABLE:
      printf("TP_STATUS_AVAILABLE, index=%d\n",i_index) ;
      memcpy(data, packet_data, size);

pthread_mutex_lock(&index_locker) ;
i_index++;
pthread_mutex_unlock(&index_locker) ;

if (i_index >= c_buffer_nb) {
    i_index = 0;
    first_loop = 0;
}

/* update packet len */
ps_header->tp_len = size;
/* set header flag to USER (trigs xmit)*/
ps_header->tp_status = TP_STATUS_SEND_REQUEST;

然后我发送

ec_send = sendto(fd_socket, NULL, 0, 0, (struct sockaddr *) ps_sockaddr, sizeof(struct sockaddr_ll));

我没有错误,ec_send = not null已发送数据的大小。但是没有数据路由到目标主机。

所以,我问 - 我应该传递给环缓冲区的数据,现在我包括头文件ip,tcp,我应该包含MAC头吗? - 可能是我必须设置其他标志来路由我的数据包。

1 个答案:

答案 0 :(得分:2)

您正在使用SOCK_RAW创建套接字。这意味着您有权提供第2层信息(以太网/ MAC地址)。您可以使用SOCK_DGRAM创建套接字。内核将处理第2层信息以放置下一跳的以太网地址。试试吧。