gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:40:29 25 4
gpt4 key购买 nike

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

我正在客户端和服务器之间进行通信。我知道udp是一个无连接程序,但它不会向客户端发送任何响应。如果我想将响应发送回客户端那么我应该做什么?我解决了上面链接中的所有错误,但我对向客户端发送响应有疑问。所以我在这里重新发帖。

最佳答案

这是我开始学习socket编程时写的代码,希望对你有帮助:

服务器

#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);
}

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

关于c - 是否可以从 udp 服务器向客户端发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22373859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com