发送端
#include<stdio.h>
#include<Windows.h>
#include<windows.h>
#include<WinSock2.h>
#include<string.h>
#include<stdlib.h>
#define ERR_OR(msg) do{\
fprintf(stderr, "__%d__", __LINE__);\
perror(msg);\
}while(0)
constexpr auto IP = "192.168.122.88";
constexpr auto PORT = 8888;
int main()
{
int cfd = socket(AF_INET, SOCK_DGRAM, 0);
if (cfd<0)
{
ERR_OR("socket");
return -1;
}
printf("cfd=%d\n", cfd);
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
char buf[128];
int num = 0;
while (num<15)
{
num++;
memset(buf,0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf) - 1] = '\0';
if (sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_OR("sendto");
return -1;
}
puts("sendto sucss");
}
closesocket(cfd);
return 0;
}
接收端
#include<myy.h>
#define ERR_OR(msg) do{\
fprintf(stderr,"__%d__",__LINE__);\
perror(msg);\
}while(0)
#define GIP "224.1.2.3"
#define LIP "192.168.123.92"
#define PORT 8888
int main()
{
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if (sfd<0)
{
ERR_OR(msg);
return -1;
}
printf("sfd=%d\n",sfd);
struct ip_mreqn mq;
mq.imr_multiaddr.s_addr=inet_addr(GIP);
mq.imr_address.s_addr =inet_addr(LIP);
mq.imr_ifindex =0;
printf("加入小组成功%s,端口%d\n",GIP,PORT);
struct sockaddr_in sin;
sin.sin_family =AF_INET;
sin.sin_port =htons(PORT);
sin.sin_addr.s_addr=inet_addr(GIP);
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_OR("bind");
return -1;
}
puts("bind YES");
struct sockaddr_in cin;
socklen_t addrlen=sizeof(cin);
char buf[128];
int num=0;
while(num<15)
{
num++;
bzero(buf,sizeof(buf));
if(recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&addrlen)<0)
{
ERR_OR("recvfrom");
return -1;
}
printf("[%s:%d]:%s\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),buf);
}
close(sfd);
return 0;
}