UDP 广播的发送和接收

// 接收端
 
#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
 
 
using namespace std;
 
int main()
{
	// 绑定地址
	struct sockaddr_in addrto;
	bzero(&addrto, sizeof(struct sockaddr_in));
	addrto.sin_family = AF_INET;
	addrto.sin_addr.s_addr = htonl(INADDR_ANY);
	addrto.sin_port = htons(6000);
	
	// 广播地址
	struct sockaddr_in from;
	bzero(&from, sizeof(struct sockaddr_in));
	from.sin_family = AF_INET;
	from.sin_addr.s_addr = htonl(INADDR_ANY);
	from.sin_port = htons(6000);
	
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<<endl;	
		return false;
	}   
 
	if(bind(sock,(struct sockaddr *)&(addrto), sizeof(struct sockaddr_in)) == -1) 
	{   
		cout<<"bind error..."<<endl;
		return false;
	}
 
	int len = sizeof(sockaddr_in);
	char smsg[100] = {0};
 
	while(1)
	{
		//从广播地址接受消息
		int ret=recvfrom(sock, smsg, 100, 0, (struct sockaddr*)&from,(socklen_t*)&len);
		if(ret<=0)
		{
			cout<<"read error...."<<sock<<endl;
		}
		else
		{		
			cout<<smsg<<endl;	
		}
 
		sleep(1);
	}
 
	return 0;
}

 

// 发送端

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<<"socket error"<<endl;	
		return false;
	}   
	
	const int opt = 1;
	//设置该套接字为广播类型,
	int nb = 0;
	nb = setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
	if(nb == -1)
	{
		cout<<"set socket error..."<<endl;
		return false;
	}
 
	struct sockaddr_in addrto;
	bzero(&addrto, sizeof(struct sockaddr_in));
	addrto.sin_family=AF_INET;
	addrto.sin_addr.s_addr=htonl(INADDR_BROADCAST);
	addrto.sin_port=htons(6000);
	int nlen=sizeof(addrto);
 
	while(1)
	{
		sleep(1);
		//从广播地址发送消息
		char smsg[] = {"abcdef"};
		int ret=sendto(sock, smsg, strlen(smsg), 0, (sockaddr*)&addrto, nlen);
		if(ret<0)
		{
			cout<<"send error...."<<ret<<endl;
		}
		else
		{		
			cout<<"ok"<<endl;	
		}
	}
 
	return 0;
}

 

 

c++类

#ifndef UDP_BROADCAST_H
#define UDP_BROADCAST_H

#include <iostream>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define UDP_BROADCAST_PORT 6666

using namespace std;

class UdpBroadcast
{
public:
    ///
    /// \brief UdpBroadcast
    ///
    UdpBroadcast();

    ~UdpBroadcast();

    ///
    /// \brief open
    /// \return
    ///
    bool Open();

    int BroadcastData(const char* str);

    ///
    /// \brief 关闭监听
    ///
    void Close();

    ///
    /// \brief IsOpened
    /// \return
    ///
    bool IsOpened() {
        return isOpened;
    }

private:
    int sockfd;
    sockaddr_in dest;
    int chilen;
    bool isOpened;
};

#endif // UDP_BROADCAST_H



#include "udpbroadcast.h"
#include <fcntl.h>

UdpBroadcast::UdpBroadcast() :
    isOpened(false)
{
    sockfd = -1;
}

UdpBroadcast::~UdpBroadcast()
{
    this->Close();
}

bool UdpBroadcast::Open()
{
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        cout<<"socket error"<<endl;
        close(sockfd);
        return false;
    }

    fcntl(sockfd, F_SETFD, FD_CLOEXEC);///< 子进程不继承该描述符

    const int opt = 1;
    //设置该套接字为广播类型,
    int nb = 0;
    nb = setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, (char *)&opt, sizeof(opt));
    if(nb != 0)
    {
        cout<<"set socket error..."<<endl;
        close(sockfd);
        return false;
    }

    bzero(&dest, sizeof(struct sockaddr_in));
    dest.sin_family = AF_INET;
    dest.sin_addr.s_addr = htonl(INADDR_BROADCAST);
    dest.sin_port = htons(UDP_BROADCAST_PORT);
    isOpened = true;
    return true;
}

int UdpBroadcast::BroadcastData(const char *str)
{
    if(!isOpened)
        return -1;

    //从广播地址发送消息
    chilen = sizeof(dest);
    int ret=sendto(sockfd, str, strlen(str), 0, (sockaddr*)&dest, chilen);

    if(ret<0)
    {
        perror("send error....");
        isOpened = false;
        close(sockfd);
        return ret;
    }
    else
    {
        cout<<"send data is : "<< str<<" len : "<<strlen(str)<<" sockfd : "<<sockfd<<endl;
    }
}

void UdpBroadcast::Close()
{
    if(isOpened) {
        isOpened = false;
        close(sockfd);
    }
}

 

  • 5
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值