Skip to content

Instantly share code, notes, and snippets.

@sayyidyofa
Created August 28, 2020 15:15
Show Gist options
  • Save sayyidyofa/2882402608fd46480266d66f5c334b40 to your computer and use it in GitHub Desktop.
Save sayyidyofa/2882402608fd46480266d66f5c334b40 to your computer and use it in GitHub Desktop.
Quick and dirty rewritten code from daytimetcpcli.c
#include <stdio.h>
#include <strings.h>
#include <unistd.h>
#include <memory.h>
#include "/usr/include/netinet/in.h"
#include "/usr/include/arpa/inet.h"
#define MAXLINE 4096
int main(int argc, char **argv) {
int sockfd, n;
char recvline[MAXLINE + 1];
struct sockaddr_in servaddr;
if (argc != 2) {
printf("usage: a.out <IPaddress>");
return -1;
}
if ( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
printf("socket error");
return -1;
}
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(13); /* daytime server */
if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
printf("inet_pton error for %s", argv[1]);
return -1;
}
// clear contents on sin_zero manually
// https://silviocesare.wordpress.com/2007/10/22/setting-sin_zero-to-0-in-struct-sockaddr_in/
memset(&servaddr.sin_zero, 0, sizeof(servaddr.sin_zero));
if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
printf("connect error");
return -1;
}
while ( (n = read(sockfd, recvline, MAXLINE)) > 0) {
recvline[n] = 0; /* null terminate */
if (fputs(recvline, stdout) == EOF) {
printf("fputs error");
return -1;
}
}
if (n < 0) {
printf("read error");
return -1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment