90 lines
2 KiB
C
90 lines
2 KiB
C
#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);
|
|
}
|