tcp_opts.cc
1 /******************************************************************** 2 * Description: tcp_opts.cc 3 * 4 * Derived from a work by Fred Proctor & Will Shackleford 5 * 6 * Author: 7 * License: LGPL Version 2 8 * System: Linux 9 * 10 * Copyright (c) 2004 All rights reserved. 11 * 12 * Last change: 13 ********************************************************************/ 14 15 #include "tcp_opts.hh" 16 #include "rcs_print.hh" /* rcs_print_error() */ 17 18 #include <errno.h> // errno 19 #include <string.h> // strerror 20 #include <netinet/tcp.h> // TCP_NODELAY 21 #include <netinet/in.h> // TCP_NODELAY 22 #include <sys/fcntl.h> // fcntl, O_NONBLOCK 23 24 #include <sys/types.h> 25 #include <sys/socket.h> 26 27 int set_tcp_socket_options(int socket_fd) 28 { 29 if (socket_fd <= 0) { 30 return -1; 31 } 32 int optval = 1; 33 #ifdef TCP_NODELAY 34 if (setsockopt(socket_fd, IPPROTO_TCP, TCP_NODELAY, 35 (char *) &optval, sizeof(optval)) < 0) { 36 rcs_print_error(" Can`t set a socket option.\n"); 37 rcs_print_error("errno = %d = %s\n", errno, strerror(errno)); 38 return -1; 39 } 40 #endif 41 42 optval = 1; 43 44 if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, 45 (char *) &optval, sizeof(optval)) < 0) { 46 rcs_print_error(" Can`t set a socket option.\n"); 47 rcs_print_error("errno = %d = %s\n", errno, strerror(errno)); 48 return -1; 49 } 50 struct linger linger_opt; 51 linger_opt.l_onoff = 0; 52 linger_opt.l_linger = 0; 53 if (setsockopt(socket_fd, SOL_SOCKET, SO_LINGER, 54 (char *) &linger_opt, sizeof(linger_opt)) < 0) { 55 rcs_print_error(" Can`t set a socket option.\n"); 56 rcs_print_error("errno = %d = %s\n", errno, strerror(errno)); 57 return -1; 58 } 59 return 0; 60 } 61 62 int make_tcp_socket_nonblocking(int socket_fd) 63 { 64 #ifdef O_NONBLOCK 65 if (-1 == fcntl(socket_fd, F_SETFL, O_NONBLOCK)) { 66 rcs_print_error("Couldn's set flag for non-blocking on socket.\n"); 67 return -1; 68 } 69 #else 70 #ifdef O_NDELAY 71 if (-1 == fcntl(socket_fd, F_SETFL, O_NDELAY)) { 72 rcs_print_error("Couldn's set flag for no delay on socket.\n"); 73 return -1; 74 } 75 #endif 76 #endif 77 return (0); 78 } 79 80 int make_tcp_socket_blocking(int socket_fd) 81 { 82 #if defined(O_NONBLOCK) || defined(O_NDELAY) 83 int val = fcntl(socket_fd, F_GETFL, 0); 84 if (val < 0) { 85 rcs_print_error("fcntl error %d %s\n", errno, strerror(errno)); 86 return -1; 87 } 88 #ifdef O_NONBLOCK 89 val &= ~O_NONBLOCK; 90 #endif 91 #ifdef O_NDELAY 92 val &= ~O_NDELAY; 93 #endif 94 if (fcntl(socket_fd, F_SETFL, val) < 0) { 95 rcs_print_error("Couldn's set flag for blocking on socket.: %d,%s\n", 96 errno, strerror(errno)); 97 return -1; 98 } 99 #endif 100 return (0); 101 }