Skip to content

Instantly share code, notes, and snippets.

@Zeex
Created November 3, 2012 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Zeex/4007371 to your computer and use it in GitHub Desktop.
Save Zeex/4007371 to your computer and use it in GitHub Desktop.
#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#define HOST "vortex.labs.overthewire.org"
#define PORT "5842"
int main() {
int error;
struct addrinfo hints;
struct addrinfo *ai, *aiptr;
char addrstr[INET_ADDRSTRLEN];
int fd;
uint32_t ints[4];
int i;
uint32_t sum;
char buf[100];
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
if ((error = getaddrinfo(HOST, PORT, &hints, &ai)) < 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(error));
goto getaddrinfo_failed;
}
for (aiptr = ai; aiptr != NULL; aiptr = aiptr->ai_next) {
if ((fd = socket(ai->ai_family, ai->ai_socktype,
ai->ai_protocol)) >= 0)
break;
}
if (fd < 0) {
fprintf(stderr, "socket: %s\n", strerror(errno));
goto socket_failed;
}
if (connect(fd, ai->ai_addr, ai->ai_addrlen) < 0) {
fprintf(stderr, "connect: %s\n", strerror(errno));
goto exit;
}
if (inet_ntop(ai->ai_family, ai->ai_addr, addrstr,
sizeof(addrstr)) != NULL)
printf("Connected to "HOST" (%s) at port "PORT"\n", addrstr);
for (i = 0; i < 4; i++) {
if (recv(fd, &ints[i], sizeof(*ints), 0) < 0) {
fprintf(stderr, "recv: %s\n", strerror(errno));
goto exit;
}
}
sum = 0;
for (i = 0; i < 4; i++)
sum += ints[i];
if (send(fd, &sum, sizeof(sum), 0) < 0) {
fprintf(stderr, "send: %s\n", strerror(errno));
goto exit;
}
memset(buf, 0, sizeof(buf));
if (recv(fd, buf, sizeof(buf), 0) < 0) {
goto exit;
}
printf("%s\n", buf);
exit:
close(fd);
freeaddrinfo(ai);
return 0;
socket_failed:
freeaddrinfo(ai);
getaddrinfo_failed:
exit(EXIT_FAILURE);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment