当前位置 : 首页 » 博文聚焦 » 正文

简单的广播收发

分类 : 博文聚焦 | 发布时间 : 2014-04-03 20:37:59 | 浏览 : 263
向局域网发送广播: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;
阅读(229) | 评论(0) | 转发(0) |
0

上一篇:知识点

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

给主人留下些什么吧!~~
评论热议

相关阅读:

What's a .sh file?

How to measure actual memory usage of an application or process?

Is there any WinSCP equivalent for linux?

How to copy a file from remote server to local machine?

Testing IO performance in Linux

How do I copy folder with files to another folder in Unix/Linux?

How can I recursively find all files in current and subfolders based on wildcard matching?

How to symlink a file in Linux?

Error: Could not find or load main class

How do I grep recursively?