Created
August 14, 2020 21:56
-
-
Save Josh798/f7052062cc91eafa81850a17e58c37df to your computer and use it in GitHub Desktop.
Simple TCP client connection (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 <stdio.h> | |
#include <unistd.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
/** | |
* Returns a file descriptor of a socket connected to the specified | |
* address, or returns -1 if an error occurred. | |
*/ | |
int connect_to_server(const char *ip_address, unsigned short port) | |
{ | |
int sockfd; | |
struct sockaddr_in servaddr; | |
sockfd = socket(AF_INET, SOCK_STREAM, 0); | |
if (sockfd == -1) | |
{ | |
fprintf(stderr, "Could not create socket. %s.\n", strerror(errno)); | |
return -1; | |
} | |
memset(&servaddr, 0, sizeof(servaddr)); | |
servaddr.sin_family = AF_INET; | |
if (inet_aton(ip_address, &(servaddr.sin_addr)) == 0) | |
{ | |
fprintf(stderr, "Could not parse IP address."); // inet_aton() does not set errno. | |
close(sockfd); | |
return -1; | |
} | |
servaddr.sin_port = htons(port); | |
if (connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) != 0) | |
{ | |
fprintf(stderr, "Could not connect to server. %s.\n", strerror(errno)); | |
close(sockfd); | |
return -1; | |
} | |
return sockfd; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment