C中的UDP套接字 [英] UDP Sockets in C

查看:22
本文介绍了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套接字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆