1、对比
服务端:
需要利用这个函数开发套接字的发广播权限,并且需要客户端地址绑定为广播地址
setsocket(sockfd,SOL_SOCKET,SO_BROADCAST,&flag,sizeof(flag));
客户端没有什么变化
2、代码
2.1、服务端
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <net/if.h>
#define PORT 9999
#define CLIENT_PORT 8888
void sys_perr(const char* str)
{
perror(str);
exit(1);
}
#define SER_PORT 9999
int main()
{
int fd = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in ser_addr,cli_addr;
ser_addr.sin_family = AF_INET;
ser_addr.sin_port = htons(SER_PORT);
ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(fd,(struct sockaddr*)&ser_addr,sizeof(ser_addr));
int opt = 1;
setsockopt(fd,SOL_SOCKET,SO_BROADCAST,&opt,sizeof(opt));
cli_addr.sin_family = AF_INET;
cli_addr.sin_port = htons(CLIENT_PORT);
inet_pton(AF_INET,"本地广播地址",&cli_addr.sin_addr.s_addr);
int i = 0;
char buf[1024];
while (1)
{
sprintf(buf,"hello %d\n",i++);
printf("buf=%s\n",buf);
int len = sendto(fd,buf,strlen(buf)+1,0,(struct sockaddr*)&cli_addr,sizeof(cli_addr));
printf("%d\n",len);
sleep(1);
}
return 0;
}
2.2、客户端
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <net/if.h>
#define CLIENT_PORT 8888
void sys_perr(const char* str)
{
perror(str);
exit(1);
}
#define SER_PORT 9999
int main()
{
int fd = socket(AF_INET,SOCK_DGRAM,0);
struct sockaddr_in cli_addr;
cli_addr.sin_family = AF_INET;
cli_addr.sin_port = htons(CLIENT_PORT);
inet_pton(AF_INET,"0.0.0.0",&cli_addr.sin_addr.s_addr);
bind(fd,(struct sockaddr*)&cli_addr,sizeof(cli_addr));
char buf[1024];
while (1)
{
int len = recvfrom(fd,buf,sizeof(buf),0,NULL,0);
printf("%d\n",len);
write(STDOUT_FILENO,buf,len);
}
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)