Linux UDP服務端和客戶端程序的實現
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 Socket */ server_sock_fd = socket(AF_INET, SOCK_DGRAM, 0); if (server_sock_fd < 0) { printf('服務端Socket創建失敗'); return -1; } printf('服務端Socket創建成功n'); /* 綁定ip和端口 */ 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) { /* 接收UDP客戶端的數據 */ printf('等待接收客戶端數據:n'); len = sizeof(client_addr); nbytes = recvfrom(server_sock_fd, recv_buf, 100, 0, (struct sockaddr *)&client_addr, &len); printf('okn'); 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; /* 創建Socket */ sock_fd = socket(AF_INET, SOCK_DGRAM, 0); if (sock_fd < 0) { printf('客戶端Socket創建失敗'); return -1; } /* 綁定ip和端口 */ 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);/* 接收UDP客戶端的數據 */ 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服務端和客戶端內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章:
