Last active
September 5, 2020 14:21
-
-
Save AlexanderOMara/26dd909dcef674c2109054720e09afaf to your computer and use it in GitHub Desktop.
A macOS connectx example
This file contains 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 <unistd.h> | |
#include <sys/socket.h> | |
#include <netinet/tcp.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#define HOST_NAME "icanhazip.com" | |
#define HOST_IP "136.144.56.255" | |
#define HOST_PORT 80 | |
int main(int argc, char **argv) { | |
int soc = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); | |
if (soc < 0) { | |
perror("ERROR: socket"); | |
return 1; | |
} | |
struct sockaddr_in addr; | |
addr.sin_family = AF_INET; | |
addr.sin_port = htons(HOST_PORT); | |
addr.sin_len = sizeof(addr); | |
inet_aton(HOST_IP, &addr.sin_addr); | |
sa_endpoints_t endpoints; | |
endpoints.sae_srcif = 0; | |
endpoints.sae_srcaddr = NULL; | |
endpoints.sae_srcaddrlen = 0; | |
endpoints.sae_dstaddr = (struct sockaddr *)&addr; | |
endpoints.sae_dstaddrlen = sizeof(addr); | |
int result; | |
result = connectx(soc, &endpoints, 0, 0, NULL, 0, NULL, NULL); | |
if (result < 0) { | |
perror("ERROR: connectx"); | |
close(soc); | |
return 1; | |
} | |
char req[] = | |
"GET / HTTP/1.1\r\n" | |
"Host: " HOST_NAME "\r\n" | |
"\r\n"; | |
result = write(soc, req, sizeof(req)); | |
if (result < 0) { | |
perror("ERROR: write"); | |
close(soc); | |
return 1; | |
} | |
char buf[1024]; | |
for (ssize_t size; (size = read(soc, buf, sizeof(buf)));) { | |
if (size < 0) { | |
perror("ERROR: read"); | |
close(soc); | |
return 1; | |
} | |
for (size_t i = 0; i < size; i++) { | |
printf("%c", buf[i]); | |
} | |
} | |
close(soc); | |
return 0; | |
} |
line 52 should read ssize_t size, because else the condition in line 53 will never be true
(alternatively you could also cast size to ssize_t on line 53)
Good call! Updated.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
line 52 should read ssize_t size, because else the condition in line 53 will never be true
(alternatively you could also cast size to ssize_t on line 53)