[置顶] linux网络编程之:多播

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

#define BUFLINE 256
int main(int argc, char *argv[]){
	struct sockaddr_in local;
	int fd, n;
	struct ip_mreq mc;
	char msg[BUFLINE + 1];
	if(argc != 3){
		printf("Usage: ip port\n");
		return 1;
	}

	fd = socket(AF_INET, SOCK_DGRAM, 0);
	if(fd == -1){
		perror("socket()");
		return 1;
	}

	memset(&local, 0, sizeof(local));
	local.sin_port = htons(atoi(argv[2]));
	local.sin_addr.s_addr = htonl(INADDR_ANY);

	if(inet_pton(AF_INET, "192.168.30.61", &mc.imr_interface) <= 0){//my ip
		perror("inet_pton");
		return 1;
	}

	if(inet_pton(AF_INET, argv[1], &mc.imr_multiaddr) <= 0){//multi addr
		perror("inet_pton()");
		return 1;
	}

	printf("ip: %s\n", inet_ntoa(mc.imr_multiaddr));
	fflush(stdout);
	if(setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mc, sizeof(mc)) < 0){
		perror("setsockopt");
		return 1;
	}

	if(bind(fd, (struct sockaddr*)&local, sizeof(local)) == -1){
		perror("bind");
		return 1;
	}
	n = read(fd, msg, BUFLINE);
	if(n < 0){
		fprintf(stderr, "read");
		return 1;
	}else{
		msg[n - 1] = 0;
		printf("%s\n", msg);
	}
	return 0;
}


运行:./mclient 224.0.4.5 123

224.0.4.5是组播地址。

你可能感兴趣的:(编程,linux,socket,struct,网络,interface)