此代码在ubuntu10.04系统上测试可正常使用。原来一直把发送地址填写成了多播地址,导致接收端可以抓到数据包但是程序无法接收到数据(多播程序写的太多,混淆了,哈哈)。
发送方代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
#define N 64
//#define BROADCAST_ADDR "192.168.121.255" //注意应该填写广播地址
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd, on = 1;
socklen_t addr_len;
char buf[N];
struct sockaddr_in peeraddr;
if (argc < 3)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
if (setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)) == -1)
{
perror("setsockopt fail");
exit(-1);
}
peeraddr.sin_family = PF_INET;
peeraddr.sin_port = htons(atoi(argv[2]));
peeraddr.sin_addr.s_addr = inet_addr(argv[1]);
strcpy(buf, "Hi! I am broadcast messgae\n");
while (1)
{
addr_len = sizeof(peeraddr);
sendto(sockfd, buf, N, 0, (SA *)&peeraddr, addr_len);
sleep(4);
}
return 0;
}
接收方代码如下:
#include
#include
#include
#include
#include
#include
#include
#define N 64
typedef struct sockaddr SA;
int main(int argc, char *argv[])
{
int sockfd;
socklen_t addr_len;
char buf[N];
struct sockaddr_in myaddr, peeraddr;
if (argc < 2)
{
printf("input format is : %s \n", argv[0]);
return -1;
}
if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("sock fail");
return -1;
}
myaddr.sin_family = PF_INET;
myaddr.sin_port = htons(atoi(argv[1]));
myaddr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (SA *)&myaddr, sizeof(myaddr)) == -1)
{
perror("bind fail");
return -1;
}
while (1)
{
addr_len = sizeof(peeraddr);
recvfrom(sockfd, buf, N, 0, (SA *)&peeraddr, &addr_len);
printf("recv from %s[%d]:%s\n", inet_ntoa(peeraddr.sin_addr),
ntohs(peeraddr.sin_port), buf);
}
return 0;
}
阅读(3759) | 评论(0) | 转发(1) |