是否可以从udp服务器向客户端发送响应?

时间:2014-03-13 09:13:19

标签: c linux windows udp embedded-linux

我在此处发布了我的代码:communication between windows client and linux server?

我在客户端和服务器之间进行通信。我知道udp是一个无连接程序,但它不会将任何响应发送回客户端。如果我想将响应发送回客户端那么我该怎么办? 我解决了上述链接中的所有错误,但我怀疑w.r.t将响应发送回客户端。所以我在这里发帖。

1 个答案:

答案 0 :(得分:0)

这是我开始学习套接字编程时编写的代码,希望它有所帮助:

服务器

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>


int main(int argc, char *argv[])
{
    struct sockaddr_in server;
    struct sockaddr_in client;
    int socket_fd;
    int ret;
    char buf[255];
    int len = sizeof(struct sockaddr_in);

    socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_fd < 0)
    {
        printf("socket error\n");
        return -1;
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(5900);
    server.sin_addr.s_addr = htonl(INADDR_ANY);

    ret = bind(socket_fd, (struct sockaddr *)&server, sizeof(struct sockaddr));
    if(ret)
    {
        printf("error while binding\n");
        return -1;
    }

    ret = recvfrom(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, &len);

    if(ret < 0)
    {
        printf("reciving error\n");
    }

    printf("recving data from %s: %s\n", inet_ntoa(client.sin_addr), buf);

    snprintf(buf, sizeof(buf), "server:");
    ret = sendto(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&client, sizeof(client));

    if(ret < 0)
    {
        printf("send error\n");
        return -1;
    }

    close(socket_fd);

    return 0;
}

<强>客户端

#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
    int socket_fd;
    struct sockaddr_in server;
    int ret;
    char buf[255] = "send to server";
    int len = sizeof(struct sockaddr_in);

    socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if(socket_fd < 0)
    {
        printf("socket error\n");  
    }

    server.sin_family = AF_INET;
    server.sin_port = htons(5900);
    server.sin_addr.s_addr = inet_addr("127.0.0.1");

    ret = sendto(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&server, sizeof(server));

    if(ret < 0)
    {
        printf("sendto error\n");
        return -1;
    }

    ret = recvfrom(socket_fd, buf, sizeof(buf), 0, (struct sockaddr *)&server, &len); 
    if(ret < 0)
    {
        printf("error recv from\n");
        return -1;
    }
    printf("recving from server:%s: %s\n", inet_ntoa(server.sin_addr), buf);

    close(socket_fd);
}

阅读上面的代码,您会找到问题的答案