socket 实现最小化UDP广播程序

广播是某一个终端给一个子网发送数据,这个子网可以是本地的最小化子网,比如 192.168.1.255,也可以是整个子网 255.255.255.255,这取决于你要发送的范围,本文中只介绍一个最小化的广播程序,值得注意的是,即使客户端没有设定IP地址,它依然是可以接收到广播数据的。


服务端代码

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>

#define SERVER_PORT 8000
#define CLIENT_PORT 9000
#define MAXLINE 1500
#define BROADCAST_IP "255.255.255.255"	// 广播地址

int main(void)
{
    int sockfd;
    struct sockaddr_in serveraddr, clientaddr;
    char buf[MAXLINE] = "mycode\n";

    /* 构造用于UDP通信的套接字 */
    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    bzero(&serveraddr, sizeof(serveraddr)); 
	/* IPv4 */
    serveraddr.sin_family = AF_INET;
	/* 本地任意IP INADDR_ANY = 0 */
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons(SERVER_PORT);
    bind(sockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr));

	// 设置socket为广播方式
    int flag = 1;
    setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag));

    /*构造 client 地址 IP+端口  192.168.12.255+9000 */
    bzero(&clientaddr, sizeof(clientaddr));
    clientaddr.sin_family = AF_INET;
    inet_pton(AF_INET, BROADCAST_IP, &clientaddr.sin_addr.s_addr);
    clientaddr.sin_port = htons(CLIENT_PORT);

    int i = 0;
    while (1) {
        sprintf(buf, "mycode %d\n", i++);
		// 发送数据
        sendto(sockfd, buf, strlen(buf), 0, 
				(struct sockaddr *)&clientaddr, sizeof(clientaddr));
        sleep(1);
    }
    close(sockfd);
    return 0;
}

客户端代码

#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <net/if.h>
#define SERVER_PORT 8000
#define MAXLINE 4096

#define CLIENT_PORT 9000
int main(int argc, char *argv[])
{
    struct sockaddr_in serveraddr, localaddr;
    int confd;
    ssize_t len;
    char buf[MAXLINE];

    //1.创建一个socket
    confd = socket(AF_INET, SOCK_DGRAM, 0);

    //2.初始化本地端地址
    bzero(&localaddr, sizeof(localaddr));
    localaddr.sin_family = AF_INET;
    inet_pton(AF_INET, "0.0.0.0" , &localaddr.sin_addr.s_addr);
    localaddr.sin_port = htons(CLIENT_PORT);

	// 广播客户端也要绑定固定的端口,否则接收不到
    bind(confd, (struct sockaddr *)&localaddr, sizeof(localaddr));

    socklen_t slen;
    while (1) {
        slen = sizeof(serveraddr);
        len = recvfrom(confd, buf, sizeof(buf), 0, (struct sockaddr *)&serveraddr, &slen);
        //printf("%s\n", inet_ntop(AF_INET, &serveraddr.sin_addr.s_addr, buf, sizeof(buf)));
        write(STDOUT_FILENO, buf, len);
    }
    close(confd);
    return 0;
}

编译

编译客户端:gcc boardcast_client.c -o boardcast_client

编译服务端:gcc boardcast_server.c -o boardcast_server

运行效果:

2015-07-18 21:35:10

发表评论