// b->服务端 #include #include #include #include #include #include #include int main(int argc, char const *argv[]) { int b_fd = socket(AF_INET, SOCK_DGRAM, 0); if (b_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); // 接收所有本地ip下同一网段的客户端消息 // addr.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(b_fd, (struct sockaddr *)&addr, sizeof(addr)); while (1) { struct sockaddr_in src_addr; bzero(&src_addr, sizeof(src_addr)); socklen_t src_addr_len = sizeof(src_addr); int n; socklen_t addr_len = sizeof(addr); recvfrom(b_fd, &n, sizeof(n), 0, (struct sockaddr *)&src_addr, &src_addr_len); printf("%d", n); char sendbuf[128] = ""; if (n == 1) strcpy(sendbuf, "disen666"); else if (n == 2) strcpy(sendbuf, "jack good"); else if (n == 3) strcpy(sendbuf, "disen888"); else if (n == 4) strcpy(sendbuf, "bye"); sendto(b_fd, sendbuf, strlen(sendbuf), 0, (struct sockaddr *)&src_addr, src_addr_len); } close(b_fd); return 0; }