发布时间:2024-11-22 01:36:49
- IP地址:每台主机都有一个唯一的IP地址,用于标识主机在网络上的位置。
- 端口号:端口号用于区分同一台主机上的不同网络服务,以便正确路由网络数据。
- 传输协议:常见的传输协议有TCP和UDP。TCP提供可靠的、面向连接的传输,而UDP则提供无连接的传输。
package main
import (
"fmt"
"net"
)
func main() {
conn, err := net.Dial("tcp", "example.com:80")
if err != nil {
fmt.Println("Error connecting:", err)
return
}
fmt.Println("Connected to", conn.RemoteAddr())
}
package main
import (
"fmt"
"net"
"time"
)
func main() {
host := "example.com"
port := "80"
timeout := time.Duration(2 * time.Second)
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
fmt.Println("Connection to", host, "failed:", err)
return
}
fmt.Println("Connection to", host, "succeeded:", conn.RemoteAddr())
}
package main
import (
"fmt"
"net"
"time"
)
func testConnectivity(host string, port string, results chan<- string) {
timeout := time.Duration(2 * time.Second)
conn, err := net.DialTimeout("tcp", net.JoinHostPort(host, port), timeout)
if err != nil {
results <- fmt.Sprintf("Connection to %s failed: %v", host, err)
return
}
results <- fmt.Sprintf("Connection to %s succeeded: %v", host, conn.RemoteAddr())
}
func main() {
hosts := []string{"example.com", "google.com", "amazon.com"}
port := "80"
results := make(chan string, len(hosts))
for _, host := range hosts {
go testConnectivity(host, port, results)
}
for i := 0; i < len(hosts); i++ {
fmt.Println(<-results)
}
}