UDP广播
程序员文章站
2022-06-29 18:25:05
...
1.服务器代码
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
int main()
{
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sockfd == -1)
{
printf("create socket failed.\n");
return -1;
}
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(9999);
if(bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{
printf("bind port error.\n");
return -1;
}
while(true)
{
char buf[1024] = {0};
struct sockaddr_in client;
socklen_t addrlen = sizeof(client);
int len = recvfrom(sockfd, buf, 1024, 0, (struct sockaddr*)&client, &addrlen);
if (len < 0)
{
printf("recvfrom() error\n");
break;
}
buf[len] = '\0';
printf("ip=%s, port=%d, from client=%s.\n", inet_ntoa(client.sin_addr), htons(client.sin_port), buf);
char msg[] = "this is server";
sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&client, addrlen);
}
close(sockfd);
return 0;
}
2.客户端代码
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>
int main(int argc, char *argv[])
{
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sockfd == -1)
{
printf("create socket failed.\n");
return -1;
}
const int opt = 1;
setsockopt(sockfd, SOL_SOCKET,SO_BROADCAST,(char*)&opt,sizeof(opt));
struct sockaddr_in server;
server.sin_family = AF_INET;
server.sin_port = htons(9999);
server.sin_addr.s_addr = INADDR_BROADCAST;
while(true)
{
char msg[] = "this is client";
sendto(sockfd, msg, strlen(msg), 0, (struct sockaddr *)&server, sizeof(server));
char buf[1024] = {0};
struct sockaddr_in peer;
socklen_t addrlen = sizeof(sockaddr_in);
int len = recvfrom(sockfd, buf, 1024, 0, (struct sockaddr*)&peer, &addrlen);
if(len < 0)
{
printf("recvfrom error\n");
break;
}
buf[len]='\0';
printf("ip=%s, port=%d, from server=%s.\n", inet_ntoa(peer.sin_addr), htons(peer.sin_port), buf);
sleep(3);
}
close(sockfd);
}
上一篇: UDP 广播
下一篇: Java实现UDP通信
推荐阅读
-
Linux UDP socket 设置为的非阻塞模式与阻塞模式区别
-
python列表生成式、键盘输入、字符串翻转、字母大小写、数组广播、循环语句等基础问题
-
python网络-Socket之udp编程(24)
-
第二十七章 网络通信协议、UDP通信、TCP通信
-
UNP卷1:第二十章(广播)
-
米聊突然更新:广播提醒增红点/气泡 小米钱包入驻
-
Android 入门第十讲02-广播(广播概述,使用方法(系统广播,自定义广播,两个activity之间的交互和传值),EventBus使用方法,数据传递,线程切换,Android的系统广播大全)
-
php socket通信tcp/udp实例分析
-
Java简单实现UDP和TCP的示例
-
浅谈java的TCP和UDP编程(附实例讲解)