github.heygears.com/openimsdk/tools@v0.0.49/utils/network/ip_test.go (about) 1 // Copyright © 2023 OpenIM. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package network 16 17 import ( 18 "net" 19 "net/http/httptest" 20 "testing" 21 ) 22 23 func TestGetLocalIP(t *testing.T) { 24 ip, err := GetLocalIP() 25 if err != nil { 26 t.Fatalf("Expected no error, got %v", err) 27 } 28 if ip == "" { 29 t.Fatal("Expected an IP address, got an empty string") 30 } 31 // Optionally, check the format of the IP address 32 if net.ParseIP(ip) == nil { 33 t.Fatalf("Expected a valid IP address, got %s", ip) 34 } 35 } 36 37 func TestGetRpcRegisterIP(t *testing.T) { 38 expectedIP := "192.168.1.1" 39 ip, err := GetRpcRegisterIP(expectedIP) 40 if err != nil { 41 t.Fatalf("Expected no error, got %v", err) 42 } 43 if ip != expectedIP { 44 t.Fatalf("Expected %s, got %s", expectedIP, ip) 45 } 46 47 // Test with an empty string, expecting a local IP back 48 ip, err = GetRpcRegisterIP("") 49 if err != nil { 50 t.Fatalf("Expected no error, got %v", err) 51 } 52 if net.ParseIP(ip) == nil { 53 t.Fatalf("Expected a valid IP address, got %s", ip) 54 } 55 t.Log("GetRpcRegisterIP:", ip) 56 } 57 58 func TestGetListenIP(t *testing.T) { 59 testCases := []struct { 60 input string 61 expected string 62 }{ 63 {"", "0.0.0.0"}, 64 {"192.168.1.1", "192.168.1.1"}, 65 } 66 67 for _, tc := range testCases { 68 result := GetListenIP(tc.input) 69 if result != tc.expected { 70 t.Errorf("Expected %s, got %s", tc.expected, result) 71 } 72 } 73 } 74 75 func TestRemoteIP(t *testing.T) { 76 testCases := []struct { 77 headers map[string]string 78 expectedIP string 79 }{ 80 {map[string]string{XClientIP: "192.168.1.1"}, "192.168.1.1"}, 81 {map[string]string{XRealIP: "10.0.0.1"}, "10.0.0.1"}, 82 {map[string]string{XForwardedFor: "172.16.0.1"}, "172.16.0.1"}, 83 {map[string]string{}, "127.0.0.1"}, // assuming RemoteAddr is set to "::1" 84 } 85 86 for _, tc := range testCases { 87 req := httptest.NewRequest("GET", "http://example.com", nil) 88 req.RemoteAddr = "::1" // simulate localhost IPv6 89 for key, value := range tc.headers { 90 req.Header.Set(key, value) 91 } 92 93 if ip := RemoteIP(req); ip != tc.expectedIP { 94 t.Errorf("Expected IP %s, got %s", tc.expectedIP, ip) 95 } 96 } 97 }