目的
多个网卡想单独使用的话可以使用不同的IP绑定,但是这样比较麻烦,也可以使用相同的IP,这样一个设备虽然有多个网卡,但只有一个IP,可以将需要的程序socket绑定到固定的网卡。这样虽然是相同的IP,但是可以独立使用了。
应用程序
代码语言:javascript复制int initUdpBroadCastSocket_eth0(void)
{
struct ifreq opt1;
const char *inface = "eth0";//根据自己的情况修改
strncpy(opt1.ifr_name, inface,IFNAMSIZ);
const int opt = 1;
int nb = 0;
struct sockaddr_in myaddr;
int sockfd = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
if (-1 == sockfd)
{
return -1;
}
nb = setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&opt1, sizeof(opt1));
if(nb == -1)
{
perror("socket_ETH0 error");
return -1;
}
nb = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
perror("socket_ETH0 error");
return -1;
}
return sockfd;
}
int initUdpBroadCastSocket_ethyzd(void)
{
struct ifreq opt1;
const char *inface = "ethyzd";//根据自己的情况修改
strncpy(opt1.ifr_name, inface,IFNAMSIZ);
const int opt = 1;
int nb = 0;
struct sockaddr_in myaddr;
int sockfd = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP);
if (-1 == sockfd)
{
return -1;
}
nb = setsockopt(sockfd, SOL_SOCKET, SO_BINDTODEVICE, (char *)&opt1, sizeof(opt1));
if(nb == -1)
{
perror("socket_ETHyzd error");
return -1;
}
nb = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
if(nb == -1)
{
perror("socket_ETHyzd error");
return -1;
}
return sockfd;
}
testeth(void *arg)
{
int recv_len, send_len;
int ETH0_bindtest1;
int ETHyzd_bindtest1;
socklen_t addr_len;
struct sockaddr_in recv_address;
struct sockaddr_in airLC6500_addr;
char recv_buffer1[] ={"testeth0"};
char recv_buffer2[] ={"testethyzd"};
ETH0_bindtest1 = initUdpBroadCastSocket_eth0();
ETHyzd_bindtest1 = initUdpBroadCastSocket_ethyzd();
while(1)
{
send_len = sendUdp(ETH0_bindtest1, BROADCAST_IP, testyzd1, recv_buffer1, sizeof(recv_buffer1));
send_len = sendUdp(ETHyzd_bindtest1, BROADCAST_IP, testyzd2, recv_buffer2, sizeof(recv_buffer2));
sleep(1);
}
int main(void)
{
pthread_t AIRCTRL_SEND_Process_Thread;
pthread_create(&AIRCTRL_RECEIVE_Process_Tread, NULL, AIRCTRL_Data1_Recv_Process, NULL);
/* main Task */
while(1)
{}
}