Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A socket example where the client act as the server by waiting for data and printing it
#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
You can’t perform that action at this time.