Created
January 17, 2022 22:29
-
-
Save vinikira/55d7be9f125913ddd9f11af3c3345714 to your computer and use it in GitHub Desktop.
TCP socket consumption in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
set -xe | |
cc -Wall -Werror -std=c11 -pedantic -o main main.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <signal.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
#include <stdarg.h> | |
#include <errno.h> | |
#include <fcntl.h> | |
#include <sys/time.h> | |
#include <sys/ioctl.h> | |
#include <netdb.h> | |
#define SERVER_PORT 80 | |
#define MAXLINE 4096 | |
#define USE_TCP 0 | |
#define SA struct sockaddr | |
void err_n_die(const char *fmt, ...) { | |
int errno_save = errno; | |
va_list ap; | |
va_start(ap, fmt); | |
vfprintf(stderr, fmt, ap); | |
fprintf(stderr, "\n"); | |
fflush(stderr); | |
if (errno_save != 0) { | |
fprintf(stderr, "(errno = %d): %s\n", errno_save, strerror(errno_save)); | |
fprintf(stderr, "\n"); | |
fflush(stderr); | |
} | |
va_end(ap); | |
exit(1); | |
} | |
int main(int argc, char *argv[]) { | |
int sockfd; | |
int n; | |
int sendbytes; | |
struct sockaddr_in serveraddr; | |
char sendline[MAXLINE]; | |
char recvline[MAXLINE]; | |
if(argc != 2) { | |
err_n_die("usage: %s <server address>", argv[0]); | |
} | |
if ((sockfd = socket(AF_INET, SOCK_STREAM, USE_TCP)) < 0) { | |
err_n_die("Error while creating the socket!"); | |
} | |
bzero(&serveraddr, sizeof(serveraddr)); | |
serveraddr.sin_family = AF_INET; | |
serveraddr.sin_port = htons(SERVER_PORT); | |
if (inet_pton(AF_INET, argv[1], &serveraddr.sin_addr) <= 0) { | |
err_n_die("inet_pton error for %s", argv[1]); | |
} | |
if (connect(sockfd, (SA *) &serveraddr, sizeof(serveraddr)) < 0) { | |
err_n_die("connect failed!"); | |
} | |
sprintf(sendline, "GET / HTTP/1.1\r\n\r\n"); | |
sendbytes = strlen(sendline); | |
if (write(sockfd, sendline, sendbytes) != sendbytes) { | |
err_n_die("write error"); | |
} | |
memset(recvline, 0, MAXLINE); | |
while ((n = read(sockfd, recvline, MAXLINE - 1)) > 0) { | |
printf("%s", recvline); | |
memset(recvline, 0, MAXLINE); | |
} | |
if (n < 0) { | |
err_n_die("read errror"); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment