Chinaunix首页 | 论坛 | 博客
  • 博客访问: 588597
  • 博文数量: 141
  • 博客积分: 3425
  • 博客等级: 中校
  • 技术积分: 1609
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-23 15:55
文章分类

全部博文(141)

文章存档

2019年(5)

2011年(19)

2010年(36)

2009年(13)

2008年(50)

2007年(18)

分类: C/C++

2010-10-20 14:15:07

//监听端口

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);
}


阅读(3590) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~