upgrade metainfo to net.Addrs

This commit is contained in:
idk
2022-03-09 12:39:15 -05:00
parent 5c1d55731f
commit a8a6984ced
2 changed files with 57 additions and 2 deletions

View File

@ -26,6 +26,7 @@ import (
"github.com/eyedeekay/sam3"
"github.com/eyedeekay/sam3/i2pkeys"
"github.com/xgfone/bt/bencode"
"github.com/xgfone/bt/utils"
)
// ErrInvalidAddr is returned when the compact address is invalid.
@ -193,8 +194,8 @@ func (a *Address) FromString(addr string) (err error) {
}
// FromUDPAddr sets the ip from net.UDPAddr.
func (a *Address) FromUDPAddr(ua *net.UDPAddr) {
a.Port = uint16(ua.Port)
func (a *Address) FromUDPAddr(ua net.Addr) {
a.Port = uint16(utils.Port(ua))
a.IP = ua
}

54
utils/addr.go Normal file
View File

@ -0,0 +1,54 @@
// Copyright 2020 xgfone
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package utils
import (
"net"
"strconv"
)
func IPAddr(a net.Addr) string {
switch a := a.(type) {
case *net.TCPAddr:
return a.IP.String()
case *net.UDPAddr:
return a.IP.String()
default:
ip, _, err := net.SplitHostPort(a.String())
if err != nil {
return ""
}
return ip
}
}
func Port(a net.Addr) int {
switch a := a.(type) {
case *net.TCPAddr:
return a.Port
case *net.UDPAddr:
return a.Port
default:
_, port, err := net.SplitHostPort(a.String())
if err != nil {
return 0
}
iport, err := strconv.Atoi(port)
if err != nil {
return 0
}
return iport
}
}