socket_can配置

socket_can配置介绍

1.打开can设备

int fd = -1;
//打开can0设备
fd = open("/sys/devices/platform/FlexCAN.1/bitrate",O_CREAT | O_TRUNC | O_WRONLY,0600);
if(fd < 0)
{
	printf("CAN1 InitDevice Failed : Open config flie failed \n");
	return false;		
}

2.写入波特率

write(fd,125000,6);

3.创建socket,设置为原始套接字,原始CAN协议

int g_nCan0Hand = -1;
g_nCan0Hand = socket(PF_CAN, SOCK_RAW, CAN_RAW);     
strcpy(g_Can0Ifreq.ifr_name, "can0");
//设备驱动管理
nResult = ioctl(g_nCan0Hand, SIOCGIFINDEX, &g_Can0Ifreq);
if (nResult < 0) 
{
	printf("CAN0 InitDevice Failed : ioctl failed \n");
	return false;
}

4.设置can协议

struct sockaddr_can g_Can0SocketAddr;
struct sockaddr_can g_Can1SocketAddr;

5.将刚生成的套接字与CAN套接字地址进行绑定

nResult = bind(g_nCan0Hand, (struct sockaddr *)&g_Can0SocketAddr, sizeof(g_Can0SocketAddr));  
if (nResult < 0) 
{
	printf("CAN0 InitDevice Failed : bind failed \n");
	return false;
}

6.设置套接字

nResult = setsockopt(g_nCan0Hand, SOL_CAN_RAW, CAN_RAW_FILTER, &g_Can0Cfg.RxFilter[0], g_Can0Cfg.nRxFilterCount * sizeof(g_Can0Cfg.RxFilter[0]));
if (nResult < 0) 
{
	printf("CAN0 InitDevice Failed : Set Rx Filter failed \n");
	return false;
}

can网络接口结构体

Struct ifreq{
Char ifr_name[IFNAMSIZ];
Union{
    Struct  sockaddr  ifru_addr;
    Struct  sockaddr  ifru_dstaddr;
    Struct  sockaddr  ifru_broadaddr;
    Struct  sockaddr  ifru_netmask;
    Struct  sockaddr  ifru_hwaddr;
    Short  ifru_flags;
    Int     ifru_metric;
    Caddr_t ifru_data;
}ifr_ifru;
};

 

你可能感兴趣的:(can)