1 /* 2 * Project: udptunnel 3 * File: socket.h 4 * 5 * Copyright (C) 2009 Daniel Meekins 6 * Contact: dmeekins - gmail 7 * 8 * This program is free software: you can redistribute it and/or modify 9 * it under the terms of the GNU General Public License as published by 10 * the Free Software Foundation, either version 3 of the License, or 11 * (at your option) any later version. 12 * 13 * This program is distributed in the hope that it will be useful, 14 * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 * GNU General Public License for more details. 17 * 18 * You should have received a copy of the GNU General Public License 19 * along with this program. If not, see <http://www.gnu.org/licenses/>. 20 */ 21 22 #ifndef SOCKET_H 23 #define SOCKET_H 24 25 #ifndef WIN32 26 #include <inttypes.h> 27 #include <sys/socket.h> 28 #include <arpa/inet.h> 29 #else 30 #include <winsock2.h> 31 #include <ws2tcpip.h> 32 #endif /*WIN32*/ 33 34 #include "common.h" 35 36 #define BACKLOG 10 37 #define ADDRSTRLEN (INET6_ADDRSTRLEN + 7) 38 39 #define SOCK_TYPE_TCP 1 40 #define SOCK_TYPE_UDP 2 41 #define SOCK_IPV4 3 42 #define SOCK_IPV6 4 43 44 #define SIN(sa) ((struct sockaddr_in *)sa) 45 #define SIN6(sa) ((struct sockaddr_in6 *)sa) 46 47 typedef struct socket { 48 int fd; /* Socket file descriptor to send/recv on */ 49 int type; /* SOCK_STREAM or SOCK_DGRAM */ 50 struct sockaddr_storage addr; /* IP and port */ 51 socklen_t addr_len; /* Length of sockaddr type */ 52 } socket_t; 53 54 #define SOCK_FD(s) ((s)->fd) 55 #define SOCK_LEN(s) ((s)->addr_len) 56 #define SOCK_ADDR(s) ((struct sockaddr *)&(s)->addr) 57 58 socket_t *sock_create(char *host, char *port, int ipver, int sock_type, 59 int is_serv, int conn); 60 socket_t *sock_copy(socket_t *sock); 61 int sock_connect(socket_t *sock, int is_serv, char *port); 62 socket_t *sock_accept(socket_t *serv); 63 int sock_addr_equal(socket_t *s1, socket_t *s2); 64 void sock_close(socket_t *s); 65 void sock_free(socket_t *s); 66 67 char *sock_get_str(socket_t *s, char *buf, int len); 68 char *sock_get_addrstr(socket_t *s, char *buf, int len); 69 uint16_t sock_get_port(socket_t *s); 70 int sock_recv(socket_t *sock, socket_t *from, char *data, int len); 71 int sock_send(socket_t *to, char *data, int len); 72 73 #endif /* SOCKET_H */ 74