Created
November 26, 2019 08:10
-
-
Save ChongyeWang/990649ed4c527ce50396e34d5cc9c6dc to your computer and use it in GitHub Desktop.
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 <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netdb.h> | |
#include <unistd.h> | |
#include <arpa/inet.h> | |
int main(int argc, char **argv) { | |
int s; | |
int sock_fd = socket(AF_INET, SOCK_STREAM, 0); | |
struct addrinfo hints, *result; | |
memset(&hints, 0, sizeof (struct addrinfo)); | |
hints.ai_family = AF_INET; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = AI_PASSIVE; | |
s = getaddrinfo(NULL, "1234", &hints, &result); | |
if (s != 0) { | |
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); | |
exit(1); | |
} | |
if (bind(sock_fd, result->ai_addr, result->ai_addrlen) != 0) { | |
perror("bind()"); | |
exit(1); | |
} | |
if (listen(sock_fd, 10) != 0) { | |
perror("listen()"); | |
exit(1); | |
} | |
struct sockaddr_in *result_addr = (struct sockaddr_in *) result->ai_addr; | |
printf("Listening on file descriptor %d, port %d\n", sock_fd, ntohs(result_addr->sin_port)); | |
printf("Waiting for connection...\n"); | |
int client_fd = accept(sock_fd, NULL, NULL); | |
printf("Connection made: client_fd=%d\n", client_fd); | |
char buffer[1000]; | |
int len = read(client_fd, buffer, sizeof (buffer) - 1); | |
buffer[len] = '\0'; | |
printf("Read %d chars\n", len); | |
printf("===\n"); | |
printf("%s\n", buffer); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment