Created
August 3, 2025 04:25
-
-
Save jmcph4/59e653222a07cab511479ce2134ea51d to your computer and use it in GitHub Desktop.
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 <netdb.h> | |
| int main(int argc, char** argv) { | |
| if (argc != 3) { /* usage */ | |
| fprintf(stderr, "rawip hostname port\n"); | |
| return EXIT_FAILURE; | |
| } | |
| const char* server_hostname = argv[1]; | |
| const char* server_port = argv[2]; | |
| struct addrinfo* addrs = NULL; | |
| struct addrinfo hints; | |
| memset(&hints, 0, sizeof(struct addrinfo)); | |
| hints.ai_family = AF_UNSPEC; | |
| hints.ai_socktype = SOCK_STREAM; | |
| hints.ai_flags = AI_PASSIVE; | |
| int gai_res = getaddrinfo(server_hostname, server_port, &hints, &addrs); | |
| if (gai_res != 0) { | |
| fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_res)); | |
| return EXIT_FAILURE; | |
| } | |
| if (addrs == NULL) { | |
| fprintf(stderr, "No available host interfaces\n"); | |
| return EXIT_FAILURE; | |
| } | |
| int sockfd = socket( | |
| addrs[0].ai_family, | |
| addrs[0].ai_socktype, | |
| addrs[0].ai_protocol | |
| ); | |
| if (sockfd == -1) { | |
| perror("socket"); | |
| freeaddrinfo(addrs); | |
| return EXIT_FAILURE; | |
| } | |
| int conn_res = connect(sockfd, addrs[0].ai_addr, addrs[0].ai_addrlen); | |
| if (conn_res == -1) { | |
| perror("connect"); | |
| freeaddrinfo(addrs); | |
| return EXIT_FAILURE; | |
| } | |
| const char* msg = "Hello, world!"; | |
| size_t msglen = strlen(msg) + 1; | |
| int bytes_sent = send(sockfd, msg, msglen, 0); | |
| uint8_t* resp = calloc(1024, sizeof(uint8_t)); | |
| size_t resplen = 1024; | |
| int bytes_received = recv(sockfd, resp, resplen, 0); | |
| printf("%s\n", resp); | |
| freeaddrinfo(addrs); | |
| free(resp); | |
| return EXIT_SUCCESS; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment