#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
#define BROADCAST_UDP_PORT 15566 //udp端口
#define BROADCAST_ADDR "255.255.255.255" //广播地址
#define MAX 255
char *udpdata = "XXXXXXXXXXXXXXXX"; //udp data,对应服务器规则
struct BroadcastIp{
char *ip;
char *mac;
char *name;
}bdip[30];//存放返回的数据
int ipCount = 0;//计算总ip
int main(void)
{
//printf("\n\n---[%d %s]---\n\n",__LINE__,__FUNCTION__);//调试方法
int sockfd,ret;
int len;
char recv[128] = {0};
struct sockaddr_in my_con;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
/*************************************************
@第一个参数domain:协议族决定了socket的地址类型,在通信中必须采用对应的地址,如AF_INET决定了要用ipv4地址(32位的)与端口号(16位的)的组合、AF_UNIX决定了要用一个绝对路径名作为地址。
@第二个参数type:指定Socket类型。常用的socket类型有SOCK_STREAM、SOCK_DGRAM、SOCK_RAW、SOCK_PACKET、SOCK_SEQPACKET等。流式Socket(SOCK_STREAM)是一种面向连接的Socket,针对于面向连接的TCP服务应用。数据报式Socket(SOCK_DGRAM)是一种无连接的Socket,对应于无连接的UDP服务应用。
@protocol:指定协议。常用协议有IPPROTO_TCP、IPPROTO_UDP、IPPROTO_STCP、IPPROTO_TIPC等,分别对应TCP传输协议、UDP传输协议、STCP传输协议、TIPC传输协议。
@注意:1.type和protocol不可以随意组合,如SOCK_STREAM不可以跟IPPROTO_UDP组合。当第三个参数为0时,会自动选择第二个参数类型对应的默认协议。
*************************************************/
if(sockfd < 0)
{
perror("socket error!\n");
return 1;
}
my_con.sin_family = AF_INET;
my_con.sin_port = ntohs(BROADCAST_UDP_PORT);
my_con.sin_addr.s_addr = inet_addr(BROADCAST_ADDR);
len = sizeof(struct sockaddr);
/* 设置通讯方式广播,即本程序发送的一个消息,网络上所有的主机均可以收到 */
setsockopt(sockfd,SOL_SOCKET,SO_BROADCAST,&sockfd,sizeof(sockfd));
ret = sendto(sockfd,udpdata,strlen(udpdata),0,(struct sockaddr *)&my_con,len);//发送函数
if( ret < 0)
{
perror("send error!\n");
return 1;
}
printf("sendto : %s\n",udpdata);
ipCount = 0;//bzero
int size = sizeof(struct sockaddr_in);
//loop recv
while(1)
{
memset(recv,0,128);
ret = recvfrom(sockfd,recv,MAX,0,(struct sockaddr *)&my_con,(socklen_t*)&size);//接收函数
recv[ret] = '\0';
if(ret > 0)
{
//服务器返回的数据:192.168.0.88,ABBC21RR266C,HF-LPB100
bdip[ipCount].ip = strtok(recv,","); //device ip
bdip[ipCount].mac = strtok(NULL,","); //device mac
bdip[ipCount].name = strtok(NULL,","); //device name
if((bdip[ipCount].ip == NULL) || (bdip[ipCount].mac == NULL) || (bdip[ipCount].name == NULL))
{
continue;
}
printf("\n\n\n\n[%d %s] ip : %s , mac : %s , other : %s\n\n\n",__LINE__,__FUNCTION__,bdip[ipCount].ip,bdip[ipCount].mac,bdip[ipCount].name);
}
}
close(sockfd);//关闭
return 0;
}
socket发送udp广播包
最新推荐文章于 2025-05-03 14:11:22 发布