#include <stdio.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
int sock_fd = -1;
struct ip_mreq zubo;
struct sockaddr_in local;
struct sockaddr_in opposite;
typedef struct chuan
{
struct sockaddr_in a;
char *s_buf b;
}Chuan;
pthread_t tid1;
void * sendfun(void *arg)
{
char *s_buf = malloc(100);
s_buf = *(Chuan*)arg.b;
struct sockaddr_in addr = *(Chuan*)arg.a;
while(1)
{
memset(s_buf,0,100);
sendto(sock_fd,s_buf,100,0,(struct sockaddr *)&addr,sizeof(addr));
}
}
int main(int argc,char **argv)
{
//1.创建套接字
sock_fd = socket(AF_INET,SOCK_DGRAM,0);
//2.设置套接字的属性
//定义组播地址结构体,给组播地址成员赋值,给本机地址成员赋值
zubo.imr_multiaddr.s_addr = inet_addr("224.10.10.10");//224.0.0.0-----238.255.255.255
zubo.imr_interface.s_addr = INADDR_ANY;
socklen_t zubo_len = sizeof(zubo);
setsockopt(sock_fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &zubo, zubo_len);
//3.绑定
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[1]));//10000
local.sin_addr.s_addr = INADDR_ANY;
socklen_t local_len = sizeof(local);
socklen_t opposite_len = sizeof(opposite);
bind(sock_fd,(struct sockaddr *)&local,local_len);
char *r_buf = malloc(100);
Chuan a1 = {opposite,r_buf};
pthread_create(&tid1,NULL,sendfun,(void *)&Chuan);
while(1)
{
memset(r_buf,0,100);
recvfrom(sock_fd,r_buf,100,0,(struct sockaddr *)&opposite,&opposite_len);
printf("from multi:%s\n",r_buf);
}
}
#include <stdio.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
int main(int argc,char **argv)
{
//1.创建套接字
int sock_fd = socket(AF_INET,SOCK_DGRAM,0);
//2.绑定
struct sockaddr_in zubo;
zubo.sin_family = AF_INET;
zubo.sin_port = htons(atoi(argv[1]));
zubo.sin_addr.s_addr = inet_addr("224.10.10.10");
socklen_t zubo_len = sizeof(zubo);
bind(sock_fd,(struct sockaddr *)&zubo,zubo_len);
char *buf = malloc(100);
while(1)
{
memset(buf,0,100);
fgets(buf,100,stdin);
sendto(sock_fd,buf,100,0,(struct sockaddr *)&zubo,zubo_len);
}
}