Windows UDP 广播(Cmake Project)

1. main.c

#include <iostream>
#include <string>
#include <WS2tcpip.h>
#include <WinSock2.h>             
// #include <thread>
using namespace std;

int mySender = -1;
struct sockaddr_in mySendAddr_;
void Function();

int main()
{
          
   
    Function();
    system("pause");
    return 0;
}
void Function()
{
          
   
    int brdcFd;
    int iResult;
    WSADATA wsaData;
    mySender = -1;

    // Initialize Winsock 
    iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
    if (iResult != 0) {
          
   
        cout << "WSAStartup failed with error:" << iResult << endl;
        return;
    }
    else{
          
   
        cout << "WSAStartup succeed! Return number:" << iResult << endl;
    }

    if((brdcFd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
          
   
        cout << "udp socket init fail." << endl;
        return;
    }
    else{
          
   
        mySender = brdcFd;
        cout << "udp socket init succeed." << endl;
    }

    if(brdcFd)
    {
          
   
        int sendBytes = -1;
        int optval = 1;
        char str[50] = "UDP Broadcast Information.";
        /*
		 * 请将对应网络设备更改为 192.168.123.XXX
		 * */
        const string broadcastAddr = "192.168.123.255"; 
        int count = 0;

        setsockopt(brdcFd, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, 
            (char*)&optval, sizeof(int));

        mySendAddr_.sin_family = AF_INET;
        mySendAddr_.sin_port = htons(8080);
        mySendAddr_.sin_addr.s_addr = inet_addr(broadcastAddr.c_str());

        while(1)
        {
          
   
              if((sendBytes = sendto(brdcFd, str, 50, 0,
                (struct sockaddr *)&mySendAddr_, sizeof(struct sockaddr))) == -1)
                {
          
   
                    cout << "UDP send failed." << endl;
                }
                else
                {
          
   
                    memset(str, 0, 50);
                    cout << "UDP sent for the " << ++count << "rd time." << endl;  
                    sprintf(str, "UDP sent for the %drd time.",count);
                    if(count > 9999)count=0;  
                }

                Sleep(100);

                // std::this_thread::sleep_for(std::chrono::milliseconds(100));
        }
    }
}

2. 现象

1. 程序输出

2. 检查(WireShark)

3. 其它

1. 工程其它部分

1. CmakeList.txt 与文件目录

cmake_minimum_required(VERSION 3.10.0)
# project name and language
project(main LANGUAGES CXX)
set(CMAKE_CXX_STANDARD 11)
aux_source_directory(${
          
   CMAKE_SOURCE_DIR} main_ALL_SRC)
add_executable(main ${
          
   main_ALL_SRC})
# 添加库文件目录(如果使用 MSVC 编译器则不用链接 ws2_32.lib)
link_directories(lib)
# 链接库文件
target_link_libraries(main ws2_32.lib)

2. bash.bat

    当前文件夹命令行输入:.ash.bat
@REM /s:递归删除 /q:强制删除
rmdir /s/q build 
mkdir build
cd build

@REM MINGW 编译器
@REM cmake -G "MinGW Makefiles" ..
@REM cmake --build .
@REM cd ..

@REM MSVC 编译器
cmake -G "Visual Studio 15 2017 Win64" ..
cmake --build . --target ALL_BUILD --config Release
cd Release
.main.exe
cd ....

2. 注意网络连接设置

经验分享 程序员 微信小程序 职场和发展