发送广播消息
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include <errno.h> int main(void)
{
char rgMessage[] = "I am sending message to you!";
int iFd;
int iSendbytes;
int iOptval = ;
struct sockaddr_in Addr;
if ((iFd = socket(AF_INET, SOCK_DGRAM, )) == -)
{
printf("socket fail\n");
return -;
} if (setsockopt(iFd, SOL_SOCKET, SO_BROADCAST | SO_REUSEADDR, &iOptval, sizeof(int)) < )
{
printf("setsockopt failed!");
}
memset(&Addr, , sizeof(struct sockaddr_in));
Addr.sin_family = AF_INET;
Addr.sin_addr.s_addr = inet_addr("255.255.255.255");
Addr.sin_port = htons(); while ()
{
if ((iSendbytes = sendto(iFd, rgMessage, strlen(rgMessage), , (struct sockaddr*)&Addr, sizeof(struct sockaddr))) == -)
{
printf("sendto fail, errno=%d\n", errno);
return -;
}
printf("rgMessage=%s, rgMessageLen=%d,iSendbytes=%d\n", rgMessage, strlen(rgMessage), iSendbytes);
sleep();
}
close(iFd); return ;
}
接收广播消息
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h> int main(void) { int iAddrLength;
char rgMessage[];
int iOptval = ;
int iFd;
struct sockaddr_in Addr; if ((iFd = socket(AF_INET, SOCK_DGRAM, )) == -)
{
printf("socket fail\n");
return -;
} if (setsockopt(iFd, SOL_SOCKET, SO_REUSEADDR, &iOptval, sizeof(int)) < )
{
printf("setsockopt failed!\n");
}
memset(&Addr, , sizeof(struct sockaddr_in));
Addr.sin_family = AF_INET;
Addr.sin_addr.s_addr = INADDR_ANY;
Addr.sin_port = htons();
iAddrLength = sizeof(Addr); if (bind(iFd, (struct sockaddr *)&Addr, sizeof(Addr)) == -)
{
printf("bind failed!\n");
} while ()
{
if (recvfrom(iFd, rgMessage, sizeof(rgMessage), , (struct sockaddr *)&Addr, &iAddrLength) == -)
{
printf("recv failed!\n");
}
printf("recv:%s\n", rgMessage);
} close(iFd); return ;
}