linux c socket之局域网广播
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
免费下载资源
·
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include "Utility.h"
//局域网广播发送,配合该工具检测http://download.csdn.net/download/ben395575481/1796582
static const char * IN6ADDR_ALLNODES="FF02::1";//v6 addr
int main(int argc, char** argv) {
//检测参数
if(argc!=4)
DieWithUserMessage("param","[4][6] <port> <string to send>");
in_port_t port=htons((in_port_t)atoi(argv[2]));
//配置地址结构
struct sockaddr_storage destStoreage;
memset(&destStoreage,0,sizeof(destStoreage));
size_t addr_size=0;
if(argv[1][0]=='4')
{
//使用IP4
struct sockaddr_in *destAddr4=(struct sockaddr_in*)&destStoreage;
destAddr4->sin_family=AF_INET;
destAddr4->sin_port=port;
destAddr4->sin_addr.s_addr=INADDR_BROADCAST;//广播
addr_size=sizeof(struct sockaddr_in);
}else if(argv[1][0]=='6')
{
//使用IP6
struct sockaddr_in6 *destAddr6=(struct sockaddr_in6*)&destStoreage;
destAddr6->sin6_family=AF_INET6;
destAddr6->sin6_port=port;
inet_pton(AF_INET6,IN6ADDR_ALLNODES,&destAddr6->sin6_addr);
addr_size=sizeof(struct sockaddr_in6);
}else{
DieWithUserMessage("Unknown address family",argv[1]);
}
//转化为最后的地址
struct sockaddr *destAddress=(struct sockaddr*)&destStoreage;
size_t msg_len=strlen(argv[3]);
if(msg_len>MAXSTRINGLENGTH)
{
DieWithUserMessage("string too long ",argv[3]);
}
//建立socket
int sock=socket(destAddress->sa_family,SOCK_DGRAM,IPPROTO_UDP);
if(sock<0)
DieWithSystemMessage("socket() failed!");
int broadcastPerm=1;
//设置socket允许发送局域网广播
if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&broadcastPerm,sizeof(broadcastPerm))<0)
{
DieWithSystemMessage("setsockopt() failed!");
}
int i=0;
for(;;)
{
printf("send broadcast %d!\n",i++);
//循环发送广播数据
ssize_t numBytes=sendto(sock,argv[3],msg_len,0,destAddress,addr_size);
if(numBytes<0)
DieWithSystemMessage("sendto() failed!");
else if(numBytes!=msg_len)
DieWithUserMessage("sendto()","sent unexpected number of bytes");
sleep(3);
}
return (EXIT_SUCCESS);
}
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
已为社区贡献27条内容
所有评论(0)