gpt4 book ai didi

C 服务器 - 打印收到的消息?

转载 作者:行者123 更新时间:2023-11-30 16:50:14 24 4
gpt4 key购买 nike

我使用 netcat 向此 C 服务器发送一条消息。

echo <message> | nc <ip> <port>

它打印:

Client IP : <ip>

我希望它也打印:

Client Message : <message>

C 服务器

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

char response[] = "hi";

int main()
{
int one = 1, client_fd;
struct sockaddr_in svr_addr, cli_addr;
socklen_t sin_len = sizeof(cli_addr);

int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0)
err(1, "can't open socket");

setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));

int port = 85;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);

if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
err(1, "Can't bind");
}

listen(sock, 5);
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
printf("Client IP : [%s]\n", inet_ntoa(cli_addr.sin_addr));

if (client_fd == -1) {
perror("Can't accept");
continue;
}

write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
close(client_fd);
}
}

最佳答案

您只需从套接字读取数据(在accept调用之后,一旦您检查client_fd可用):

if (client_fd == -1) {
perror("Can't accept");
continue;
}



printf("Client Message : <");

/* buffer to store result */
char buffer[64] = "";
/* while we can read from socket */
while (read(client_fd, buffer, sizeof buffer-1) > 0)
{
/* write what have been read */
printf("%s", buffer);
}
puts(">");



write(client_fd, response, sizeof(response) - 1); /*-1:'\0'*/
close(client_fd);

您还可以使用 recv功能。

关于C 服务器 - 打印收到的消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42270177/

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