[Linux Programming] Echo(Based on UDP Multicast)

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

const char* MULTICAST_IP = "224.0.1.1";
const unsigned short MULTICAST_PORT = 1234;
const unsigned int MAX_LINE = 1024;

void* multicast_recv(void*);

int main() {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 

    struct sockaddr_in multicast_addr;
    bzero(&multicast_addr, sizeof(multicast_addr));
    multicast_addr.sin_family = AF_INET;
    multicast_addr.sin_addr.s_addr = inet_addr(MULTICAST_IP);
    multicast_addr.sin_port = htons(MULTICAST_PORT);
    size_t addr_len = sizeof(sockaddr_in);

    pthread_t tid;
    pthread_create(&tid, NULL, multicast_recv, &sockfd);

    char msg[MAX_LINE];
    while(fgets(msg, MAX_LINE, stdin)) {
        sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr*)&multicast_addr, addr_len);
    }

    return 0;
}

void *multicast_recv(void* fd_addr)
{
    int sockfd = *((int*)fd_addr);

    struct sockaddr_in c_addr;
    bzero(&c_addr, sizeof(sockaddr_in));
    socklen_t c_addr_len = sizeof(sockaddr_in);
    while(1)
    {
        char msg[MAX_LINE];
        int n = recvfrom(sockfd, msg, MAX_LINE, 0, (struct sockaddr*)&c_addr, &c_addr_len);
        write(2, msg, n);
    }

    return NULL;
}
// multicast group
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdio.h>

const char* MULTICAST_IP = "224.0.1.1";
const unsigned short MULTICAST_PORT = 1234;
const unsigned int MAX_LINE = 1024;

int main() {
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0); 

    struct sockaddr_in svr_addr;
    bzero(&svr_addr, sizeof(sockaddr_in));
    svr_addr.sin_family = AF_INET;
    svr_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    svr_addr.sin_port = htons(MULTICAST_PORT);
    size_t addr_len = sizeof(sockaddr_in);

    bind(sockfd,(struct sockaddr *)&svr_addr, addr_len);

    struct ip_mreq mreq;
    mreq.imr_multiaddr.s_addr = inet_addr(MULTICAST_IP);
    mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq));

    struct sockaddr_in c_addr;
    bzero(&c_addr, sizeof(sockaddr_in));
    socklen_t c_addr_len = sizeof(sockaddr_in);
    while(1) {
        char msg_recv[MAX_LINE];
        int len = recvfrom(sockfd, msg_recv, MAX_LINE, 0, (struct sockaddr*)&c_addr, &c_addr_len);
        write(2, msg_recv, len);
        sendto(sockfd, msg_recv, len, 0, (struct sockaddr*)&c_addr, c_addr_len);
    }

    return 0;
}

发表评论

电子邮件地址不会被公开。必填项已用 * 标注