You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

106 lines
2.6 KiB
C

#include "easysock.h"
int create_socket(int network, char transport) {
int domain;
int type;
if (network == 4) {
domain = AF_INET;
} else if (network == 6) {
domain = AF_INET6;
} else {
return -1;
}
if (transport == 'T') {
type = SOCK_STREAM;
} else if (transport == 'U') {
type = SOCK_DGRAM;
} else {
return -1;
}
int newSock = socket(domain,type,0);
return newSock;
}
void create_addr(int network, char* address, int port,struct sockaddr* dest) {
if (network == 4) {
struct sockaddr_in listen_address;
listen_address.sin_family = AF_INET;
listen_address.sin_port = htons(port);
inet_pton(AF_INET,address,&listen_address.sin_addr);
memcpy(dest,&listen_address,sizeof(listen_address));
return;
} else if (network == 6) {
struct sockaddr_in6 listen_ipv6;
listen_ipv6.sin6_family = AF_INET6;
listen_ipv6.sin6_port = htons(port);
inet_pton(AF_INET6,address,&listen_ipv6.sin6_addr);
memcpy(dest,&listen_ipv6,sizeof(listen_ipv6));
return;
} else {
exit(-2);
}
}
int create_local (int network, char transport, char* address, int port,struct sockaddr* addr_struct) {
int socket = create_socket(network,transport);
if (socket < 0) {
exit(socket);
}
create_addr(network,address,port,addr_struct);
int addrlen;
if (network == 4) {
addrlen = sizeof(struct sockaddr_in);
} else if (network == 6) {
addrlen = sizeof(struct sockaddr_in6);
} else {
exit(-7);
}
/* The value of addrlen should be the size of the 'sockaddr'.
This should be set to the size of 'sockaddr_in' for IPv4, and 'sockaddr_in6' for IPv6.
See https://stackoverflow.com/questions/73707162/socket-bind-failed-with-invalid-argument-error-for-program-running-on-macos */
int i = bind (socket,addr_struct,(socklen_t)addrlen);
if (i < 0) {
exit(errno);
}
return socket;
}
int create_remote (int network,char transport,char* address,int port) {
int socket = create_socket(network,transport);
if (socket == -1) {
exit(-1);
}
struct sockaddr remote_addr_struct;
create_addr(network,address,port,&remote_addr_struct);
int addrlen;
if (network == 4) {
addrlen = sizeof(struct sockaddr_in);
} else if (network == 6) {
addrlen = sizeof(struct sockaddr_in6);
} else {
exit(-7);
}
/* The value of addrlen should be the size of the 'sockaddr'.
This should be set to the size of 'sockaddr_in' for IPv4, and 'sockaddr_in6' for IPv6.
See https://stackoverflow.com/questions/73707162/socket-bind-failed-with-invalid-argument-error-for-program-running-on-macos */
int i = connect(socket,&remote_addr_struct,(socklen_t)addrlen);
if (i < 0) {
exit(errno);
}
return socket;
}