|
我的设备有两个网卡驱动,一个是物理网口驱动,另一个是虚拟网口的驱动,物理网口的ip是192.168.110.4 ,虚拟网口的ip是192.168.11.6.我写了个udp广播的程序,发送广播,但是每次都是从物理网口发出去的,我怎样才能让他从虚拟网口发出去呢?是不是我的程序有错误?
INT32 UdpBroadcastGet(void)
{
struct sockaddr_in s_addr_r;
struct sockaddr_in s_addr_t;
INT32 sock_udp = 0;
INT32 addr_len = 0;
INT32 len = 0;
ST_REQ stReq = {0};
ST_RSP stRsp = {0};
INT32 i_opt = 1;
INT32 iResend = 0;
fd_set readfds;
INT32 maxfds = 0;
struct timeval tv;
if ((sock_udp = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
return -1;
}
setsockopt(sock_udp, SOL_SOCKET, SO_BROADCAST, &i_opt, sizeof(i_opt));
s_addr_r.sin_family = AF_INET;
s_addr_r.sin_port = htons(DATA_PORT);
s_addr_r.sin_addr.s_addr = htonl(INADDR_ANY);
s_addr_t.sin_family = AF_INET;
s_addr_t.sin_port = htons(DATA_PORT);
s_addr_t.sin_addr.s_addr = htonl(INADDR_BROADCAST);
if (-1 == bind(sock_udp, (struct sockaddr*)&s_addr_r, sizeof(struct sockaddr)))
{
return -1;
}
stReq.u_id = gId;
addr_len = sizeof(struct sockaddr_in);
for (iResend = 0; iResend < 10; iResend++)
{
DebugPrintf("resend times is %d\n", iResend);
len = sendto(sock_udp, (INT8*)&stReq, sizeof(ST_REQ), 0, (struct
sockaddr *)&s_addr_t, addr_len);
if (len < 0)
{
printf("\n\rsend error.\n\r");
continue;
}
FD_ZERO(&readfds);
FD_SET(sock_udp, &readfds);
tv.tv_sec = 10;
tv.tv_usec = 0;
maxfds = sock_udp + 1;
select(maxfds, &readfds, NULL, NULL, &tv);
if (FD_ISSET(sock_udp, &readfds))
{
len = recvfrom(sock_udp, (INT8*)&stRsp, DATA_LEN, 0, NULL,
&addr_len);
if (-1 == len)
{
printf("recv err\n");
continue;
}
return 0;
}
}
return -1;
}
|
|