// a->客户端 #include #include #include #include #include #include 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) { char buf[1] = ""; bzero(&buf, sizeof(buf)); scanf("%s", buf); sendto(a_fd, buf, strlen(buf), 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; }