QQ登录

只需一步,快速开始

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 1199|回复: 1

UDP的socket绑定到IP地址后无法接受广播数据

[复制链接]
发表于 2005-11-10 18:37:24 | 显示全部楼层 |阅读模式
由于考虑到我的程序要在多网卡的机器上运行,所以我将网卡的ip地址绑定到了socket
server_addr.sin_addr.s_addr = inet_addr(servIP);但是这样就无法收到广播数据?同时我也绑定到了一个广播地址接受时发现没次客户端来的数据都连续接受两次;请问是为什么?

以下是我的测试程序:

//server.cpp
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>

char * host_name = "192.168.0.255";
int port = 10051;

int main(void)
{
struct sockaddr_in serv_addr,addr;
char buf[256];

int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
perror("Error: socket";
return -1;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = inet_addr(host_name);//htonl(INADDR_ANY);//

int bd = bind(sockfd, (struct sockaddr*)&addr, sizeof(struct sockaddr_in));
while(1)
{
int len = sizeof(serv_addr);
memset(&serv_addr, 0, len);
int ret = recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&serv_addr,(socklen_t*)&len);
printf("recv=%d buf=%s
",ret, buf);
printf("RecvieIPs Recive Portd
", inet_ntoa(serv_addr.sin_addr),
ntohs(serv_addr.sin_port));
ret = sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&serv_addr,sizeof(struct sockaddr_in));
}

}


//client.cpp

#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <string.h>

char * host_name = "192.168.0.255";

int port = 10051;
int main(void)
{
int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == -1)
{
perror("Error: socket";
return -1;
}

struct sockaddr_in serv_addr;
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(port);
serv_addr.sin_addr.s_addr = inet_addr(host_name);
int so_broadcast;
setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &so_broadcast,
sizeof(so_broadcast));

char buf[256]="client .............";
sockaddr from ;
int len;
sendto(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&serv_addr,sizeof(struct sockaddr_in));
while(1)
{
recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr*)&serv_addr,(socklen_t*)&len);
printf("server buf= %s
",buf);
}
}
 楼主| 发表于 2005-11-11 12:11:52 | 显示全部楼层
没人知道吗?自己顶。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

GMT+8, 2024-11-3 04:24 , Processed in 0.039757 second(s), 15 queries .

© 2021 Powered by Discuz! X3.5.

快速回复 返回顶部 返回列表