|
由于考虑到我的程序要在多网卡的机器上运行,所以我将网卡的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);
}
} |
|