Chinaunix首页 | 论坛 | 博客
  • 博客访问: 48366
  • 博文数量: 13
  • 博客积分: 563
  • 博客等级: 下士
  • 技术积分: 140
  • 用 户 组: 普通用户
  • 注册时间: 2009-08-18 14:45
文章存档

2014年(1)

2011年(2)

2010年(2)

2009年(8)

分类: LINUX

2009-09-06 17:21:12

向局域网发送广播:server.c

Int main()
{
Int sockfd;
Struct sockaddr_in server_addr, client_addr;
Int broadcast_en = 1;
Socklen_t broadcast_len = sizeof(broadcast_en);

Char buf[] = "good luck";


Bzero
(&server_addr, sizeof(server_addr));
Bzero
(&client_addr, sizeof(client_addr));


Server_addr
.sin_family = AF_INET;
Server_addr
.sin_port = htons(2222);
Server_addr
.sin_addr.s_add=inet_addr("192.168.220.255");


Sockfd
= socket(AF_INET, SOCK_DGRAM, 0);


Setsocketopt
(sockfd, SOL_SOCKET, SO_BROADCAST, &broadcast_en, broadcast_len);


Sendto(sockfd, buf, sizeof(buf), 0, (struct sockaddr *)&clinet_addr, sizeof(client_addr));


}

定义套接字,命名套接字,向ip段局域网中发送广播信息;
接受广播:client.c

Int main()
{
Int servfd;
Struct Sockaddr_in server_addr,client_addr;
Char buf[] = " ";


Int len = sizeof(server_addr)
Bzero
(&server_addr,sizeof(server_addr));
Bzero
(&client_addr, sizeof(client_addr));


Servfd
= socket(AF_INET, SOCK_DGRAM, 0 );
Server_addr
.sin_famliy = AF_INET;
Server_addr
.sin_port = htons(2222);//端口一定要一样
Server_addr
.sin_addr.s_addr = htonl(INADDR_ANY);


Blind
(server_addr, (struct sockaddr *)&server_addr, len);

Recvfrom(servfd, buf, 100, 0, (struct sockaddr *)&client_addr, sizeof(client_addr));


Printf("recv %s\n",buf);
Return 1;


}


定义套接字,绑定地址,命名套接字,收广播信息buf;
阅读(584) | 评论(0) | 转发(0) |
0

上一篇:知识点

下一篇:UDP类型的 client/server 实例

给主人留下些什么吧!~~