c++ 使用UDP协议实现广播
程序员文章站
2022-06-29 18:34:55
...
文章参考:
Windows:https://blog.csdn.net/great3779/article/details/5699986
稍微替博主整理一下子/哈哈
Linux: https://blog.csdn.net/robertkun/article/details/8475843
1. Windows 服务器端
// 服务器端
// Server.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#include <iostream>
using namespace std;
#pragma comment(lib, "ws2_32.lib")
const int MAX_BUF_LEN = 255;
int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
// 启动socket api
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return -1;
}
if ( LOBYTE( wsaData.wVersion ) != 2 ||
HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup( );
return -1;
}
// 创建socket
SOCKET connect_socket;
connect_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == connect_socket)
{
err = WSAGetLastError();
printf("/"socket/" error! error code is %d/n", err);
return -1;
}
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3779);
sin.sin_addr.s_addr = INADDR_BROADCAST;
bool bOpt = true;
//设置该套接字为广播类型
setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));
int nAddrLen = sizeof(SOCKADDR);
char buff[MAX_BUF_LEN] = "";
int nLoop = 0;
while(1)
{
nLoop++;
sprintf(buff, "%8d", nLoop);
// 发送数据
int nSendSize = sendto(connect_socket, buff, strlen(buff), 0, (SOCKADDR*)&sin, nAddrLen);
if(SOCKET_ERROR == nSendSize)
{
err = WSAGetLastError();
printf("/"sendto/" error!, error code is %d/n", err);
return -1;
}
printf("Send: %s/n", buff);
Sleep(500);
}
return 0;
}
2. Windows 客户端
// 客户端
// Client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <WinSock2.h>
#include <stdio.h>
#pragma comment(lib, "ws2_32.lib")
const int MAX_BUF_LEN = 255;
int _tmain(int argc, _TCHAR* argv[])
{
WORD wVersionRequested;
WSADATA wsaData;
int err;
// 启动socket api
wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
if ( err != 0 )
{
return -1;
}
if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 )
{
WSACleanup( );
return -1;
}
// 创建socket
SOCKET connect_socket;
connect_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(INVALID_SOCKET == connect_socket)
{
err = WSAGetLastError();
printf("/"socket/" error! error code is %d/n", err);
return -1;
}
// 用来绑定套接字
SOCKADDR_IN sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(3779);
sin.sin_addr.s_addr = 0;
// 用来从网络上的广播地址接收数据
SOCKADDR_IN sin_from;
sin_from.sin_family = AF_INET;
sin_from.sin_port = htons(3779);
sin_from.sin_addr.s_addr = INADDR_BROADCAST;
//设置该套接字为广播类型,
bool bOpt = true;
setsockopt(connect_socket, SOL_SOCKET, SO_BROADCAST, (char*)&bOpt, sizeof(bOpt));
// 绑定套接字
err = bind(connect_socket, (SOCKADDR*)&sin, sizeof(SOCKADDR));
if(SOCKET_ERROR == err)
{
err = WSAGetLastError();
printf("/"bind/" error! error code is %d/n", err);
return -1;
}
int nAddrLen = sizeof(SOCKADDR);
char buff[MAX_BUF_LEN] = "";
int nLoop = 0;
while(1)
{
// 接收数据
int nSendSize = recvfrom(connect_socket, buff, MAX_BUF_LEN, 0, (SOCKADDR*)&sin_from, &nAddrLen);
if(SOCKET_ERROR == nSendSize)
{
err = WSAGetLastError();
printf("/"recvfrom/" error! error code is %d/n", err);
return -1;
}
buff[nSendSize] = '/0';
printf("Recv: %s/n", buff);
}
return 0;
}
3. Linux 客户端
// 发送端
#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()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
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
{
printf("ok ");
}
}
return 0;
}
4. Linux 服务器端
#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()
{
setvbuf(stdout, NULL, _IONBF, 0);
fflush(stdout);
// 绑定地址
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;
}
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;
}
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
{
printf("%s\t", smsg);
}
sleep(1);
}
return 0;
}
上一篇: UDP---广播的实现