广播:
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
//1.创建套接字
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd == -1)
{
perror("socket error:");
return -1;
}
//2.设置服务器的地址
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(10086);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//自动识别本机ip
//3.设置选项参数 (设置端口号重用)
int val = 1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));
//4.把套接字和网络地址进行绑定
int re = bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(re == -1)
{
perror("bind error:");
return -1;
}
struct sockaddr_in addr;
int len = sizeof(addr);
while(1)
{
//接收数据
char recvbuf[128];
recvfrom(sockfd,recvbuf,128,0,(struct sockaddr*)&addr,&len);
printf("ip = %s:%s\n",inet_ntoa(addr.sin_addr),recvbuf);
}
close(sockfd);
}
组播:
#include <stdio.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main()
{
//1. 创建套接字
int sockfd = socket(AF_INET,SOCK_DGRAM,0);
if(sockfd == -1)
{
perror("socket error:");
return -1;
}
//2.把本机ip加入到多播组
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr("224.1.2.3");
//mreq.imr_interface.s_addr = inet_addr("192.168.3.13");
mreq.imr_interface.s_addr = htonl(INADDR_ANY);
//加入多播组
setsockopt(sockfd,IPPROTO_IP, IP_ADD_MEMBERSHIP,&mreq, sizeof(mreq));
//3.绑定 组ip
struct sockaddr_in server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(10086);
server_addr.sin_addr.s_addr = inet_addr("224.1.2.3");// 绑定组 ip
//4.设置选项参数 (设置端口号重用)
int val = 1;
setsockopt(sockfd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));
int re = bind(sockfd,(struct sockaddr*)&server_addr,sizeof(server_addr));
if(re == -1)
{
perror("bind error:");
return -1;
}
printf("start:\n");
struct sockaddr_in addr;
int len = sizeof(addr);
while(1)
{
char recvbuf[128] = {0};
recvfrom(sockfd,recvbuf,128,0,(struct sockaddr*)&addr,&len);
printf("ip = %s:%s\n",inet_ntoa(addr.sin_addr),recvbuf);
}
close(sockfd);
}