我板卡的双网卡分别是192.168.2.111、192.168.1.111,假设他们分别接收来自192.168.2.2、192.168.1.10的数据。
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
int main(void)
{
int udp_socket_fd = socket(AF_INET,SOCK_DGRAM,0);
if(udp_socket_fd < 0)
{
printf("create socket fail\n");
return -1;
}
//2.设置UDP的地址并绑定
struct sockaddr_in local_addr = {0};
local_addr.sin_family = AF_INET; //使用IPv4协议
local_addr.sin_port = htons(161); //网络通信都使用大端格式
local_addr.sin_addr.s_addr = INADDR_ANY;//让系统检测本地网卡,自动绑定本地IP
//设置目的IP地址
struct sockaddr_in dest_addr = {0};
dest_addr.sin_family = AF_INET;//使用IPv4协议
dest_addr.sin_port = htons(161);//设置接收方端口号
int ret = bind(udp_socket_fd,(struct sockaddr*)&local_addr,sizeof