#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>
#include <string.h>
struct{
int sid;
struct sockaddr_in destinaion;
}data;
void* groupmem_send(void* s){
char *send_buf = calloc(1,100);
while(1){
// printf("data.sid=%d\n",data.sid);
fgets(send_buf,99,stdin);
if(-1==sendto(data.sid,send_buf,100,0,(struct sockaddr*)&(data.destinaion),(socklen_t)sizeof(struct sockaddr_in)))
printf("-----------------------\n");
// printf("buf=%s\n",send_buf);
bzero(send_buf,100);
}
return NULL;
}
int main(int argc,char* argv[])
{
//1.创建套接字
data.sid = socket(AF_INET,SOCK_DGRAM,0);
//2.设置套接字的属性
//广播设置
int bt = 1;
setsockopt(data.sid, SOL_SOCKET, SO_BROADCAST, &bt, (socklen_t)sizeof(bt));
//-1失败,懒得判断了
// printf("data.sid=%d\n",data.sid);
//定义组播地址结构体,给组播地址成员赋值,给本机地址成员赋值
struct ip_mreq zubo;
zubo.imr_multiaddr.s_addr = inet_addr("224.17.17.17");
zubo.imr_interface.s_addr = INADDR_ANY;
socklen_t zubo_len = sizeof(zubo);
setsockopt(data.sid, IPPROTO_IP, IP_ADD_MEMBERSHIP, &zubo, zubo_len);
//3.绑定地址
struct sockaddr_in local,foreign,broadcast;
local.sin_family = AF_INET;
local.sin_port = htons(atoi(argv[1]));
local.sin_addr.s_addr = INADDR_ANY;
socklen_t foreign_len = sizeof(foreign);
bind(data.sid,(struct sockaddr*)&local,(socklen_t)sizeof(local));
// printf("myip=%s\n",inet_ntoa(local.sin_addr));//0.0.0.0
//组播
data.destinaion.sin_family = AF_INET;
data.destinaion.sin_port = htons(atoi(argv[1]));
data.destinaion.sin_addr.s_addr = inet_addr("224.17.17.17");
//广播
broadcast.sin_family = AF_INET;
broadcast.sin_port = htons(atoi(argv[1]));
broadcast.sin_addr.s_addr = inet_addr("192.168.124.255");
char str[20] = "hello,everyone!\n";
//为什么自己能收到啊?//利用这个特性
sendto(data.sid,str,20,0,(struct sockaddr*)&broadcast,sizeof(broadcast));
pthread_t pid;
pthread_create(&pid,NULL,groupmem_send,NULL);
char *buf = calloc(1,100),*end=calloc(1,300),*jump=calloc(1,300);
while(1){
recvfrom(data.sid,buf,100,0,(struct sockaddr*)&foreign,&foreign_len);
snprintf(jump,300,"来自IP:%s端口号为:%d:数据为:%s",inet_ntoa(foreign.sin_addr),ntohs(foreign.sin_port),buf);
printf("%s\n",jump);
if(strlen(end)==0)
snprintf(end,300,"来自IP:%s端口号为:%d:数据为:end\n",inet_ntoa(foreign.sin_addr),ntohs(foreign.sin_port));
if(strcmp(end,jump)==0)
break;
bzero(jump,300);
bzero(buf,100);
}
char str2[20] = "byebye!\n";
sendto(data.sid,str2,20,0,(struct sockaddr*)&broadcast,sizeof(broadcast));
return 0;
}
网络编程第九次作业(2024.8.21)
最新推荐文章于 2024-08-31 21:24:29 发布