Linux Client Socket

This piece of code will connect to the specified host (example: towel.blinkenlights.nl) on the specified port (example: 23) and print any data it receives line by line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

void die(char *errmsg);
int recvl(int sock, char *buf);
const char *nametoip(char *host);
char *iptoname(char *ip);
int connect(char *host,int port);

void help(char *fname) {
    printf("Usage: %s hostname port",fname);
    exit(1);
}

int main(int argc, char** argv) {
    if (argc<2) help(argv[0]);
    int sock,len=1;
    char buf[600];
    sock=connect(argv[1],atoi(argv[2]));
    while (len=recvl(sock,buf)) {
        write(1,buf,len);
    }
    close(sock);
    return 0;
}

int connect(char *host,int port) {
    int sock;
    struct sockaddr_in si;
    struct hostent *hostess_twinkies = gethostbyname(host);
    sock = socket(PF_INET, SOCK_STREAM, 0);
    si.sin_family = AF_INET;
    si.sin_port = htons(port);
    si.sin_addr = *((struct in_addr*)hostess_twinkies->h_addr);
    memset(&(si.sin_zero),'',8);
    if (connect(sock,(struct sockaddr*)&si,sizeof(struct sockaddr))==-1) sock=0;
    return sock;

}

void die(char *errmsg) {
    fprintf(STRERR,"%s",errmsg);
    exit(1);
}

const char *nametoip(const char *host) {
    char buf[256];
    return inet_ntop(AF_INET,gethostbyname(host)->h_name,buf,256);
}

char *iptoname(char *ip) {
    struct in_addr inp;
    inet_pton(AF_INET,ip,&inp);
    return gethostbyaddr(&inp,sizeof(in_addr),AF_INET)->h_name;
}

int recvl(int sock, char *buf) {
    int len=0;
    while (recv(sock,buf,1,0)) {
        len++;
        if (*buf=='\n') return len;
        buf++;
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: