Skip to content

Instantly share code, notes, and snippets.

@PeterWaIIace
Created July 4, 2020 18:42
Show Gist options
  • Save PeterWaIIace/1e9bcd2a0f69a9434b0ce372ef25a77d to your computer and use it in GitHub Desktop.
Save PeterWaIIace/1e9bcd2a0f69a9434b0ce372ef25a77d to your computer and use it in GitHub Desktop.
Simple template for tcp client socket in C for Linux. Based on https://www.youtube.com/watch?v=bdIiTxtMaKA
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <netdb.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#define PORT 80
#define BUFF_SIZE 4096
#define SOCK_ADDR struct sockaddr
int main(int argc, char **argv){
int sockfd, n,errcode;
int sendbytes;
struct sockaddr_in servaddr;
char sendline[BUFF_SIZE];
char readline[BUFF_SIZE];
// usage check
if(argc != 2)
return 0;
sockfd = socket(AF_INET,SOCK_STREAM,0);
bzero(&servaddr,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(PORT);
if(1 > (errcode = inet_pton(AF_INET,argv[1],&servaddr.sin_addr))){
printf("[%d] %s does not look like correct ip addr ",errcode,argv[1]);
return 0; // 1 - success, 0 - fail
}
if(0 > (errcode = connect(sockfd,&servaddr,sizeof(servaddr)))){
printf("[%d] Cannoc connect",errcode);
return 0; // 0 - success, -1 - fail
}
sprintf(sendline,"GET / HTTP/1.1.\r\n\r\n");
sendbytes = strlen(sendline);
if(0 >= (errcode = write(sockfd, sendline,sendbytes))){
printf("[%d] Cannot write to file descriptor",errcode);
return 0; // write returns number of zeros
}
memset(readline,0,BUFF_SIZE);
while((n = read(sockfd,readline,BUFF_SIZE))> 0 ){
printf("%s",readline);
};
if(n < 0) return 0;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment