64 lines
1.9 KiB
C
64 lines
1.9 KiB
C
// 编写一个UDP服务器程序, 接收客户端发送的整数, 计算其平方并发送回客户端
|
|
#include <stdio.h>
|
|
#include <arpa/inet.h>
|
|
#include <netinet/in.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
#include <sys/socket.h>
|
|
|
|
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;
|
|
int n = 0; // 接收数的空间
|
|
socklen_t socklen = sizeof(src_addr);
|
|
while (1)
|
|
{
|
|
bzero(&src_addr, sizeof(src_addr));
|
|
|
|
// 接收数据,如果数据未到达,则会阻塞,直到数据到达为止
|
|
ssize_t len = recvfrom(sock_fd, &n, sizeof(n), 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): %d\n", srcIP, port, len, n);
|
|
|
|
int n_to_square = n * n;
|
|
|
|
sendto(sock_fd, &n_to_square, len, 0, (struct sockaddr *)&src_addr, socklen);
|
|
printf("发送回去的平方值为 %d\n", n_to_square);
|
|
}
|
|
}
|
|
|
|
close(sock_fd);
|
|
|
|
return 0;
|
|
}
|