简体   繁体   English

如何在C中将数据包写入TAP接口?

[英]How to write a packet to TAP interface in C?

Does any one know how to write a packet into a TAP interface in C? 有人知道如何将数据包写入C中的TAP接口吗? Or any other language? 还是其他任何语言?

I have constructed an Ethernet datagram by myself, and I want to write it to a specific tap interface. 我自己构建了一个以太网数据报,我想把它写到一个特定的tap接口。

Thanks! 谢谢! :) :)

About TAP: http://en.wikipedia.org/wiki/TUN/TAP 关于TAP: http//en.wikipedia.org/wiki/TUN/TAP

Assuming you've created a TAP interface already (using ip tuntap add ), you can use a Packet Socket to write data into it (try man 7 packet for more info). 假设您已经创建了一个TAP接口(使用ip tuntap add ),您可以使用Packet Socket将数据写入其中(尝试man 7 packet以获取更多信息)。

To start with, use int sockfd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL)) to create a packet socket. 首先,使用int sockfd = socket(AF_PACKET, SOCK_DGRAM, htons(ETH_P_ALL))来创建数据包套接字。

The second step is to find the interface index ( ifindex ) of the TAP interface. 第二步是找到TAP接口的接口索引ifindex )。 Just run the command ip link and note down the number at the beginning of each line. 只需运行命令ip link并记下每行开头的数字。 For instance, 例如,

[nav@blumarine Test02]$ ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN mode DEFAULT 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
2: p12p1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast state DOWN mode DEFAULT qlen 1000
    link/ether 00:26:b9:24:82:16 brd ff:ff:ff:ff:ff:ff
3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP mode DORMANT qlen 1000
    link/ether c4:17:fe:8c:f7:c8 brd ff:ff:ff:ff:ff:ff

the ifindex of lo will be 1 and that of eth0 will be 3. lo的ifindex为1, eth0的ifindex为3。

The third step is to fill in a sockaddr_ll structure to pass to the sendto() api. 第三步是填写sockaddr_ll结构以传递给sendto() api。 This structure is used to hold the info about your packet's destination address. 此结构用于保存有关数据包的目标地址的信息。 Fill it exactly this way: 以这种方式填写:

struct sockaddr_ll SendSockAddr;
SendSockAddr.sll_family   = AF_PACKET;
SendSockAddr.sll_halen    = ETH_ALEN;
SendSockAddr.sll_ifindex  = ifindex;   // The number we just found earlier..
SendSockAddr.sll_protocol = htons(ETH_P_ALL);
SendSockAddr.sll_hatype   = 0;
SendSockAddr.sll_pkttype  = 0;

And finally, use sendto() to send your packet out. 最后,使用sendto()发送数据包。 Use man 3 sendto for more info on sendto() and man 7 packet for more insight into struct sockaddr_ll . 使用man 3 sendto获取有关sendto()man 7 packet更多信息,以便更深入地了解struct sockaddr_ll

Good luck :) 祝好运 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM