93 lines
2 KiB
C
93 lines
2 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <sys/types.h>
|
|
#include <sys/socket.h>
|
|
#include <netdb.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
|
|
int server_tcp() {
|
|
char* hostname = "localhost";
|
|
char* port = "9004";
|
|
|
|
struct addrinfo hints = {0};
|
|
hints.ai_family = AF_INET;
|
|
hints.ai_socktype = SOCK_STREAM;
|
|
hints.ai_protocol = IPPROTO_TCP;
|
|
hints.ai_flags = AI_PASSIVE;
|
|
|
|
struct addrinfo* res;
|
|
int err_ret = getaddrinfo(hostname, port, &hints, &res);
|
|
if (err_ret != 0) {
|
|
fprintf(stderr, "getaddrinfo got error code: %d\n", err_ret);
|
|
return -1;
|
|
}
|
|
|
|
int sfd = -1;
|
|
for (struct addrinfo* i = res; i != NULL; i = i->ai_next) {
|
|
sfd = socket(i->ai_family, i->ai_socktype, i->ai_protocol);
|
|
if (sfd == -1) {
|
|
perror("socket");
|
|
continue;
|
|
}
|
|
|
|
int err_ = bind(sfd, i->ai_addr, i->ai_addrlen);
|
|
if (err_ == -1) {
|
|
perror("bind server tcp");
|
|
close(sfd);
|
|
continue;
|
|
}
|
|
|
|
err_ = listen(sfd, 100);
|
|
if (err_ == -1) {
|
|
perror("listen server tcp");
|
|
close(sfd);
|
|
continue;
|
|
}
|
|
|
|
break;
|
|
}
|
|
|
|
freeaddrinfo(res);
|
|
return sfd;
|
|
}
|
|
|
|
void* echo_server(int sfd_server, int sfd_client) {
|
|
printf("socket server: %d\n", sfd_server);
|
|
printf("socket client: %d\n", sfd_client);
|
|
|
|
char buf[1000];
|
|
int len;
|
|
while (1) {
|
|
len = read(sfd_client, buf, 1000);
|
|
|
|
if (len == 0) {
|
|
continue;
|
|
}
|
|
|
|
printf("Got length: %d\n", len);
|
|
printf("Server received message: `%s`\n", buf);
|
|
break;
|
|
}
|
|
|
|
char* new_msg = "Some new string from the server";
|
|
write(sfd_client, new_msg, strlen(new_msg) + 1);
|
|
|
|
close(sfd_client);
|
|
return NULL;
|
|
}
|
|
|
|
|
|
int main(void) {
|
|
int sfd_server = server_tcp();
|
|
int sfd_client = accept(sfd_server, NULL, NULL);
|
|
|
|
if (sfd_client == -1) {
|
|
perror("accept server tcp");
|
|
return 1;
|
|
}
|
|
|
|
echo_server(sfd_server, sfd_client);
|
|
|
|
close(sfd_server);
|
|
}
|