#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#define SERV_PORT 8000
#define CLNT_PORT 9000
#define GROUP_IP "239.0.0.2"
int main()
{
struct sockaddr_in serv_addr, clnt_addr
int lfd, n
char buf[BUFSIZ]
struct ip_mreqn group
lfd = socket(AF_INET, SOCK_DGRAM, 0)
if(lfd >0){
printf("socket success\n")
}
bzero(&serv_addr, sizeof(serv_addr))
serv_addr.sin_family = AF_INET
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY)
serv_addr.sin_port = htons(SERV_PORT)
bind(lfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr))
inet_pton(AF_INET, GROUP_IP, &group.imr_multiaddr)//多播组IP地址
inet_pton(AF_INET, "0.0.0.0", &group.imr_address)//本地接口IP地址
group.imr_ifindex = if_nametoindex("eth0")
//赋予组播权限
setsockopt(lfd, IPPROTO_IP, IP_MULTICAST_IF, &group, sizeof(group))
bzero(&clnt_addr, sizeof(clnt_addr))
clnt_addr.sin_family = AF_INET
//clnt_addr.sin_addr.s_addr = htonl(GROUP_IP)
inet_pton(AF_INET, GROUP_IP, &clnt_addr.sin_addr.s_addr)
clnt_addr.sin_port = htons(CLNT_PORT)
int i = 1
while(1){
sprintf(buf, "hello multicast %d\n", i++)
n = sendto(lfd, buf, strlen(buf), 0, (struct sockaddr*)&clnt_addr, sizeof(clnt_addr))
sleep(1)
}
close(lfd)
return 0
}
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#define GROUP_IP "239.0.0.2"
#define CLNT_PORT 9000
int main()
{
struct sockaddr_in localaddr
int sockfd, n
char buf[BUFSIZ]
struct ip_mreqn group
sockfd = socket(AF_INET, SOCK_DGRAM, 0)
localaddr.sin_family = AF_INET
localaddr.sin_addr.s_addr = htonl(INADDR_ANY)
localaddr.sin_port = htons(CLNT_PORT)
bind(sockfd, (struct sockaddr*)&localaddr, sizeof(localaddr))
inet_pton(AF_INET, GROUP_IP, &group.imr_multiaddr)
inet_pton(AF_INET, "0.0.0.0", &group.imr_address)
group.imr_ifindex = if_nametoindex("etho0")
//加入组播
setsockopt(sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &group, sizeof(group))
while(1){
n = recvfrom(sockfd, buf, sizeof(buf), 0, NULL, 0)
if(n >0){
write(STDOUT_FILENO, buf, n)
}
}
close(sockfd)
return 0
}
缺失ws2_32.dll文件造成,解决步骤如下:
1、首先,在一定途径获取ws2_32.dll文件,例如搜索引擎查询并下载。
2、其次,将ws2_32.dll文件复制到DLL目录“C:\Windows\System32”下。
3、点击“开始菜单”,选择“运行”按钮,输入:regsvr32 ws2_32.dll,点击确定。
4、此时d出安装完成ws2_32.dll文件的提示,点击确定。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)