Last active
March 8, 2023 09:58
-
-
Save neur1n/c231fb81568d2ab01bc4bdb34c2784a9 to your computer and use it in GitHub Desktop.
Using readv in a loop
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 <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <unistd.h> | |
| #include <sys/uio.h> | |
| #define BUF_SIZE 1024 | |
| int main() { | |
| int sockfd; | |
| struct sockaddr_in serv_addr; | |
| struct iovec iov[2]; | |
| char header[10]; | |
| char body[100]; | |
| int header_bytes_received = 0; | |
| int body_bytes_received = 0; | |
| int bytes_received = 0; | |
| // Create a socket | |
| sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
| if (sockfd < 0) { | |
| perror("ERROR opening socket"); | |
| exit(1); | |
| } | |
| // Set up the server address | |
| memset(&serv_addr, 0, sizeof(serv_addr)); | |
| serv_addr.sin_family = AF_INET; | |
| serv_addr.sin_addr.s_addr = INADDR_ANY; | |
| serv_addr.sin_port = htons(1234); | |
| // Connect to the server | |
| if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { | |
| perror("ERROR connecting"); | |
| exit(1); | |
| } | |
| // Receive data from the server | |
| while (header_bytes_received < sizeof(header) || body_bytes_received < sizeof(body)) { | |
| iov[0].iov_base = header + header_bytes_received; | |
| iov[0].iov_len = sizeof(header) - header_bytes_received; | |
| iov[1].iov_base = body + body_bytes_received; | |
| iov[1].iov_len = sizeof(body) - body_bytes_received; | |
| bytes_received = readv(sockfd, iov, 2); | |
| if (bytes_received < 0) { | |
| perror("ERROR reading from socket"); | |
| exit(1); | |
| } else if (bytes_received == 0) { | |
| printf("Server closed connection\n"); | |
| break; | |
| } else { | |
| header_bytes_received += bytes_received < iov[0].iov_len ? bytes_received : iov[0].iov_len; | |
| body_bytes_received += bytes_received - header_bytes_received; | |
| } | |
| } | |
| printf("Received message from server:\nHeader: %s\nBody: %s\n", header, body); | |
| close(sockfd); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment