Linux UDP服务端和客户端程序的实现

时间:2021-05-20

1. 源码

UDP服务端:

/** * @brief UDP服务端 * @author Mculover666 * @date 2020/04/15*/#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <stdlib.h>#include <string.h>int main(int argc, char* argv[]){ int server_sock_fd; struct sockaddr_in server_addr, client_addr; char recv_buf[100]; int nbytes = 0; socklen_t len = 0; server_sock_fd = socket(AF_INET, SOCK_DGRAM, 0); if (server_sock_fd < 0) { printf("服务端Socket创建失败"); return -1; } printf("服务端Socket创建成功\n"); bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(atoi(argv[1]));//指定端口号 bind(server_sock_fd, (struct sockaddr *) &server_addr, sizeof(server_addr)); printf("服务端Socket绑定成功\n"); while(1) { printf("等待接收客户端数据:\n"); len = sizeof(client_addr); nbytes = recvfrom(server_sock_fd, recv_buf, 100, 0, (struct sockaddr *)&client_addr, &len); printf("ok\n"); recv_buf[nbytes] = '\0'; printf("recv %d bytes:%s.\n", nbytes, recv_buf); //接收用户输入,发送给客户端 printf("请输入要发送给客户端的数据:"); fgets(recv_buf, 100, stdin); sendto(server_sock_fd,recv_buf,strlen(recv_buf),0,(struct sockaddr *)&client_addr,len); } return 0;}

UDP客户端:

/** * @brief UDP客户端程序 * @author Mculover666 * @date 2020/04/15*/#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <stdlib.h>#include <string.h>int main(int argc, char* argv[]){ int sock_fd; struct sockaddr_in server_addr; char recv_buf[100]; int nbytes = 0; socklen_t len = 0; sock_fd = socket(AF_INET, SOCK_DGRAM, 0); if (sock_fd < 0) { printf("客户端Socket创建失败"); return -1; } bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(argv[1]); server_addr.sin_port = htons(atoi(argv[2]));//指定端口号 while(1) { len = sizeof(server_addr); //接收用户输入,发送给服务端 printf("请输入要发送给服务端的数据:"); fgets(recv_buf, 100, stdin); sendto(sock_fd,recv_buf,100,0,(struct sockaddr *)(&server_addr),len); len = sizeof(server_addr); nbytes = recvfrom(sock_fd, recv_buf, 100, 0, (struct sockaddr *)&server_addr, &len); recv_buf[nbytes] = '\0'; printf("recv %d bytes:%s.\n", nbytes, recv_buf); } return 0;}

2. 在本机运行结果

编译:

gcc server.c -o srever_wangshiwei.ogcc client.c -o client_wangshiwei.o

运行:


3. 在开发板与PC之间运行结果

编译:

gcc server.c -o srever_wangshiwei.oarm-linux-gnueabi-gcc client.c -o clientARM_wangshiwei.o


到此这篇关于Linux UDP服务端和客户端程序的实现的文章就介绍到这了,更多相关Linux UDP服务端和客户端内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章