广播接收端:
#include<stdio.h>
#include<stdlib.h>#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h>
#include <signal.h>
void myfun(int sig)
{
printf("catch sigalrm!\n");
}
int main(int argc, const char *argv[])
{
int serverfd = socket(AF_INET, SOCK_DGRAM, 0);
if (serverfd == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
int on = 1;
setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8888);
servaddr.sin_addr.s_addr = (argv[1] == NULL ? INADDR_ANY : inet_addr(argv[1]));
if (bind(serverfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
{
perror("bind");
exit(EXIT_FAILURE);
}
printf("bind success\n");
char buff[1024];
while(1)
{
int recvbytes = recvfrom(serverfd, buff, sizeof(buff), 0, NULL, NULL);
if(recvbytes == -1)
{
if (errno == EAGAIN || errno == EWOULDBLOCK)
{
printf("No data to recv\n");
sleep(1);
continue;
}
perror("recvfrom");
break;
}
printf("recv:%s", buff);
}
close(serverfd);
return 0;
}
广播发送端:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <netinet/in.h>
#include <arpa/inet.h>
int main(int argc, const char *argv[])
{
int clientfd = socket(AF_INET, SOCK_DGRAM, 0);
if (clientfd == -1)
{
perror("socket");
exit(EXIT_FAILURE);
}
struct sockaddr_in servaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(8888);
servaddr.sin_addr.s_addr = inet_addr("192.168.100.255");
int on = 1;
setsockopt(clientfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on));
char buff[1024];
while (fgets(buff, sizeof(buff), stdin))
{
if (strncmp(buff, "quit", 4) == 0)
{
break;
}
int sndbytes = sendto(clientfd, buff, sizeof(buff), 0,(struct sockaddr*)&servaddr, sizeof(servaddr));
if (sndbytes == -1)
{
perror("sendto");
break;
}
}
close(clientfd);
return 0;
}