379_demos/lab3/demos/client.c

91 lines
2 KiB
C
Raw Permalink Normal View History

2024-10-01 16:45:02 -06:00
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#define PORT "1025"
#define HOST "localhost"
#define SOURCE_PORT "1026"
int create_client_sock(char* port, char* host, char* source_port) {
struct addrinfo hints = {
.ai_family = AF_INET6,
.ai_socktype = SOCK_STREAM,
.ai_flags = AI_V4MAPPED,
};
struct addrinfo* res;
int err = getaddrinfo(host, port, &hints, &res);
if (err != 0) {
fprintf(stderr, "%s\n", gai_strerror(err));
_exit(1);
}
struct addrinfo *self;
err = getaddrinfo(NULL, source_port, &hints, &self);
if (err != 0) {
fprintf(stderr, "%s\n", gai_strerror(err));
_exit(1);
}
int sfd;
struct addrinfo* cur = res;
for (; cur != NULL; cur = cur->ai_next) {
// socket
sfd = socket(cur->ai_family, cur->ai_socktype, cur->ai_protocol);
if (sfd == -1) {
perror("socket");
continue;
}
int val = 1;
err = setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
if (err == -1) {
perror("setsockopt");
close(sfd);
continue;
}
// Bind
err = bind(sfd, self->ai_addr, self->ai_addrlen);
if (err == -1) {
perror("bind");
close(sfd);
continue;
}
// Connect
err = connect(sfd, res->ai_addr, res->ai_addrlen);
if (err == -1) {
perror("connect");
close(sfd);
continue;
}
break;
}
freeaddrinfo(res);
freeaddrinfo(self);
if (cur == NULL) {
fprintf(stderr, "failed to connect to the server\n");
_exit(1);
}
return sfd;
}
int main() {
int cfd = create_client_sock(PORT, HOST, SOURCE_PORT);
char* msg = "This is a test message!\n";
write(cfd, msg, strlen(msg));
printf("message send: \"%s\"\n", msg);
close(cfd);
}