Created
November 12, 2025 17:09
-
-
Save congwang-mk/e8e4febf3626065a63c941ac5be19027 to your computer and use it in GitHub Desktop.
Multikernel Vsock Test (Client)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <unistd.h> | |
| #include <errno.h> | |
| #include <sys/socket.h> | |
| #include <linux/vm_sockets.h> | |
| #define VSOCK_TRANSPORT_VM 0 | |
| #define VSOCK_TRANSPORT_MULTIKERNEL 1 | |
| #define SO_VM_SOCKETS_TRANSPORT 9 | |
| int main(int argc, char *argv[]) | |
| { | |
| int sock_fd; | |
| struct sockaddr_vm sa; | |
| int cid, port; | |
| int transport_type = VSOCK_TRANSPORT_MULTIKERNEL; | |
| char send_buf[256]; | |
| char recv_buf[256]; | |
| ssize_t n; | |
| if (argc < 3) { | |
| fprintf(stderr, "Usage: %s <instance_cid> <port>\n", argv[0]); | |
| fprintf(stderr, "Example: %s 0 9000 (connect to instance 0, port 9000)\n", argv[0]); | |
| return 1; | |
| } | |
| cid = atoi(argv[1]); | |
| port = atoi(argv[2]); | |
| printf("Connecting to multikernel instance %d, port %d\n", cid, port); | |
| /* Create vsock socket */ | |
| sock_fd = socket(AF_VSOCK, SOCK_STREAM, 0); | |
| if (sock_fd < 0) { | |
| perror("socket"); | |
| return 1; | |
| } | |
| /* Set transport to multikernel */ | |
| if (setsockopt(sock_fd, AF_VSOCK, SO_VM_SOCKETS_TRANSPORT, | |
| &transport_type, sizeof(transport_type)) < 0) { | |
| perror("setsockopt(SO_VM_SOCKETS_TRANSPORT)"); | |
| close(sock_fd); | |
| return 1; | |
| } | |
| printf("Transport set to MULTIKERNEL\n"); | |
| /* Connect to server */ | |
| memset(&sa, 0, sizeof(sa)); | |
| sa.svm_family = AF_VSOCK; | |
| sa.svm_cid = cid; | |
| sa.svm_port = port; | |
| if (connect(sock_fd, (struct sockaddr *)&sa, sizeof(sa)) < 0) { | |
| perror("connect"); | |
| close(sock_fd); | |
| return 1; | |
| } | |
| printf("Connected successfully!\n"); | |
| /* Interactive client */ | |
| printf("Enter messages (Ctrl-D to quit):\n"); | |
| while (fgets(send_buf, sizeof(send_buf), stdin) != NULL) { | |
| size_t len = strlen(send_buf); | |
| /* Send message */ | |
| if (send(sock_fd, send_buf, len, 0) != len) { | |
| perror("send"); | |
| break; | |
| } | |
| printf("Sent %zu bytes\n", len); | |
| /* Receive echo */ | |
| n = recv(sock_fd, recv_buf, sizeof(recv_buf), 0); | |
| if (n < 0) { | |
| perror("recv"); | |
| break; | |
| } | |
| if (n == 0) { | |
| printf("Server closed connection\n"); | |
| break; | |
| } | |
| printf("Received echo (%zd bytes): %.*s", n, (int)n, recv_buf); | |
| } | |
| close(sock_fd); | |
| printf("Connection closed\n"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment