dhilst

Simple socket client

This sample application will connect to addres passed as first argument
and port passed as second argument. Then will send everything received from stdin
to that socket and send everything received as answer from socket to stdout. Simple!
Type quit to exit.

Is useful when you need to rember how to setup PF_INET sockects and when you need something simple
to talk with some socket.

Note: I have used `~' character as prompt.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <netdb.h>

#define pexit(s) ({perror(s); exit(EXIT_FAILURE);})

#define BUFLEN 0x400
static char buf[BUFLEN];

int main(int argc, char **argv)
{
int sock;
int addr_len;
int error;
struct sockaddr_in addr;
struct hostent *host;


if (argc <= 2) {
printf("Usage: %s address port\n", argv[0]);
exit(EXIT_FAILURE);
}

sock = socket(PF_INET, SOCK_STREAM, 0);
if (sock < 0)
pexit("socket");


host = gethostbyname(argv[1]);
if (!host)
pexit("gethostbyname");

memcpy(&addr.sin_addr.s_addr, host->h_addr_list[0], sizeof(struct
sockaddr_in));
addr.sin_family = PF_INET;
addr.sin_port = htons(atoi(argv[2]));

error = connect(sock, (struct sockaddr *)&addr, sizeof addr);
if (error)
pexit("connect");

for (;;) {
printf("~ "); /* my prompt */
fgets(buf, BUFLEN, stdin);
if (!strcmp(buf, "quit\n"))
break;

error = send(sock, buf, strnlen(buf, BUFLEN), 0);
if (error == -1) /* error */
pexit("send");

error = recv(sock, buf, BUFLEN, 0);
if (error == -1)
pexit("recv");

printf(buf);
}

close(sock);
return 0;
}

Testing: