/ tls_client / sockets.c
sockets.c
1 // 2 // sockets.c 3 // coretls_tools 4 // 5 6 #include <stdio.h> 7 #include <unistd.h> 8 #include <strings.h> 9 #include <sys/types.h> 10 #include <sys/socket.h> 11 #include <netinet/in.h> 12 #include <arpa/inet.h> 13 #include <netdb.h> 14 #include <errno.h> 15 16 17 #include "sockets.h" 18 19 /* Connect to a hostname:port */ 20 int SocketConnect(const char *hostname, const char *service, bool udp) 21 { 22 int err; 23 int sock; 24 struct addrinfo hints, *res, *res0; 25 const char *cause = NULL; 26 27 memset(&hints, 0, sizeof(hints)); 28 hints.ai_family = udp?PF_INET:PF_UNSPEC; // For udp, hint to ipv4 29 hints.ai_socktype = udp?SOCK_DGRAM:SOCK_STREAM; 30 err = getaddrinfo(hostname, service, &hints, &res0); 31 if (err) { 32 fprintf(stderr, "%s", gai_strerror(err)); 33 return err; 34 } 35 sock = -1; 36 for (res = res0; res; res = res->ai_next) { 37 sock = socket(res->ai_family, res->ai_socktype, 38 res->ai_protocol); 39 if (sock < 0) { 40 cause = "socket"; 41 continue; 42 } 43 44 if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) { 45 cause = "connect"; 46 close(sock); 47 sock = -1; 48 continue; 49 } 50 51 break; /* okay we got one */ 52 } 53 if (sock < 0) { 54 fprintf(stderr, "%s", cause); 55 } 56 freeaddrinfo(res0); 57 58 return sock; 59 } 60 61 int SocketBind(int port, bool udp) 62 { 63 struct sockaddr_in sa; 64 int sock; 65 int val = 1; 66 67 if ((sock=socket(AF_INET, udp?SOCK_DGRAM:SOCK_STREAM, 0))==-1) { 68 perror("socket"); 69 return -errno; 70 } 71 72 setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *)&val, sizeof(val)); 73 74 75 memset((char *) &sa, 0, sizeof(sa)); 76 sa.sin_family = AF_INET; 77 sa.sin_port = htons(port); 78 sa.sin_addr.s_addr = htonl(INADDR_ANY); 79 80 if(bind (sock, (struct sockaddr *)&sa, sizeof(sa))==-1) 81 { 82 perror("bind"); 83 return -errno; 84 } 85 86 87 return sock; 88 } 89