Last active
November 23, 2015 16:20
-
-
Save cmaruan/2795843fbd1b13d7d739 to your computer and use it in GitHub Desktop.
Simple client 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
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <netinet/in.h> | |
#include <netdb.h> | |
#include <stdio.h> | |
#include <string.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <errno.h> | |
#include <arpa/inet.h> | |
#define error(msg, ret) do { fprintf(stderr, "Error: " msg "\n"); exit(ret); } while (0) | |
int communicate(struct sockaddr_in * serv_addr, const char * message, char ** response) { | |
int sockfd = 0, n = 0, len = 0; | |
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) | |
error("could not create socket.", -1); | |
if (connect(sockfd, (struct sockaddr *)serv_addr, sizeof(*serv_addr)) < 0) | |
error("connection failed.", -1); | |
return 0; | |
} | |
struct sockaddr_in * init(int argc, char * argv[]) { | |
struct sockaddr_in * serv_addr; | |
char * ip, * port, * message; | |
if (argc < 2) | |
error("use <program name> <server ip addr>:<port>", -1); | |
serv_addr = calloc(1, sizeof(*serv_addr)); | |
ip = strtok(argv[1], ":"); | |
port = strtok(NULL, ""); | |
serv_addr->sin_family = AF_INET; | |
serv_addr->sin_port = htons(atoi(port)); | |
if(inet_pton(AF_INET, ip, &serv_addr->sin_addr) <= 0) | |
error("inet_pton error occured.", -1); | |
return serv_addr; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
struct sockaddr_in * serv_addr; | |
char * message; | |
serv_addr = init(argc, argv); | |
communicate(serv_addr, "message", &message); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment