windows系统存在多个网卡,发送广播包的时候,容易出现发送的网卡不正确问题!
多网卡发送数据的时候,如果想指定网卡,使用bind函数,进行ip地址和端口的绑定,将想要使用的网卡上的地址,进行bind,这样在发包时就可以使用bind的地址进行发送。从而达到指定网卡发送的目的。
#include <stdio.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <vector>
#include <string>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
class UDPSender
{
public:
UDPSender()
{
m_sock = -1;
}
~UDPSender() {}
// 需要注意区分 netAddr 和 localAddr
bool SetRecvAddr(const char* netAddr, const char* localAddr, int port)
{
int iRet = 0;
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0)
{
std::cout << "socket init error!";
return false;
}
sockaddr_in addrSrv;
addrSrv.sin_addr.s_addr = inet_addr(netAddr); // 局域网段 192.168.1.255
addrSrv.sin_family = AF_INET;
addrSrv.sin_port = htons(port);
if ((addrSrv.sin_addr.s_addr >> 24) == 0xff)//if addr end with 255 then broadcast
{
isBroadCast = true;
sockaddr_in addrSrvLocal;
addrSrvLocal.sin_addr.s_addr = inet_addr(localAddr); // 指定的网卡ip 192.168.1.113
addrSrvLocal.sin_family = AF_INET;
addrSrvLocal.sin_port = 0;//unuse
if (bind(sock, (sockaddr*)&addrSrvLocal, sizeof(addrSrvLocal)) != 0)
{
cout << "bind local ip error!";
return false;
}
int opval = 1;
addrSrv.sin_addr.s_addr = htonl(INADDR_BROADCAST);
setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char*)&opval, sizeof(opval));
}
m_sock = sock;
m_sockaddr = addrSrv;
return true;
}
void Send(const char* buf, int bufsize)
{
int n=sendto(m_sock, buf, bufsize, 0, (struct sockaddr*)&m_sockaddr, sizeof(sockaddr));
}
std::vector<std::string> LocalIP;
bool isBroadCast;
int m_sock;
sockaddr_in m_sockaddr;
};
int main()
{
UDPSender sender1, sender2;
if (sender1.SetRecvAddr("192.168.1.255","192.168.1.113", 9999) == true)
{
//cout << "BroadCasting 192.168.23 ...";
sender1.Send("hello", sizeof("hello"));
}
if (sender2.SetRecvAddr("10.20.30.255", "192.168.1.113", 9999) == true)
{
cout << "BroadCasting 10.20.30 ...";
sender2.Send("hello", sizeof("hello"));
}
return 1;
}
linux版本 https://blog.csdn.net/wmx313880747/article/details/44942499