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

43 lines
956 B
C

// a->客户端
#include <stdio.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
int main(int argc, char const *argv[])
{
int a_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (a_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 = 0;
scanf("%d", &n);
sendto(a_fd, &n, sizeof(n), 0, (struct sockaddr *)&addr, sizeof(addr));
char recvbuf[128] = "";
socklen_t addr_len = sizeof(addr);
recvfrom(a_fd, recvbuf, strlen(recvbuf), 0, (struct sockaddr *)&addr, &addr_len);
printf("%s", recvbuf);
if (strncmp(recvbuf, "bye", 3) == 0)
break;
}
close(a_fd);
return 0;
}