作者:手机用户2602915671 | 来源:互联网 | 2023-08-06 15:16
广播 向子网 中多台计算机发送消息,并且子网中所有的计算机都可以接收到发送方发送的消息,每个广播消息都包含一个特殊的IP地址,这个IP中子网内主机标志部分的二进制全部为1(也就是网络号是255)。 a. 只能在局域网中使用。 b. 客户端需要绑定服务器广播使用的端口 ,才可以接收到广播消息。
只能在局域网中使用;
int setsockopt ( int sockfd, int level, int optname, const void * optval, socklen_t optlen) ; - 参数: - sockfd : 文件描述符- level : SOL_SOCKET- optname : SO_BROADCAST- optval : int 类型的值,为1 表示允许广播- optlen : optval的大小
广播代码较UDP代码需要做的改变:
服务端需要设置广播属性 服务端不需要使用bind进行绑定; 客户端需要绑定服务端使用的端口; # include # include # include # include # include int main ( ) { int fd = socket ( PF_INET, SOCK_DGRAM, 0 ) ; if ( fd == - 1 ) { perror ( "socket" ) ; exit ( - 1 ) ; } int op = 1 ; setsockopt ( fd, SOL_SOCKET, SO_BROADCAST, & op, sizeof ( op) ) ; struct sockaddr_in cliaddr; cliaddr. sin_family = AF_INET; cliaddr. sin_port = htons ( 9999 ) ; inet_pton ( AF_INET, "192.168.193.255" , & cliaddr. sin_addr. s_addr) ; -- 注意网络号使用255 int num = 0 ; while ( 1 ) { char sendBuf[ 128 ] ; sprintf ( sendBuf, "hello, client....%d\n" , num++ ) ; sendto ( fd, sendBuf, strlen ( sendBuf) + 1 , 0 , ( struct sockaddr * ) & cliaddr, sizeof ( cliaddr) ) ; printf ( "广播的数据:%s\n" , sendBuf) ; sleep ( 1 ) ; } close ( fd) ; return 0 ; }
# include # include # include # include # include int main ( ) { int fd = socket ( PF_INET, SOCK_DGRAM, 0 ) ; if ( fd == - 1 ) { perror ( "socket" ) ; exit ( - 1 ) ; } struct in_addr in; struct sockaddr_in addr; addr. sin_family = AF_INET; addr. sin_port = htons ( 9999 ) ; addr. sin_addr. s_addr = INADDR_ANY; int ret = bind ( fd, ( struct sockaddr * ) & addr, sizeof ( addr) ) ; if ( ret == - 1 ) { perror ( "bind" ) ; exit ( - 1 ) ; } while ( 1 ) { char buf[ 128 ] ; int num = recvfrom ( fd, buf, sizeof ( buf) , 0 , NULL , NULL ) ; printf ( "server say : %s\n" , buf) ; } close ( fd) ; return 0 ; }
服务端:
客户端1: 192.168.193.128
客户端2: 192.168.193.129