C中的UDP套接字

编程入门 行业动态 更新时间:2024-10-27 19:20:48
本文介绍了C中的UDP套接字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在处理课堂作业问题.我想启动一个侦听文件请求的 UDP 服务器.它打开文件并使用 UDP 将其发送回请求客户端.

I'm working on a homework problem for class. I want to start a UDP Server that listens for a file request. It opens the file and sends it back to the requesting client with UDP.

这是服务器代码.

// Create UDP Socket if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) { perror("Can't create socket"); exit(-1); } // Configure socket memset(&server, 0, sizeof server); server.sin_family = AF_INET; // Use IPv4 server.sin_addr.s_addr = htonl(INADDR_ANY); // My IP server.sin_port = htons(atoi(argv[1])); // Server Port // Bind socket if ((bind(sockfd, (struct sockaddr *) &server, sizeof(server))) == -1) { close(sockfd); perror("Can't bind"); } printf("listener: waiting to recvfrom... "); if (listen(sockfd, 5) == -1) { perror("Can't listen for connections"); exit(-1); } while (1) { client_len = sizeof(struct sockaddr_in); newsockfd = accept(sockfd, (struct sockaddr*)&client,&client_len); if (newsockfd < 0) { perror("ERROR on accept"); } // Some how parse request // I do I use recv or recvfrom? // I do I make new UDP socket to send data back to client? sendFile(newsockfd, filename); close(newsockfd); } close(sockfd);

我有点迷路了如何从客户端接收数据?以及如何与客户端建立新的 UDP 连接?

I'm kind of lost how do I recv data from the client? And how to I make a new UDP connection back to the client?

推荐答案

我用C写了一个UDP server-client,客户端发送一个注册号,服务器给出一个名字作为反馈.

I have written a UDP server-client in C , where the client sends a registration number and the server gives a name as the feedback.

服务器

0. Variable initialization 1. sock() 2. bind() 3. recvfrom() 4. sendto()

客户

0. gethostbyname() 1. sock() 2. bzero() 4. sendto() 5. recvfrom()

希望对您有所帮助.您可以在此处找到示例代码 udp server/client

Hope it helps. You can find the example code here udp server/client

更多推荐

C中的UDP套接字

本文发布于:2023-11-15 13:21:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1594803.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:UDP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!