代码模拟二层lldp报文,从socket接口发送出去,这是协议报文
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <malloc.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <linux/if_packet.h>
#define INTERFACE_NAME "eth0"
int main(void)
{
static struct sockaddr_ll sll_g;
int sockfd;
// unsigned char lldp_mac[6] = {0x01, 0x80, 0xC2, 0x00, 0x00, 0x0E};
struct ifreq *ifr = malloc (sizeof (struct ifreq));
sockfd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL));
if (0 > sockfd) {
perror("socket error");
exit(EXIT_FAILURE);
}
memset (&sll_g, 0, sizeof (struct sockaddr_ll));
memset (ifr, 0, sizeof (struct ifreq));
sll_g.sll_family = PF_PACKET;
sll_g.sll_protocol = htons (ETH_P_ALL);
sll_g.sll_halen = 6;
sll_g.sll_ifindex = if_nametoindex (INTERFACE_NAME);
strcpy (ifr->ifr_name, INTERFACE_NAME);
if (bind (sockfd, (struct sockaddr *) &sll_g, sizeof (struct sockaddr_ll)) < 0)
{
close (sockfd);
return 0;
}
ioctl (sockfd, SIOCGIFFLAGS, ifr);
ifr->ifr_flags |= IFF_ALLMULTI; /* allmulti on (verified via ifconfig) */
// ifr->ifr_flags |= IFF_PROMISC; /*promisc on (verified via ifconfig) */
ioctl (sockfd, SIOCSIFFLAGS, ifr);
if (ioctl (sockfd, SIOCGIFHWADDR, ifr) == -1)
{
close (sockfd);
return 0;
}
char send_msg[105] = {0x01 ,0x80, 0xc2, 0x00, 0x00, 0x0e, 0x90, 0xe2, 0xfc, 0x00, 0x3b, 0x4f, 0x88, 0xcc, 0x02, 0x07,
0x04, 0x90, 0xe2, 0xfc, 0x00, 0x3b, 0x4f, 0x04, 0x04, 0x07, 0x47, 0x45, 0x31, 0x06, 0x02, 0x00,
0x0a, 0x08, 0x05, 0x70, 0x6f, 0x72, 0x74, 0x31, 0x0a, 0x05, 0x54, 0x39, 0x30, 0x30, 0x34, 0x0c,
0x22, 0x54, 0x4f, 0x50, 0x2d, 0x54, 0x45, 0x4b, 0x20, 0x49, 0x6e, 0x64, 0x75, 0x73, 0x74, 0x72,
0x69, 0x61, 0x6c, 0x20, 0x45, 0x74, 0x68, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x53, 0x77, 0x69,
0x74, 0x63, 0x68, 0x0e, 0x04, 0x00, 0xff, 0x00, 0xff, 0x10, 0x0c, 0x05, 0x01, 0xc0, 0xa8, 0x01,
0xe0, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
free (ifr);
int msg_len = 105;
for ( ; ; ) {
int len = sendto(sockfd, send_msg, msg_len, 0 , (struct sockaddr *)&sll_g, sizeof(sll_g));
if(len == -1) {
perror("sendto");
}
sleep(10);
}
close(sockfd);
exit(EXIT_SUCCESS);
}