All pastes #186295 Raw Edit

vortex00

public c v1 · immutable
#186295 ·published 2006-09-29 19:25 UTC
rendered paste body
e/* tcp_connect.c Connects to [char *hostname] on port [int port] and returnsa socket descriptor. */#include <stdio.h>#include <sys/socket.h>#include <sys/types.h>#include <netdb.h>int tcp_connect(char *hostname, int port){  int sockfd;  struct sockaddr_in target;  struct hostent *h;  if((h = (struct hostent *) gethostbyname(hostname)) == 0){       perror("gethostbyname()");       return -1;  }  target.sin_family   = AF_INET;  target.sin_port     = htons(port);  target.sin_addr     = *((struct in_addr *)h->h_addr);  if((sockfd = socket(PF_INET, SOCK_STREAM, 0)) == -1){    perror("socket");    return -1;  }  if(connect(sockfd, (struct sockaddr *)&target, sizeof(struct sockaddr)) == -1){    perror("connect");    return -1;  }  return sockfd;}/*A Simple Programming ExerciseYour goal is to connect to port 5842 on vortex.labs.pulltheplug.org and read in 4 unsigned integers. Add these integers together and send back the results to get a username and password for level 1. Note that vortex is on an x86 machine (meaning, a little endian architecture). */#include <stdio.h>#include <stdlib.h>#define BUFSIZE 256int main(int argc, char **argv){  int sockfd, i, recv_n, sent_n;  unsigned int ui[4] = {0,0,0,0};  unsigned long sum = 0;  char answer[BUFSIZE];    if((sockfd = tcp_connect("vortex.labs.pulltheplug.org", 5842)) == -1){    exit(-1);  }    for(i = 0; i < 4; i++){    if((recv_n = recv(sockfd, ui[i], sizeof(unsigned int), 0)) == -1){      fprintf(stderr, "Error in receiving unsigned ints.\n");      exit(-1);    }  }    for(i = 0; i < 4; i++){    sum += ui[i];    fprintf(stdout, "Adding %u to sum: %u\n", ui[i], sum);  }    if((sent_n = send(sockfd, sum, sizeof(unsigned long), 0)) == -1){    perror("send");    exit(-1);  }    if((recv_n = recv(sockfd, answer, BUFSIZE, 0)) == -1){    perror("recv");    exit(-1);  }    fprintf(stdout, "%s\n", answer);}