windows下IPv6 UDP组播(C++、MFC)📞
🌈 linux下 IPv6组播(C++) 🍓windows下IPv4 UDP通信(C++、MFC) 📞windows下IPv6 UDP通信(C++、MFC) 🍎 windows下IPv6 UDP组播(C++、MFC)
Server
#include <stdio.h>
#include <Ws2tcpip.h>
#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
#define PORT 6060
#define IP "ff02::2"
#define BUF_LEN 256
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(wVersionRequested, &wsaData);
struct sockaddr_in6 addr = { AF_INET6, htons(PORT) };
int l_nServer;
if ((l_nServer = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
{
perror("创建失败");
return -1;
}
bind(l_nServer, (struct sockaddr*)&addr, sizeof(addr));
struct ipv6_mreq group;
group.ipv6mr_interface = 0;
inet_pton(AF_INET6, IP, &group.ipv6mr_multiaddr);
setsockopt(l_nServer, IPPROTO_IPV6, IPV6_ADD_MEMBERSHIP, (char*)&group, sizeof(group));
int l_naddLen = sizeof(addr);
int l_nReadLen = 0;
char msgbuf[BUF_LEN];
printf("等待接收\n");
while (1)
{
l_nReadLen = recvfrom(l_nServer, msgbuf, BUF_LEN, 0, (struct sockaddr*)&addr, &l_naddLen);
if (l_nReadLen < 0)
{
perror("接收失败");
exit(1);
}
msgbuf[l_nReadLen] = '\0';
printf("%s\n", msgbuf);
strcpy_s(msgbuf, "world");
int l_nLen = sendto(l_nServer, msgbuf, strlen(msgbuf), 0, (struct sockaddr*)&addr, sizeof(addr));
if (l_nLen < 0)
{
perror("发送失败");
exit(1);
}
printf("Send %s\n", msgbuf);
}
return 0;
}
Cilect
#include <stdio.h>
#include <Ws2tcpip.h>
#include <winsock2.h>
#define HELLO_PORT 7905
#define HELLO_GROUP "224.0.0.1"
#pragma comment(lib,"ws2_32.lib")
int main(int argc, char* argv[])
{
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(1, 1);
WSAStartup(0x0202, &wsaData);
int l_nCilect;
struct sockaddr_in6 addr = { AF_INET6, htons(6060) };
if ((l_nCilect = socket(AF_INET6, SOCK_DGRAM, 0)) < 0)
{
perror("创建失败");
exit(1);
}
inet_pton(AF_INET6, "ff02::2", &addr.sin6_addr);
char message[128];
int l_naddLen = sizeof(addr);
while (1)
{
strcpy_s(message, "hello");
int l_nLen = sendto(l_nCilect, message, strlen(message), 0, (struct sockaddr*)&addr, sizeof(addr));
if (l_nLen < 0)
{
perror("发送失败");
exit(1);
}
printf("Send %s\n", message);
Sleep(1000);
int l_nReadLen = recvfrom(l_nCilect, message, strlen(message), 0, (struct sockaddr*)&addr, &l_naddLen);
if (l_nReadLen < 0)
{
perror("接收失败");
exit(1);
}
message[l_nReadLen] = '\0';
printf("%s\n", message);
}
return 0;
}
|