Skip to content

Instantly share code, notes, and snippets.

@xeioex
Created August 7, 2018 18:07
Show Gist options
  • Save xeioex/8caa6c28f1c62bbd88bbd3bbeee1b9b6 to your computer and use it in GitHub Desktop.
Save xeioex/8caa6c28f1c62bbd88bbd3bbeee1b9b6 to your computer and use it in GitHub Desktop.
/*
* tcpclient.c - A simple TCP client
* usage: tcpclient <host> <port>
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define BUFSIZE 1024
/*
* error - wrapper for perror
*/
void error(char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char **argv) {
int sockfd, portno, n;
struct sockaddr_in serveraddr;
struct hostent *server;
char *hostname;
char buf[BUFSIZE];
/* check command line arguments */
if (argc != 3) {
fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
exit(0);
}
hostname = argv[1];
portno = atoi(argv[2]);
/* socket: create the socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
/* gethostbyname: get the server's DNS entry */
server = gethostbyname(hostname);
if (server == NULL) {
fprintf(stderr,"ERROR, no such host as %s\n", hostname);
exit(0);
}
/* build the server's Internet address */
bzero((char *) &serveraddr, sizeof(serveraddr));
serveraddr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serveraddr.sin_addr.s_addr, server->h_length);
serveraddr.sin_port = htons(portno);
/* connect: create a connection with the server */
if (connect(sockfd, (struct sockaddr *) &serveraddr, sizeof(serveraddr)) < 0)
error("ERROR connecting");
for (int i = 0; i < 10; i++) {
/* send the message line to the server */
buf[0] = 'A' + i;
buf[1] = 'A' + i;
buf[2] = 'A' + i;
buf[3] = 'A' + i;
buf[4] = '\0';
printf("sending: '%.*s'\n", (int) strlen(buf), buf);
n = write(sockfd, buf, strlen(buf));
if (n < 0)
error("ERROR writing to socket");
sleep(1);
}
close(sockfd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment