UDP放送の送受信

2408 ワード

//    
 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
 
 
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<

 
//    

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
 
using namespace std;
 
int main()
{
	int sock = -1;
	if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) 
	{   
		cout<

 
 
c++クラス
#ifndef UDP_BROADCAST_H
#define UDP_BROADCAST_H

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#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 

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

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

bool UdpBroadcast::Open()
{
    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
    {
        cout<