欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

UDP广播

程序员文章站 2022-06-29 18:25:05
...

1.服务器代码

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sockfd == -1)
    {
        printf("create socket failed.\n");
        return -1;
    }

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(9999);
    if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        printf("bind port error.\n");
        return -1;
    }

    while(true)
    {
        char buf[1024] = {0};
        struct sockaddr_in client;
        socklen_t addrlen = sizeof(client);

        int len = recvfrom(sockfd, buf, 1024, 0, (struct sockaddr*)&client, &addrlen);
        if (len < 0)
        {
            printf("recvfrom() error\n");
            break;
        }

        buf[len] = '\0';
        printf("ip=%s, port=%d, from client=%s.\n", inet_ntoa(client.sin_addr), htons(client.sin_port), buf);

        char msg[] = "this is server";
        sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&client, addrlen);
    }

    close(sockfd);
    return 0;
}


2.客户端代码

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>

int main(int argc, char *argv[])
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if(sockfd == -1)
    {
        printf("create socket failed.\n");
        return -1;
    }

    const int opt = 1;
    setsockopt(sockfd, SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(9999);
    server.sin_addr.s_addr = INADDR_BROADCAST;

    while(true)
    {
        char msg[] = "this is client";
        sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&server, sizeof(server));

        char buf[1024] = {0};
        struct sockaddr_in peer;
        socklen_t  addrlen = sizeof(sockaddr_in);

        int len = recvfrom(sockfd, buf, 1024, 0, (struct sockaddr*)&peer, &addrlen);
        if(len < 0)
        {
            printf("recvfrom error\n");
            break;
        }

        buf[len]='\0';
        printf("ip=%s, port=%d, from server=%s.\n", inet_ntoa(peer.sin_addr), htons(peer.sin_port), buf);
        sleep(3);
    }

    close(sockfd);
}


上一篇: UDP 广播

下一篇: Java实现UDP通信