Last active
July 30, 2016 17:27
-
-
Save hex128/8746254e0025be2172db to your computer and use it in GitHub Desktop.
Example C TCP socket client
This file contains hidden or 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 <stdio.h> | |
#include <stdlib.h> | |
#include <netdb.h> | |
#include <string.h> | |
#include <unistd.h> | |
int main(int argc, char *argv[]) { | |
int sockfd; | |
ssize_t n; | |
uint16_t portno; | |
struct sockaddr_in serv_addr; | |
struct hostent *server; | |
char buffer[256]; | |
if (argc < 3) { | |
fprintf(stderr, "Usage: %s <host> <port>\n", argv[0]); | |
exit(1); | |
} | |
portno = (uint16_t) atoi(argv[2]); | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd < 0) { | |
perror("Error opening socket\n"); | |
exit(2); | |
} | |
server = gethostbyname(argv[1]); | |
if (server == NULL) { | |
fprintf(stderr, "Host not found\n"); | |
exit(3); | |
} | |
bzero(&serv_addr, sizeof(serv_addr)); | |
serv_addr.sin_family = AF_INET; | |
bcopy(server->h_addr, (char *) &serv_addr.sin_addr.s_addr, (size_t) server->h_length); | |
serv_addr.sin_port = htons(portno); | |
if (connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { | |
perror("ERROR connecting\n"); | |
exit(4); | |
} | |
printf("Please enter the message: "); | |
bzero(buffer, 256); | |
fgets(buffer, 255, stdin); | |
n = write(sockfd, buffer, strlen(buffer)); | |
if (n < 0) { | |
perror("ERROR writing to socket\n"); | |
exit(5); | |
} | |
bzero(buffer, 256); | |
n = read(sockfd, buffer, 255); | |
if (n < 0) { | |
perror("Error reading from socket\n"); | |
exit(6); | |
} | |
printf("%s\n", buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment