Created
April 2, 2019 03:20
-
-
Save ksvbka/d87840ce07a9e1f039848bada2b799ed to your computer and use it in GitHub Desktop.
Socket util
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <errno.h> | |
| #include <string.h> | |
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <netinet/in.h> | |
| #include <arpa/inet.h> | |
| #include <netdb.h> | |
| #include "inet_sockets.h" | |
| #ifdef TRUE | |
| #undef TRUE | |
| #endif | |
| #ifdef FALSE | |
| #undef FALSE | |
| #endif | |
| typedef enum { FALSE, TRUE } boolean_t; | |
| /* The following arguments are common to several of the routines below: | |
| 'host': NULL for loopback IP address, or | |
| a host name or numeric IP address | |
| 'service': either a name or a port number | |
| 'type': either SOCK_STREAM or SOCK_DGRAM | |
| */ | |
| /* Create socket and connect it to the address specified by | |
| 'host' + 'service'/'type'. Return socket descriptor on success, | |
| or -1 on error */ | |
| int inet_connect(const char *host, const char *service, int type) | |
| { | |
| struct addrinfo hints; | |
| struct addrinfo *result, *rp; | |
| int sfd, s; | |
| memset(&hints, 0, sizeof(struct addrinfo)); | |
| hints.ai_canonname = NULL; | |
| hints.ai_addr = NULL; | |
| hints.ai_next = NULL; | |
| hints.ai_family = AF_UNSPEC; /* Allows IPv4 or IPv6 */ | |
| hints.ai_socktype = type; | |
| s = getaddrinfo(host, service, &hints, &result); | |
| if (s != 0) { | |
| errno = ENOSYS; | |
| return -1; | |
| } | |
| /* Walk through returned list until we find an address structure | |
| that can be used to successfully connect a socket */ | |
| for (rp = result; rp != NULL; rp = rp->ai_next) { | |
| sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
| if (sfd == -1) | |
| continue; /* On error, try next address */ | |
| if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1) | |
| break; /* Success */ | |
| /* Connect failed: close this socket and try next address */ | |
| close(sfd); | |
| } | |
| freeaddrinfo(result); | |
| return (rp == NULL) ? -1 : sfd; | |
| } | |
| /* Create an Internet domain socket and bind it to the address | |
| { wildcard-IP-address + 'service'/'type' }. | |
| If 'do_listen' is TRUE, then make this a listening socket (by | |
| calling listen() with 'backlog'), with the SO_REUSEADDR option set. | |
| If 'addrLen' is not NULL, then use it to return the size of the | |
| address structure for the address family for this socket. | |
| Return the socket descriptor on success, or -1 on error. */ | |
| static int /* Public interfaces: inet_bind() and inet_listen() */ | |
| inet_passive_socket(const char *service, int type, socklen_t *addrlen, | |
| boolean_t do_listen, int backlog) | |
| { | |
| struct addrinfo hints; | |
| struct addrinfo *result, *rp; | |
| int sfd, optval, s; | |
| memset(&hints, 0, sizeof(struct addrinfo)); | |
| hints.ai_canonname = NULL; | |
| hints.ai_addr = NULL; | |
| hints.ai_next = NULL; | |
| hints.ai_socktype = type; | |
| hints.ai_family = AF_UNSPEC; /* Allows IPv4 or IPv6 */ | |
| hints.ai_flags = AI_PASSIVE; /* Use wildcard IP address */ | |
| s = getaddrinfo(NULL, service, &hints, &result); | |
| if (s != 0) | |
| return -1; | |
| /* Walk through returned list until we find an address structure | |
| that can be used to successfully create and bind a socket */ | |
| optval = 1; | |
| for (rp = result; rp != NULL; rp = rp->ai_next) { | |
| sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
| if (sfd == -1) | |
| continue; /* On error, try next address */ | |
| if (do_listen) { | |
| if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)) == -1) { | |
| close(sfd); | |
| freeaddrinfo(result); | |
| return -1; | |
| } | |
| } | |
| if (bind(sfd, rp->ai_addr, rp->ai_addrlen) == 0) | |
| break; /* Success */ | |
| /* bind() failed: close this socket and try next address */ | |
| close(sfd); | |
| } | |
| if (rp != NULL && do_listen) { | |
| if (listen(sfd, backlog) == -1) { | |
| freeaddrinfo(result); | |
| return -1; | |
| } | |
| } | |
| if (rp != NULL && addrlen != NULL) | |
| *addrlen = rp->ai_addrlen; /* Return address structure size */ | |
| freeaddrinfo(result); | |
| return (rp == NULL) ? -1 : sfd; | |
| } | |
| /* Create stream socket, bound to wildcard IP address + port given in | |
| 'service'. Make the socket a listening socket, with the specified | |
| 'backlog'. Return socket descriptor on success, or -1 on error. */ | |
| int inet_listen(const char *service, int backlog, socklen_t *addrlen) | |
| { | |
| return inet_passive_socket(service, SOCK_STREAM, addrlen, TRUE, backlog); | |
| } | |
| /* Create socket bound to wildcard IP address + port given in | |
| 'service'. Return socket descriptor on success, or -1 on error. */ | |
| int inet_bind(const char *service, int type, socklen_t *addrlen) | |
| { | |
| return inet_passive_socket(service, type, addrlen, FALSE, 0); | |
| } | |
| /* Given a socket address in 'addr', whose length is specified in | |
| 'addrlen', return a null-terminated string containing the host and | |
| service names in the form "(hostname, port#)". The string is | |
| returned in the buffer pointed to by 'addr_str', and this value is | |
| also returned as the function result. The caller must specify the | |
| size of the 'addr_str' buffer in 'addr_strLen'. */ | |
| char * inet_address_str(const struct sockaddr *addr, socklen_t addrlen, | |
| char *addr_str, int addr_strLen) | |
| { | |
| char host[NI_MAXHOST], service[NI_MAXSERV]; | |
| if (getnameinfo(addr, addrlen, host, NI_MAXHOST, service, NI_MAXSERV, NI_NUMERICSERV) == 0) | |
| snprintf(addr_str, addr_strLen, "(%s, %s)", host, service); | |
| else | |
| snprintf(addr_str, addr_strLen, "(?UNKNOWN?)"); | |
| return addr_str; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #ifndef __INET_SOCKETS_H__ | |
| #define __INET_SOCKETS_H__ | |
| #include <sys/socket.h> | |
| #include <netdb.h> | |
| /* Suggested length for string buffer that caller | |
| should pass to inetAddressStr(). Must be greater | |
| than (NI_MAXHOST + NI_MAXSERV + 4) */ | |
| #define IS_ADDR_STR_LEN 4096 | |
| /* Create a socket with the given socket type and connect to addr or service. | |
| Return file descriptor or -1 on error. | |
| Using for client need to connect to server socket */ | |
| int inet_connect(const char* host, const char* service, int type); | |
| /* Create listening SOCK_STREAM bound to IP/Port specified by service. | |
| Return file descriptor or -1 if error. | |
| Using for TCP server */ | |
| int inet_listen(const char* service, int backlog, socklen_t *addrlen); | |
| /* Create socket of given type, bound to IP/port specified by service. | |
| Return file descriptor or -1 if error. | |
| Using for UDP server and client to create socket bound to specific addr */ | |
| int inet_bind(const char* service, int type, socklen_t *addrlen); | |
| /* Return string containing hostname and port as form (hostname, port) store | |
| in addr_str buffer with max length is addr_str_len -1. */ | |
| char* inet_address_str(const struct sockaddr *addr, socklen_t addrlen, | |
| char* addr_str, int addr_str_len); | |
| #endif //__INET_SOCKETS_H__ |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <stdarg.h> | |
| #include <string.h> | |
| #include "inet_sockets.h" | |
| void err_exit(const char *format, ...) { | |
| va_list args; | |
| va_start(args, format); | |
| vfprintf(stderr, format, args); | |
| va_end(args); | |
| exit(EXIT_FAILURE); | |
| } | |
| void usage_err(const char *format, ...) | |
| { | |
| va_list argList; | |
| fflush(stdout); /* Flush any pending stdout */ | |
| fprintf(stderr, "Usage: "); | |
| va_start(argList, format); | |
| vfprintf(stderr, format, argList); | |
| va_end(argList); | |
| fflush(stderr); /* In case stderr is not line-buffered */ | |
| exit(EXIT_FAILURE); | |
| } | |
| int main(int argc, char *argv[]) | |
| { | |
| int listenFd, acceptFd, connFd; | |
| socklen_t len; /* Size of socket address buffer */ | |
| void *addr; /* Buffer for socket address */ | |
| char addr_str[IS_ADDR_STR_LEN]; | |
| if (argc != 2 || strcmp(argv[1], "--help") == 0) | |
| usage_err("%s service\n", argv[0]); | |
| /* Create listening socket, obtain size of address structure */ | |
| listenFd = inet_listen(argv[1], 5, &len); | |
| if (listenFd == -1) | |
| err_exit("inet_listen"); | |
| connFd = inet_connect(NULL, argv[1], SOCK_STREAM); | |
| if (connFd == -1) | |
| err_exit("inet_connect"); | |
| acceptFd = accept(listenFd, NULL, NULL); | |
| if (acceptFd == -1) | |
| err_exit("accept"); | |
| addr = malloc(len); | |
| if (addr == NULL) | |
| err_exit("malloc"); | |
| if (getsockname(connFd, addr, &len) == -1) | |
| err_exit("getsockname"); | |
| printf("getsockname(connFd): %s\n", inet_address_str(addr, len, addr_str, IS_ADDR_STR_LEN)); | |
| if (getsockname(acceptFd, addr, &len) == -1) | |
| err_exit("getsockname"); | |
| printf("getsockname(acceptFd): %s\n", inet_address_str(addr, len, addr_str, IS_ADDR_STR_LEN)); | |
| if (getpeername(connFd, addr, &len) == -1) | |
| err_exit("getpeername"); | |
| printf("getpeername(connFd): %s\n", inet_address_str(addr, len, addr_str, IS_ADDR_STR_LEN)); | |
| if (getpeername(acceptFd, addr, &len) == -1) | |
| err_exit("getpeername"); | |
| printf("getpeername(acceptFd): %s\n", inet_address_str(addr, len, addr_str, IS_ADDR_STR_LEN)); | |
| sleep(30); /* Give us time to run netstat(8) */ | |
| exit(EXIT_SUCCESS); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment