Skip to content

Instantly share code, notes, and snippets.

@Idorobots
Last active August 29, 2015 14:01
Show Gist options
  • Save Idorobots/8d487e3bd43b44d31a33 to your computer and use it in GitHub Desktop.
Save Idorobots/8d487e3bd43b44d31a33 to your computer and use it in GitHub Desktop.
Simple TCP Echo client.
#include <signal.h>
#include <errno.h>
#include <pthread.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define BUFFER_SIZE 1024
void *client_function(void *ptr);
struct args {
long id;
int port;
char * host;
};
int main(int argc, char *argv[]) {
pthread_t *threads;
size_t iret;
long i;
signal(SIGPIPE, SIG_IGN);
if(argc < 4) {
printf("USAGE: %s NUMCONNECTIONS HOST PORT\n", argv[0]);
exit(EXIT_FAILURE);
}
long num = atoi(argv[1]);
threads = malloc(num * sizeof(pthread_t));
for(i = 1; i <= num; ++i) {
printf("Spawning client %ld.\n", i);
struct args *a = malloc(sizeof(struct args));
a->host = argv[2];
a->port = atoi(argv[3]);
a->id = i;
iret = pthread_create(&threads[i], NULL, client_function, (void *) a);
}
for(i = 1; i <= num; ++i) {
pthread_join(threads[i], (void**) &iret);
printf("Client %ld returned %ld.\n", i, iret);
}
free(threads);
exit(EXIT_SUCCESS);
}
void *client_function(void *ptr) {
struct args *a = (struct args *) ptr;
int sockd;
int count;
char buffer[BUFFER_SIZE];
long i = a->id;
if ((sockd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
pthread_exit((void *) EXIT_FAILURE);
}
struct sockaddr_in serv_name;
serv_name.sin_family = AF_INET;
inet_aton(a->host, &serv_name.sin_addr);
serv_name.sin_port = htons(a->port);
printf("Trying to connect client %ld...\n", i);
if (connect(sockd, (struct sockaddr*)&serv_name, sizeof(serv_name)) != 0) {
pthread_exit((void *) EXIT_FAILURE);
}
printf("Client %ld connected!\n", i);
while (1) {
if((count = read(sockd, buffer, BUFFER_SIZE)) > 0) {
buffer[count] = 0;
printf("Client %ld received: %s\n", i, buffer);
write(sockd, buffer, count);
}
}
free(ptr);
close(sockd);
pthread_exit((void *) EXIT_SUCCESS);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment