379_demos/lab10/client_tcp.c

62 lines
1.4 KiB
C
Raw Permalink Normal View History

2025-01-31 17:18:34 -07:00
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <string.h>
int client_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;
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 connect_err = connect(sfd, i->ai_addr, i->ai_addrlen);
if (connect_err == -1) {
perror("connect client tcp");
continue;
}
break;
}
freeaddrinfo(res);
if (sfd == -1) {
fprintf(stderr, "couldn't create client socket\n");
return -1;
}
return sfd;
}
int main(void) {
int sfd_client = client_tcp();
char* my_string = "message from tcp client";
write(sfd_client, my_string, strlen(my_string) + 1);
char buf[1000];
read(sfd_client, buf, 1000);
printf("Client recieved from server: `%s`\n", buf);
close(sfd_client);
}