win7或win10下UDP广播包收发失败

因为工作须要,需要实现一个UDP发送广播包到设备的需求。

若是是linux下,那很简单,可是上位机要求是windows平台。发现没办法在设备端收到发送的广播包。使用Wireshark调试,监听对应的广播地址,也没有收到任何数据。

windows都不用检查防火墙,电脑的防火墙也都关了。后来看到stackoverflow.com上面有人也遇到了一样的问题,可是没有给出具体的例子。简单来讲缘由是这样的:win7以前的系统,发送广播包是到PC全部的网卡上。 win7及之后,是要求指定广播包的源IP,简单说bind的IP不能是INADDR_ANY

//--------------------------------------------
#include "stdafx.h"
#include <WinSock2.h>
#include <Windows.h>
#include <string.h>
using namespace std;
#pragma comment(lib, "ws2_32.lib")

int main(int argc, char *argv[])
{
    SOCKET s;
    struct sockaddr_in server, si_other;
    int slen ;
    
    WSADATA wsa;
 
    slen = sizeof(si_other) ;
     
    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");
     
    //Create a socket
    if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    {
        printf("Could not create socket : %d" , WSAGetLastError());
    }
    printf("Socket created.\n");
     int so_broadcast = TRUE;
    setsockopt(s, SOL_SOCKET, SO_BROADCAST, (char *)&so_broadcast, sizeof(so_broadcast));    
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    /* the card IP of the PC*/
    printf("send BC package on the port with IP %s\n", argv[1]);
    server.sin_addr.s_addr = inet_addr(argv[1]);   // -----------------> SPECIFIC THE IP HERE
    server.sin_port = htons( 9989 );
     
    //Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
        printf("Bind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    puts("Bind done");
     si_other.sin_family = AF_INET;
    si_other.sin_addr.S_un.S_addr =htonl(INADDR_BROADCAST);
    //unsigned long ip = inet_addr("172.17.255.255");
    //b_addr.sin_addr.S_un.S_addr =htonl(ip);
    si_other.sin_port = htons(9988);
    //keep listening for data
    while(1)
    {
        //buf the buffer by filling null, it might have previously received data
        char buf[128] = "ADD YOUR PAYLOAD HERE";
             
        //now reply the client with the same data
        if (sendto(s, buf, strlen(buf), 0, (struct sockaddr*) &si_other, slen) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }
        printf("send... %d\n", WSAGetLastError());
        Sleep(1000);

    }
 
    closesocket(s);
    WSACleanup();
     
    return 0;
}

参考链接

1. UDP – Broadcast

2. 网络UDP广播包发不出去或接收不到问题

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值