Skip to content

Instantly share code, notes, and snippets.

@kYroL01
Created August 30, 2021 22:31
Show Gist options
  • Save kYroL01/fb2e5fa375856e1cdb4c451d4113a9f7 to your computer and use it in GitHub Desktop.
Save kYroL01/fb2e5fa375856e1cdb4c451d4113a9f7 to your computer and use it in GitHub Desktop.
TCP client
/* -*- compile-command: "gcc -Wall -pedantic -g3 client.c -o client" -*- */
/**
TCP client implementation
1. Create TCP socket.
2. connect() Connect newly created client socket to server.
**/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netdb.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define BUFF_SIZE 1000
#define PORT 8080
void func_client(int sockfd)
{
char buff[BUFF_SIZE];
int n, nread = 0, nwrite = 0;
/* infinite loop */
for (;;) {
memset(buff, 0, sizeof(buff));
printf("\nEnter the string : ");
n = 0;
while((buff[n++] = getchar()) != '\n');
errno = 0;
nwrite = write(sockfd, buff, sizeof(buff));
if(nwrite == -1) {
perror("write");
exit(EXIT_FAILURE);
}
memset(buff, 0, sizeof(buff));
errno = 0;
nread = read(sockfd, buff, sizeof(buff));
if(nread == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Message From Server : %s\n", buff);
}
}
// MAIN
int main(int argc, char *argv[])
{
struct sockaddr_in servaddr;
int sockfd;
// Socket create
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd == -1) {
printf("Socket creation failed...\n");
exit(EXIT_FAILURE);
} else {
printf("Socket successfully created..\n");
}
memset(&servaddr, 0, sizeof(servaddr));
// Assign IP, PORT
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
servaddr.sin_port = htons(PORT);
// Connect the client socket to server socket
if (connect(sockfd, (struct sockaddr*) &servaddr, sizeof(servaddr)) != 0) {
printf("Client connect() with server failed...\n");
exit(EXIT_FAILURE);
} else {
printf("Connected to the server..\n");
}
// Function for CLIENT
func_client(sockfd);
// Close the socket
close(sockfd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment