UDP(用户数据报协议)是一种无连接的传输层协议,常用于需要快速传输数据但对可靠性要求不高的场景。
UDP服务器端:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 1024 int main() { int server_sock; char message[BUF_SIZE]; int str_len; socklen_t client_addr_size; struct sockaddr_in server_addr, client_addr; server_sock = socket(PF_INET, SOCK_DGRAM, 0); if (server_sock == 1) { perror("socket() error"); exit(1); } memset(&server_addr, 0, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(12345); if (bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 1) { perror("bind() error"); exit(1); } while (1) { client_addr_size = sizeof(client_addr); str_len = recvfrom(server_sock, message, BUF_SIZE, 0, (struct sockaddr *)&client_addr, &client_addr_size); sendto(server_sock, message, str_len, 0, (struct sockaddr *)&client_addr, client_addr_size); } close(server_sock); return 0; }
UDP客户端:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/socket.h> #define BUF_SIZE 1024 int main() { int client_sock; char message[BUF_SIZE]; int str_len; socklen_t server_addr_size; struct sockaddr_in server_addr, client_addr; client_sock = socket(PF_INET, SOCK_DGRAM, 0); if (client_sock == 1) { perror("socket() error"); exit(1); } memset(&client_addr, 0, sizeof(client_addr)); client_addr.sin_family = AF_INET; client_addr.sin_addr.s_addr = htonl(INADDR_ANY); client_addr.sin_port = htons(0); if (bind(client_sock, (struct sockaddr *)&client_addr, sizeof(client_addr)) == 1) { perror("bind() error"); exit(1); } server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); server_addr.sin_port = htons(12345); while (1) { fputs("Input message(Q to quit): ", stdout); fgets(message, BUF_SIZE, stdin); if (!strcmp(message, "q ") || !strcmp(message, "Q ")) { break; } sendto(client_sock, message, strlen(message), 0, (struct sockaddr *)&server_addr, sizeof(server_addr)); server_addr_size = sizeof(server_addr); str_len = recvfrom(client_sock, message, BUF_SIZE, 0, (struct sockaddr *)&server_addr, &server_addr_size); message[str_len] = 0; printf("Message from server: %s", message); } close(client_sock); return 0; }
这个示例中,服务器端使用UDP协议接收客户端发送的消息,然后将收到的消息原样返回给客户端,客户端从用户输入读取消息并发送给服务器,然后接收服务器返回的消息并打印出来。
各位小伙伴们,我刚刚为大家分享了有关c 源码 udp的知识,希望对你们有所帮助。如果您还有其他相关问题需要解决,欢迎随时提出哦!
原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/1104851.html
本网站发布或转载的文章及图片均来自网络,其原创性以及文中表达的观点和判断不代表本网站。如有问题,请联系客服处理。
发表回复