Created
November 3, 2018 19:59
-
-
Save emandret/f9d8a1c6951ded4cdac4dbc5396a7f58 to your computer and use it in GitHub Desktop.
A socket example where the client act as the server by waiting for data and printing it
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 <arpa/inet.h> | |
#include <errno.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#define REMOTE_ADDR "127.0.0.1" | |
#define REMOTE_PORT 4444 | |
int main(void) | |
{ | |
int sock_fd; | |
struct sockaddr_in remote_addr; | |
char buf[1024]; | |
ssize_t ret; | |
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { | |
fprintf(stderr, "Socket creation error: %s\n", strerror(errno)); | |
return 1; | |
} | |
bzero(&remote_addr, 0); | |
remote_addr.sin_family = AF_INET; | |
remote_addr.sin_port = htons(REMOTE_PORT); | |
if (inet_pton(AF_INET, REMOTE_ADDR, &remote_addr.sin_addr) == -1) { | |
fprintf(stderr, "Invalid address: %s\n", strerror(errno)); | |
return 1; | |
} | |
if (connect(sock_fd, (struct sockaddr*)&remote_addr, sizeof(remote_addr)) < 0) { | |
fprintf(stderr, "Connection error: %s\n", strerror(errno)); | |
return 1; | |
} | |
while ((ret = recv(sock_fd, buf, 1023, 0))) { | |
buf[ret] = '\0'; | |
printf("%s\n", buf); | |
} | |
if (ret == 0) { | |
fprintf(stderr, "Connection closed by remote host\n"); | |
return 1; | |
} else if (ret == -1) { | |
fprintf(stderr, "Receiving error: %s\n", strerror(errno)); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment