1 /* 2 * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 #include <stdio.h> 27 #include <stdlib.h> 28 #include <unistd.h> 29 #include <errno.h> 30 31 #if defined(_ALLBSD_SOURCE) 32 #include <sys/sysctl.h> 33 #endif 34 35 #include "jni.h" 36 #include "net_util.h" 37 #include "sun_net_PortConfig.h" 38 39 #ifdef __cplusplus 40 extern "C" { 41 #endif 42 43 struct portrange { 44 int lower; 45 int higher; 46 }; 47 48 static int getPortRange(struct portrange *range) 49 { 50 #ifdef __linux__ 51 { 52 FILE *f; 53 int ret; 54 55 f = fopen("/proc/sys/net/ipv4/ip_local_port_range", "r"); 56 if (f != NULL) { 57 ret = fscanf(f, "%d %d", &range->lower, &range->higher); 58 fclose(f); 59 return ret == 2 ? 0 : -1; 60 } 61 return -1; 62 } 63 #elif defined(_ALLBSD_SOURCE) 64 { 65 int ret; 66 size_t size = sizeof(range->lower); 67 ret = sysctlbyname( 68 "net.inet.ip.portrange.first", &range->lower, &size, 0, 0 69 ); 70 if (ret == -1) { 71 return -1; 72 } 73 size = sizeof(range->higher); 74 ret = sysctlbyname( 75 "net.inet.ip.portrange.last", &range->higher, &size, 0, 0 76 ); 77 return ret; 78 } 79 #else 80 return -1; 81 #endif 82 } 83 84 /* 85 * Class: sun_net_PortConfig 86 * Method: getLower0 87 * Signature: ()I 88 */ 89 JNIEXPORT jint JNICALL Java_sun_net_PortConfig_getLower0 90 (JNIEnv *env, jclass clazz) 91 { 92 struct portrange range; 93 if (getPortRange(&range) < 0) { 94 return -1; 95 } 96 return range.lower; 97 } 98 99 /* 100 * Class: sun_net_PortConfig 101 * Method: getUpper0 102 * Signature: ()I 103 */ 104 JNIEXPORT jint JNICALL Java_sun_net_PortConfig_getUpper0 105 (JNIEnv *env, jclass clazz) 106 { 107 struct portrange range; 108 if (getPortRange(&range) < 0) { 109 return -1; 110 } 111 return range.higher; 112 } 113 114 #ifdef __cplusplus 115 } 116 #endif