qfedu-network-advanced-level/day2/homework/h2.c

71 lines
2.1 KiB
C
Raw Normal View History

// 编写一个UDP服务器程序接收客户端发送的字符串并将其转换为大写后发送回客户端。
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <ctype.h> // toupper
int main(int argc, char const *argv[])
{
int sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0)
{
perror("socket");
return -1;
}
struct sockaddr_in addr;
bzero(&addr, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons(8000);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) != 0)
{
perror("bind");
}
else
{
printf("bind success\n");
struct sockaddr_in src_addr;
char buf[128] = ""; // 接收数据的空间
socklen_t socklen = sizeof(src_addr);
while (1)
{
bzero(&src_addr, sizeof(src_addr));
bzero(buf, 128);
// 接收数据,如果数据未到达,则会阻塞,直到数据到达为止
ssize_t len = recvfrom(sock_fd, buf, sizeof(buf), 0, (struct sockaddr *)&src_addr, &socklen);
if (len < 0)
{
perror("recvfrom");
break;
}
char srcIP[INET_ADDRSTRLEN]; // 16
int port = ntohs(src_addr.sin_port); // 将网络字节序转化为本地字节序
inet_ntop(AF_INET, &src_addr.sin_addr.s_addr, srcIP, INET_ADDRSTRLEN); // 将网络数字转换为点分十进制 ip
printf("从 %s:%d 位置接收到的数据(%lu Bytes): %s\n", srcIP, port, len, buf);
int i = 0;
while (buf[i])
{
buf[i] = toupper(buf[i]); // 转大写
i++;
}
sendto(sock_fd, buf, len, 0, (struct sockaddr *)&src_addr, socklen);
printf("发送回去的消息为 %s\n", buf);
}
}
close(sock_fd);
return 0;
}