当前位置: 技术问答>linux和unix
原始套接字接收是多了4个字节,是怎么回事?
来源: 互联网 发布时间:2017-02-01
本文导语: 本帖最后由 kulung 于 2011-09-09 14:10:10 编辑 rt 两个一样的开发板,一个发送,一个接收,不管哪边发哪边接,接收方都会多四个字节,正好多在二层数据帧协议出,不知道如何解决,以下是源代码: //send.c #include #inc...
//send.c
#include
#include //perror
#include //strcpy,memset
#include //socket
#include //ioctl
#include //ifreq
#include //sockaddr_sll
#include //ETH_P_ALL
#define IFRNAME0 "eth0"
#define IFRNAME2 "eth2"
#define BUF_SIZE 2048
char buf[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int main(int argc, char *argv[])
{
int i, sfd, len;
struct sockaddr_ll sll;
struct ifreq ifr;
if ((sfd=socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
perror("socket");
return 0;
}
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, IFRNAME0);
if ((ioctl(sfd, SIOCGIFINDEX, &ifr)) == -1) {
strcpy(ifr.ifr_name, IFRNAME2);
if ((ioctl(sfd, SIOCGIFINDEX, &ifr)) == -1) {
perror("ioctl 1");
close(sfd);
return 0;
}
}
memset(&sll, 0, sizeof(sll));
sll.sll_family = PF_PACKET;
sll.sll_ifindex = ifr.ifr_ifindex;
sll.sll_protocol = htons(ETH_P_ALL);
if ((bind(sfd, (struct sockaddr *)&sll, sizeof(sll))) == -1) {
perror("bind");
close(sfd);
return 0;
}
while (1) {
len = sizeof(buf);
sendto(sfd, buf, len, 0, (struct sockaddr *)&sll, sizeof(sll));
printf("send data2: %dn", len);
for(i=0; i