//监听端口
int listen_udp_port(void)
{
#ifdef DEBUG
printf("now start listen udp func which port is 2009 ");
#endif
int inet_sock, socklen, so_reuseaddr = 1;
char data[128];
char buff[128];
struct sockaddr_in addr, from;
socklen = sizeof(addr);
//建立socket
if ((inet_sock = socket(AF_INET, SOCK_DGRAM, 0))< 0)
perror("Listen UDP created socket error");
if (setsockopt(inet_sock, SOL_SOCKET, SO_REUSEADDR, &so_reuseaddr,
sizeof(so_reuseaddr)) < 0)
{
perror("Listen UDP set socket error");
close(inet_sock);
return 1;
}
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(UDP_PORT);
addr.sin_family = AF_INET;
if (bind(inet_sock, (struct sockaddr *)&addr, sizeof addr)<0)
{
perror("Listen UDP bind socket error");
close(inet_sock);
return 2;
}
int len;
for (;;)
{
len = recvfrom(inet_sock, data, 127, 0, (struct sockaddr *)&from,
(socklen_t*)&socklen);
if(len < 0)
{
perror("Listen UDP send error");
close(inet_sock);
return 3;
}
else
{
broadcast();
getpeermac(inet_sock, buff);
data[len] = '\0';
printf("收到来自%s:%d的消息:%s\n\r",
inet_ntoa(from.sin_addr), ntohs(from.sin_port), data);
memset(data, 0, 128);
}
memset(&from, 0, sizeof(from));
}
close(inet_sock);
return 0;
}
//广播
void broadcast()
{
int inet_sock, so_broadcast = 1;
struct sockaddr_in adr_bc;
if ((inet_sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
perror("Broadcast UDP created socket error");
if (setsockopt(inet_sock, SOL_SOCKET, SO_BROADCAST, &so_broadcast,
sizeof(so_broadcast)) < 0)
{
perror("Broadcast UDP set socket error");
close(inet_sock);
return;
}
adr_bc.sin_family = AF_INET;
adr_bc.sin_port = htons(UDP_PORT1);
adr_bc.sin_addr.s_addr = inet_addr("255.255.255.255");
if (sendto(inet_sock, BROAD_CONTENT, strlen(BROAD_CONTENT), 0,
(struct sockaddr *)&adr_bc, sizeof(adr_bc))< 0)
{
perror("Broadcast send error!");
close(inet_sock);
return;
}
close(inet_sock);
}
|