1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include "unp.h" //im assuming this has all the socket includes
int main(int argc, char *argv[]) {
if (argc != 2) {
err_quit("usage: a.out <server-ipv4-address>");
return 1;
}
int sockfd; //The file descriptor of socket() call
int n; //The number of bytes read from recv()
char recvline[MAXLINE + 1]; //The buffer where you'll be recieving messages to
addrinfo hints; //hints that the DNS service will use to find the host you're connecting to.
memset(&hints, 0, sizeof(hints)); //clear out hints
hints.ai_family = AF_INET; //IPV4 address
hints.ai_socktype = SOCK_STREAM; //The socket will be streaming data
hints.ai_protocol = IPPROTO_TCP; //The packets are guaranteed to reach their destination in order
addrinfo *result; //will be the results of a DNS request through getaddrinfo()
//http://linux.die.net/man/3/getaddrinfo
if (getaddrinfo(*argv[2], "13"/*port*/, &hints, &result) != 0) {
err_sys("Could not find server");
return 2;
}
sockfd = socket(hints.ai_family, hints.ai_socktype, 0);
if(sockfd == -1) { //unsuccessful
err_sys("socket() failed");
return 3;
}
int success = -1;
for (addrinfo *i = result; (i != nullptr) && (success != 0); i=i->ai_next)
connect( sockfd, (sockaddr*)result, sizeof(result) );
//connect to each returned address until you reach the end of the list or connect successfull
do {
n = recv(sockfd, recvline, MAXLINE, 0); //wait to recieve a message
recvline[n] = 0; /* null terminate */
fputs(recvline, stdout); //print the message to the screen
} while (n > 0)
if (n < 0)
err_sys("read error");
close(sockfd);
return 0;
}
|