rt 两个一样的开发板,一个发送,一个接收,不管哪边发哪边接,接收方都会多四个字节,正好多在二层数据帧协议出,不知道如何解决,以下是源代码:
//send.c
#include <stdio.h>
#include <stdlib.h> //perror
#include <string.h> //strcpy,memset
#include <sys/socket.h> //socket
#include <sys/ioctl.h> //ioctl
#include <net/if.h> //ifreq
#include <linux/if_packet.h> //sockaddr_sll
#include <linux/if_ether.h> //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: %d\n", len);
for(i=0; i<len; i++)
printf("%x", buf[i]);
printf("\n");
}
close(sfd);
return 1;
}
//recv.c
#include <stdio.h>
#include <stdlib.h> //perror
#include <string.h> //strcpy,memset
#include <sys/socket.h> //socket
#include <sys/ioctl.h> //ioctl
#include <net/if.h> //ifreq
#include <linux/if_packet.h> //sockaddr_sll
#include <linux/if_ether.h> //ETH_P_ALL
#define IFRNAME0 "eth0"
#define IFRNAME2 "eth2"
#define BUF_SIZE 2048
char buf[BUF_SIZE];
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 = recvfrom(sfd, buf, sizeof(buf), 0, NULL, NULL);
printf("recv data2: %d\n", len);
if (len>0) {
for(i=0; i<len; i++)
printf("%x", buf[i]);
printf("\n");
}
}
close(sfd);
return 1;
}