socket广播

setsockopt设置socket广播选项

例:

发送广播报文代码如下:

mysendto.c

#include <sys/types.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
    if(3 > argc) {
        fprintf(stderr, "Usage: %s <ipaddr> <port>\n", argv[0]);
        exit(1);
    }
    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sock_fd) {
        perror("create socket");    
        exit(2);
    }
    
    struct sockaddr_in to;
    to.sin_family = AF_INET;
    to.sin_port = htons(atoi(argv[2]));
    to.sin_addr.s_addr = inet_addr(argv[1]);
    
    int broad_flag = 1;    
    setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, &broad_flag, sizeof(int));

    char *str = "hello world.";
    if(argc >= 4) {
        str = argv[3];
    }

/*
    int normal_fd;
    if(-1 == (normal = open(argv[3],RD_ONLY)))
    {
        perror("open()");
        exit(3);
    }
*/
    int packet_num = 0;
    while(1) {
        int ret = sendto(sock_fd, str, strlen(str)+1, 0, (struct sockaddr*)&to,sizeof(struct sockaddr_in));
        if(-1 == ret) {
            perror("sendto");
            exit(2);
        }
        printf("broad %d packets.\n", ++packet_num);

        sleep(1);
    }

    close(sock_fd);    
}

接收报文代码如下:

myrecvfrom.c

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

#define PORT_NUM 12345

/*
 *recv data and dump to dsp
 */

int main(int argc, char *argv[])
{
    char buf[1024];
    struct sockaddr_in sendaddr;
    int recv_len = sizeof(struct sockaddr_in);

    struct sockaddr_in myaddr;
    myaddr.sin_family = AF_INET;
    myaddr.sin_port = htons(PORT_NUM);
    myaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(-1 == sock_fd) {
        perror("create socket");    
        exit(2);
    }

    int ret = bind(sock_fd, (struct sockaddr *)&myaddr, sizeof(struct sockaddr_in));
    if(-1 == ret) {
        perror("bind");
        exit(3);
    }
    while(1) {
      ret = recvfrom(sock_fd, buf, sizeof(buf), 0, 
              (struct sockaddr*)&sendaddr, &recv_len);
      if(-1 == ret) {
          perror("recv");
          exit(4);
      }

      printf("recv data from address: %s data: %s\n", 
          inet_ntoa(sendaddr.sin_addr), buf);
    }
    close(sock_fd);    
}

编译链接后, 在两个终端分别运行输出如下:

socket广播_第1张图片

上图第二次运行" ./mysendto 192.168.1.255 12345 abcdefg"输出"sendto Permission denied", 是在屏蔽"

setsockopt(sock_fd, SOL_SOCKET, SO_BROADCAST, &broad_flag, sizeof(int));

"后运行的结果

socket广播_第2张图片

 

你可能感兴趣的:(socket广播)