Created
May 16, 2013 20:05
-
-
Save dmitru/5594660 to your computer and use it in GitHub Desktop.
A UNIX socket client
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
// Usage: | |
// client <address> <port> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <strings.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <sys/un.h> | |
int main(int argc, char *argv[]) | |
{ | |
if (argc < 3) | |
exit(1); | |
// 1. Create a socket | |
int clientSocket = socket(AF_INET, SOCK_STREAM, 0); | |
if (socket == -1) { | |
perror("socket() error"); | |
exit(errno); | |
} | |
puts("Socket created"); | |
// 2. Create a structure to hold the server's address | |
struct sockaddr_in serverAddress; | |
bzero(&serverAddress, sizeof(serverAddress)); | |
serverAddress.sin_family = AF_INET; | |
if (inet_aton(argv[1], &serverAddress.sin_addr)) { | |
perror("inet_aton() error"); | |
exit(errno); | |
} | |
serverAddress.sin_port = htons(atoi(argv[2])); | |
// 3. Connect to the newly created address | |
if (connect(clientSocket, (struct sockaddr *) &serverAddress, sizeof(serverAddress))) { | |
perror("connect() error"); | |
exit(errno); | |
} | |
puts("Socket connected"); | |
// 4. Communicate with the server | |
char c; | |
while ((c = getchar()) != EOF) { | |
int bytesSent = send(clientSocket, &c, 1, 0); | |
if (bytesSent < 0) { | |
perror("error while sending a byte"); | |
exit(errno); | |
} | |
} | |
close(clientSocket); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment