qfedu-network-advanced-level/day5/weak_task/da.c

58 lines
1.4 KiB
C
Raw Normal View History

// a->客户端
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.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 = inet_addr("127.0.0.1"); // 指定服务器地址
while (1)
{
// 创建发送的数据
int n = 5;
printf("请输入内容:\n");
scanf("%d", &n);
// 发送 udp 数据
ssize_t sendnum = sendto(sock_fd, &n, sizeof(n), 0, (struct sockaddr *)&addr, sizeof(addr)); // 将 buf 数据发送给服务器
if (sendnum > 0)
{
perror("发送成功\n");
}
socklen_t addrlen = sizeof(addr);
char recvbuf[128] = "";
ssize_t recvlen = recvfrom(sock_fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&addr, &addrlen); // 从服务器获取数据到 buf
if (recvlen < 0)
{
perror("recvfrom");
return 1;
}
printf("从服务器获取内容为 %s\n", recvbuf);
if (strncmp(recvbuf, "bye", 3) == 0)
break;
}
close(sock_fd);
return 0;
}