func NewLilyConn(address string) *LilyConn { localAddress, _ := net.ResolveTCPAddr("0.0.0.0:0") lilyAddress, err := net.ResolveTCPAddr(address) if err != nil { logger.Logf("failed resolving %s: %s", address, err) return nil } tcpConn, err := net.DialTCP("tcp", localAddress, lilyAddress) if err != nil { logger.Logf("failed connecting to %s: %s", address, err) return nil } var newLilyConn LilyConn newLilyConn.tcpConn = tcpConn newLilyConn.textConn = textproto.NewConn(tcpConn) newLilyConn.incomingChannel = make(chan *LilyMessage, 100) newLilyConn.outgoingChannel = make(chan *LilyMessage, 100) newLilyConn.handleMap = make(map[string]*LilyHandle) newLilyConn.SendOptions() go newLilyConn.Dispatch() return &newLilyConn }
func (c *Client) Start() { addr, err := net.ResolveTCPAddr("tcp", c.host) if !HandleError("Failed to resolve", err) { return } laddr, err := net.ResolveTCPAddr("tcp", ":0") if !HandleError("Failed to resolve", err) { return } conn, err := net.DialTCP("tcp", laddr, addr) if !HandleError("Failed to connect", err) { return } go listen(conn) go keepAlive(conn) bind := Bind(1, PDU_COMMAND_BIND_TX, c.username, c.password, "GO-SMPP", 0, 1, 1, "") data := bind.Pack() fmt.Printf("Wrote %d bytes\n", len(data)) conn.Write(data) c.conn = conn }
func (app *Application) Init() error { httpAddr, err := net.ResolveTCPAddr("tcp", app.Options.HTTPAddress) if err != nil { return err } app.httpAddr = httpAddr httpListener, err := net.Listen("tcp", app.httpAddr.String()) if err != nil { return err } app.httpListener = httpListener apiAddr, err := net.ResolveTCPAddr("tcp", app.Options.APIAddress) if err != nil { return err } app.apiAddr = apiAddr apiListener, err := net.Listen("tcp", app.apiAddr.String()) if err != nil { return err } app.apiListener = apiListener vhosts := NewVirtualHost(app.Options.Root, app.Logger) if err := vhosts.Load(); err != nil { return err } app.vhosts = vhosts forwarder, err := forward.New(forward.Logger(app.Logger)) if err != nil { return err } app.forwarder = forwarder reverser, err := reverse.New(app.forwarder, reverse.Route(app.vhosts), reverse.Logger(app.Logger)) if err != nil { return err } app.reverser = reverser app.api = NewAPIController(app.vhosts) appid_dft, _ := util.AlphaStringRange(24, 32) secret_dft, _ := util.AlphaStringRange(32, 36) app.Configs.SetSection("forward") appid := app.Configs.StringDefault("appid", appid_dft) secret := app.Configs.StringDefault("secret", secret_dft) acl := app.Configs.BoolDefault("acl.enable", true) signature := app.api.sign(secret, appid) app.Info("application signature (%s)", signature) app.api.acl(acl) if err := app.Configs.Save(""); err != nil { return err } return nil }
func main() { addr, _ := net.ResolveTCPAddr(os.Args[2]) _, serverComp, clients, err := RunServer(addr) if err != nil { print("server error\n") print(err.String()) os.Exit(1) } address, err := net.ResolveTCPAddr(os.Args[1]) client := NewClient(address) clientComp, err := client.Run() if err != nil { print("client error\n") print(err.String()) os.Exit(1) } <-clientComp for i := range clients { <-i } //killServer<-true <-serverComp }
func getResolvedAddresses(localHost, remoteHost *string) (*net.TCPAddr, *net.TCPAddr) { laddr, err := net.ResolveTCPAddr("tcp", *localHost) check(err) raddr, err := net.ResolveTCPAddr("tcp", *remoteHost) check(err) return laddr, raddr }
func tcp_talk() { rAddr, err := net.ResolveTCPAddr("tcp", "129.241.187.23:33546") CheckError(err) conn, err := net.DialTCP("tcp", nil, rAddr) CheckError(err) defer conn.Close() conn.Write([]byte("HelloWorld!\000")) laddr, err := net.ResolveTCPAddr("tcp4", ":30000") CheckError(err) listen, err := net.ListenTCP("tcp", laddr) CheckError(err) listen.SetDeadline(time.Now().Add(2 * time.Second)) defer listen.Close() //conn.Write([]byte("Connect to: 129.241.187.144:30000\000")) //conn.Write([]byte("Connect to: 129.241.187.144:30000\000")) deadline := time.Now().Add(2 * time.Second) for time.Now().Before(deadline) { conn2, err := listen.Accept() if err != nil { fmt.Fprintln(os.Stderr, "Socket acceptance error: "+err.Error()) continue } defer conn2.Close() } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0]) flag.PrintDefaults() fmt.Fprintln(os.Stderr, " -h : show help usage") } flag.Parse() if *ip == "" && *iface != "" { *ip = getIpFromInterface(*iface) } else { log.Fatal("IP address or Interface must be specified") } var servers []string if *dnsServers == "" { log.Fatal("DNS servers must be specified") } servers = strings.Split(*dnsServers, " ") r := &resolver.Resolver{Servers: servers, LocalAddr: *ip} proxy := goproxy.NewProxyHttpServer() proxy.Verbose = *verbose proxy.Tr.Dial = func(network, addr string) (c net.Conn, err error) { if network == "tcp" { var remoteAddr *net.TCPAddr var err error localAddr, err := net.ResolveTCPAddr(network, *ip+":0") if err != nil { return nil, err } chunks := strings.Split(addr, ":") addrIp, err := r.LookupAddr(chunks[0]) if err != nil { remoteAddr, err = net.ResolveTCPAddr(network, addr) } else { remoteAddr, err = net.ResolveTCPAddr(network, addrIp+":"+chunks[1]) } if err != nil { return nil, err } return net.DialTCP(network, localAddr, remoteAddr) } return net.Dial(network, addr) } go http.ListenAndServe(*listen, proxy) log.Printf("DaisyProxy listen on %s outgoing from %s\n", *listen, *ip) select {} }
func (tcpClient *TcpClient) Connect(addr string) error { var err error tcpClient.tcpAddr, err = net.ResolveTCPAddr("tcp", addr) if err != nil { elog.LogSysln(addr, ":resolve tcp addr fail, please usage: 0.0.0.1:2345, fail: ", err) return err } var localaddr *net.TCPAddr localaddr, err = net.ResolveTCPAddr("tcp", "0.0.0.0") conn, err := net.DialTCP("tcp", localaddr, tcpClient.tcpAddr) if err != nil { elog.LogSysln("connect server , because :", err) return err } tcpClient.isConnection = true tcpClient.conn, err = NewConn(conn, tcpClient.eventDispatch, tcpClient.waitGroup) if tcpClient.connCb != nil { tcpClient.connCb(tcpClient.conn) } //开始处理网络 go tcpClient.conn.handleEvent() return err }
func main() { // localAddr := "localhost:3389" // 监听localhost时只能本机访问,别的电脑访问不了。 localAddr := ":3389" // 不指定IP,本机和其它电脑都可以访问到。 remoteAddr := "192.168.102.60:3389" lAddr, err := net.ResolveTCPAddr("tcp", localAddr) if err != nil { panic(err) } rAddr, err := net.ResolveTCPAddr("tcp", remoteAddr) if err != nil { panic(err) } listener, err := net.ListenTCP("tcp", lAddr) if err != nil { panic(err) } log.Println("listen::", localAddr) for { conn, err := listener.AcceptTCP() if err != nil { panic(err) } go handleTCPProxy(conn, rAddr) } }
// SetConfig validates, sets given configuration and resolv listen and daemon // addresses using new configuration variables. func (proxy *GitProxy) SetConfig(config zhash.Hash) error { listenAddrString, err := config.GetString("git", "listen") if err != nil { return err } daemonAddrString, err := config.GetString("git", "daemon") if err != nil { return err } storageDir, err := config.GetString("storage") if err != nil { return err } listenAddr, err := net.ResolveTCPAddr("tcp", listenAddrString) if err != nil { return err } daemonAddr, err := net.ResolveTCPAddr("tcp", daemonAddrString) if err != nil { return err } proxy.storageDir = storageDir proxy.listenAddr = listenAddr proxy.daemonAddr = daemonAddr return nil }
func newProxy(proto, ip, port string) (proxy.Proxy, error) { var ( rAddr net.Addr lAddr net.Addr err error ) switch proto { case "tcp", "tcp6", "tcp4": rAddr, err = net.ResolveTCPAddr(proto, fmt.Sprintf("%s:%s", ip, port)) if err != nil { return nil, err } lAddr, err = net.ResolveTCPAddr(proto, fmt.Sprintf("0.0.0.0:%s", port)) if err != nil { return nil, err } case "udp", "udp4", "udp6": rAddr, err = net.ResolveUDPAddr(proto, fmt.Sprintf("%s:%s", ip, port)) if err != nil { return nil, err } lAddr, err = net.ResolveUDPAddr(proto, fmt.Sprintf("0.0.0.0:%s", port)) if err != nil { return nil, err } default: return nil, fmt.Errorf("Unsupported proto: %s", proto) } return proxy.NewProxy(lAddr, rAddr) }
func (s *RTcpForwardServer) Serve() error { if len(s.Base.Chain.nodes) == 0 { return errors.New("rtcp: at least one -F must be assigned") } laddr, err := net.ResolveTCPAddr("tcp", s.Base.Node.Addr) if err != nil { return err } raddr, err := net.ResolveTCPAddr("tcp", s.Base.Node.Remote) if err != nil { return err } retry := 0 for { conn, err := s.Base.Chain.GetConn() if err != nil { glog.V(LWARNING).Infof("[rtcp] %s - %s : %s", laddr, raddr, err) time.Sleep((1 << uint(retry)) * time.Second) if retry < 5 { retry++ } continue } retry = 0 if err := s.connectRTcpForward(conn, laddr, raddr); err != nil { conn.Close() time.Sleep(6 * time.Second) } } }
func NewTCPJSONHandler(a *giles.Archiver, addPort, queryPort, subscribePort int) *TCPJSONHandler { var err error t := &TCPJSONHandler{a: a, errors: make(chan error)} t.addAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(addPort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", addPort, err) } t.addConn, err = net.ListenTCP("tcp", t.addAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } t.queryAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(queryPort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", queryPort, err) } t.queryConn, err = net.ListenTCP("tcp", t.queryAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } t.subscribeAddr, err = net.ResolveTCPAddr("tcp", ":"+strconv.Itoa(subscribePort)) if err != nil { log.Fatalf("Error resolving TCPJSON address %v (%v)", subscribePort, err) } t.subscribeConn, err = net.ListenTCP("tcp", t.subscribeAddr) if err != nil { log.Fatalf("Error listening to TCP (%v)", err) } return t }
func (s *PeerSuite) TestResolveRecoverAddr(c *gc.C) { for _, testHostPort := range []string{"147.26.10.11:11370", "[fe80::d0dd:7dff:fefc:a828]:11370"} { reconAddr, err := net.ResolveTCPAddr("tcp", testHostPort) c.Assert(err, gc.IsNil) testHost, _, err := net.SplitHostPort(testHostPort) c.Assert(err, gc.IsNil) c.Assert(reconAddr.Port, gc.Equals, 11370) r := &Recover{ RemoteAddr: reconAddr, RemoteConfig: &Config{ HTTPPort: 8080, }, } hkpHostPort, err := r.HkpAddr() c.Assert(err, gc.IsNil) hkpAddr, err := net.ResolveTCPAddr("tcp", hkpHostPort) c.Assert(err, gc.IsNil) hkpHost, _, err := net.SplitHostPort(hkpHostPort) c.Assert(err, gc.IsNil) c.Assert(hkpAddr.Port, gc.Equals, 8080) c.Assert(reconAddr.IP, gc.DeepEquals, hkpAddr.IP) c.Assert(testHost, gc.Equals, hkpHost) } }
func hostEqual(proto string, h1 string, h2 string) bool { // TODO: check all local addresses if h1 is 0.0.0.0 if h1 == h2 { return true } if proto[:3] == "udp" { a1, err := net.ResolveUDPAddr(proto, h1) if err != nil { return false } a2, err := net.ResolveUDPAddr(proto, h2) if err != nil { return false } return a1.IP.Equal(a2.IP) && a1.Zone == a2.Zone && a1.Port == a2.Port } else if proto[:3] == "tcp" { a1, err := net.ResolveTCPAddr(proto, h1) if err != nil { return false } a2, err := net.ResolveTCPAddr(proto, h2) if err != nil { return false } return a1.IP.Equal(a2.IP) && a1.Zone == a2.Zone && a1.Port == a2.Port } return false }
func getResolvedAddresses(localHost, remoteHost, remotePort *string) (*net.TCPAddr, *net.TCPAddr) { laddr, err := net.ResolveTCPAddr("tcp", *localHost) check(err) raddr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%s:%s", *remoteHost, *remotePort)) check(err) return laddr, raddr }
func default_dialer(proto, laddr, raddr string, timeout time.Duration) (net.Conn, error) { if proto == "" { if strings.IndexRune(raddr, ':') != -1 { proto = "tcp" } else { proto = "unix" } } // Make a connection d := &net.Dialer{Timeout: timeout} if laddr != "" { var err error switch proto { case "tcp", "tcp4", "tcp6": d.LocalAddr, err = net.ResolveTCPAddr(proto, laddr) case "unix": d.LocalAddr, err = net.ResolveTCPAddr(proto, laddr) default: err = net.UnknownNetworkError(proto) } if err != nil { return nil, err } } return d.Dial(proto, raddr) }
func TestScan(t *testing.T) { // Define some local constants over1, _ := net.ResolveTCPAddr("tcp", "127.0.0.3:33333") over2, _ := net.ResolveTCPAddr("tcp", "127.0.0.5:55555") ipnet1 := &net.IPNet{ IP: over1.IP, Mask: over1.IP.DefaultMask(), } ipnet2 := &net.IPNet{ IP: over2.IP, Mask: over2.IP.DefaultMask(), } // Start up two bootstrappers bs1, evs1, err := New(ipnet1, []byte("magic"), big.NewInt(1), over1.Port) if err != nil { t.Fatalf("failed to create first booter: %v.", err) } if err := bs1.Boot(); err != nil { t.Fatalf("failed to boot first booter: %v.", err) } defer bs1.Terminate() bs2, evs2, err := New(ipnet2, []byte("magic"), big.NewInt(2), over2.Port) if err != nil { t.Fatalf("failed to create second booter: %v.", err) } if err := bs2.Boot(); err != nil { t.Fatalf("failed to boot second booter: %v.", err) } defer bs2.Terminate() // Wait and make sure they found each other and not themselves e1, e2 := <-evs1, <-evs2 if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port { t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2) } if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port { t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1) } // Each should report twice (foreign request + foreign response to local request) e1, e2 = <-evs1, <-evs2 if !e1.Addr.IP.Equal(over2.IP) || e1.Addr.Port != over2.Port { t.Fatalf("invalid address on first booter: have %v, want %v.", e1.Addr, over2) } if !e2.Addr.IP.Equal(over1.IP) || e2.Addr.Port != over1.Port { t.Fatalf("invalid address on second booter: have %v, want %v.", e2.Addr, over1) } // Further beats shouldn't arrive (unless the probing catches us, should be rare) timeout := time.Tick(250 * time.Millisecond) select { case <-timeout: // Do nothing case a := <-evs1: t.Fatalf("extra address on first booter: %v.", a) case a := <-evs2: t.Fatalf("extra address on second booter: %v.", a) } }
func newProxy(listenAddr string, remoteAddr string) (*proxy, error) { l, e := net.ResolveTCPAddr("tcp", listenAddr) if e != nil { return nil, e } addrList := strings.Split(remoteAddr, ",") if len(addrList) == 0 { return nil, errors.New("empty remote address") } ra := make([]*net.TCPAddr, len(addrList)) for i, v := range addrList { r, e := net.ResolveTCPAddr("tcp", v) if e != nil { return nil, e } ra[i] = r } return &proxy{ listenAddr: l, remoteAddr: ra, }, nil }
func NewTCPListener(ircd *Ircd, address string, port int, config *tls.Config) (*TCPListener, os.Error) { var listener net.Listener secure := Insecure // Go is slightly silly here. The IPv6 form, in Go, is "[::1]:6667" whereas // the IPv4 form is "127.0.0.1:6667". Let's try to satisfy both parties by // firstly trying with 'a:6667' and if that fails retry with '[a]:6667'. finalAddress, error := net.ResolveTCPAddr("TCP", address) if error != nil { finalAddress, error = net.ResolveTCPAddr("TCP", fmt.Sprintf("[%s]:%d", address, port)) if error != nil { return nil, error } } listener, error = net.ListenTCP(finalAddress.Network(), finalAddress) if error != nil { return nil, error } if config != nil { listener = tls.NewListener(listener, config) secure = Secure } bl := NewBasicListener(ircd) bl.listener = listener bl.secure = secure return &TCPListener{bl}, nil }
func main() { flag.Parse() if *showVersion { fmt.Printf("nsqlookupd v%s\n", util.BINARY_VERSION) return } signalChan := make(chan os.Signal, 1) exitChan := make(chan int) go func() { <-signalChan exitChan <- 1 }() signal.Notify(signalChan, os.Interrupt) tcpAddr, err := net.ResolveTCPAddr("tcp", *tcpAddress) if err != nil { log.Fatal(err) } httpAddr, err := net.ResolveTCPAddr("tcp", *httpAddress) if err != nil { log.Fatal(err) } log.Printf("nsqlookupd v%s", util.BINARY_VERSION) lookupd = NewNSQLookupd() lookupd.tcpAddr = tcpAddr lookupd.httpAddr = httpAddr lookupd.Main() <-exitChan lookupd.Exit() }
/** * Create connection to server using unix socket or tcp/ip then setup buffered reader/writer */ func (handlerSocket *HandlerSocket) connect() (err error) { localAddress, _ := net.ResolveTCPAddr("tcp", "0.0.0.0:0") targetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.readPort) wrTargetAddress := fmt.Sprintf("%s:%d", handlerSocket.auth.host, handlerSocket.auth.writePort) hsAddress, err := net.ResolveTCPAddr("tcp", targetAddress) hsWrAddress, err := net.ResolveTCPAddr("tcp", wrTargetAddress) handlerSocket.conn, err = net.DialTCP("tcp", localAddress, hsAddress) handlerSocket.wrConn, err = net.DialTCP("tcp", localAddress, hsWrAddress) if handlerSocket.Logging { log.Print("Connected using TCP/IP") } handlerSocket.in = make(chan HandlerSocketResponse) handlerSocket.out = make(chan HandlerSocketCommandWriter) handlerSocket.wrIn = make(chan HandlerSocketResponse) handlerSocket.wrOut = make(chan HandlerSocketCommandWriter) go handlerSocket.reader(handlerSocket.conn) go handlerSocket.writer(handlerSocket.conn) go handlerSocket.wrreader(handlerSocket.wrConn) go handlerSocket.wrwriter(handlerSocket.wrConn) indexes = make(map[int][]string, 10) handlerSocket.connected = true return }
func TestAgent_CheckAdvertiseAddrsSettings(t *testing.T) { c := nextConfig() c.AdvertiseAddrs.SerfLan, _ = net.ResolveTCPAddr("tcp", "127.0.0.42:1233") c.AdvertiseAddrs.SerfWan, _ = net.ResolveTCPAddr("tcp", "127.0.0.43:1234") c.AdvertiseAddrs.RPC, _ = net.ResolveTCPAddr("tcp", "127.0.0.44:1235") dir, agent := makeAgent(t, c) defer os.RemoveAll(dir) defer agent.Shutdown() serfLanAddr := agent.consulConfig().SerfLANConfig.MemberlistConfig.AdvertiseAddr if serfLanAddr != "127.0.0.42" { t.Fatalf("SerfLan is not properly set to '127.0.0.42': %s", serfLanAddr) } serfLanPort := agent.consulConfig().SerfLANConfig.MemberlistConfig.AdvertisePort if serfLanPort != 1233 { t.Fatalf("SerfLan is not properly set to '1233': %d", serfLanPort) } serfWanAddr := agent.consulConfig().SerfWANConfig.MemberlistConfig.AdvertiseAddr if serfWanAddr != "127.0.0.43" { t.Fatalf("SerfWan is not properly set to '127.0.0.43': %s", serfWanAddr) } serfWanPort := agent.consulConfig().SerfWANConfig.MemberlistConfig.AdvertisePort if serfWanPort != 1234 { t.Fatalf("SerfWan is not properly set to '1234': %d", serfWanPort) } rpc := agent.consulConfig().RPCAdvertise if rpc != c.AdvertiseAddrs.RPC { t.Fatalf("RPC is not properly set to %v: %s", c.AdvertiseAddrs.RPC, rpc) } }
// TODO(barakmich): Currently ignores priority and weight (as they don't make as much sense for a bootstrap) // Also doesn't do any lookups for the token (though it could) // Also sees each entry as a separate instance. func SRVGetCluster(name, dns string, defaultToken string, apurls types.URLs) (string, string, error) { stringParts := make([]string, 0) tempName := int(0) tcpAPUrls := make([]string, 0) // First, resolve the apurls for _, url := range apurls { tcpAddr, err := net.ResolveTCPAddr("tcp", url.Host) if err != nil { log.Printf("discovery: Couldn't resolve host %s during SRV discovery", url.Host) return "", "", err } tcpAPUrls = append(tcpAPUrls, tcpAddr.String()) } updateNodeMap := func(service, prefix string) error { _, addrs, err := lookupSRV(service, "tcp", dns) if err != nil { return err } for _, srv := range addrs { host := net.JoinHostPort(srv.Target, fmt.Sprintf("%d", srv.Port)) tcpAddr, err := net.ResolveTCPAddr("tcp", host) if err != nil { log.Printf("discovery: Couldn't resolve host %s during SRV discovery", host) continue } n := "" for _, url := range tcpAPUrls { if url == tcpAddr.String() { n = name } } if n == "" { n = fmt.Sprintf("%d", tempName) tempName += 1 } stringParts = append(stringParts, fmt.Sprintf("%s=%s%s", n, prefix, tcpAddr.String())) log.Printf("discovery: Got bootstrap from DNS for %s at host %s to %s%s", service, host, prefix, tcpAddr.String()) } return nil } failCount := 0 err := updateNodeMap("etcd-server-ssl", "https://") if err != nil { log.Printf("discovery: Error querying DNS SRV records for _etcd-server-ssl %s", err) failCount += 1 } err = updateNodeMap("etcd-server", "http://") if err != nil { log.Printf("discovery: Error querying DNS SRV records for _etcd-server %s", err) failCount += 1 } if failCount == 2 { log.Printf("discovery: SRV discovery failed: too many errors querying DNS SRV records") return "", "", err } return strings.Join(stringParts, ","), defaultToken, nil }
func main() { if len(os.Args) < 4 { showHelp() return } local, err := net.Listen("tcp", os.Args[1]) if err != nil { log.Fatalf("Listen error: %s", err) } log.Printf("Listening on %s", os.Args[1]) remoteHTTPAddr, err := net.ResolveTCPAddr("tcp", os.Args[2]) if err != nil { log.Fatalf("Resolve remoteHTTP address error: %s", err) } remoteTCPAddr, err := net.ResolveTCPAddr("tcp", os.Args[3]) if err != nil { log.Fatalf("Resolve remoteTCP address error: %s", err) } for { conn, err := local.Accept() if err != nil { log.Printf("Accept failed: %s", err) } go handleConn(conn, remoteHTTPAddr, remoteTCPAddr) } }
// makePort creates a new communication port and return a listener for this. func (ftp *FTP) makePort() (listener net.Listener, err error) { tcpAddr := ftp.conn.LocalAddr() network := tcpAddr.Network() var la *net.TCPAddr if la, err = net.ResolveTCPAddr(network, tcpAddr.String()); err != nil { return } // get the new address newad := la.IP.String() + ":0" // any available port ftp.writeInfo("The new local address in makePort is:", newad) listening := runServer(newad, network) list := <-listening // wait for server to start and accept if list == nil { return nil, errors.New("Unable to create listener") } la, _ = net.ResolveTCPAddr(list.Addr().Network(), list.Addr().String()) ftp.writeInfo("Trying to listen locally at: ", la.IP.String(), " on new port:", la.Port) _, err = ftp.SendPort(la.IP.String(), la.Port) return list, err }
func (d *IpAddr) ToTCPAddr(port string) (*net.TCPAddr, error) { ip := net.IP(*d) if ip.To4() == nil { return net.ResolveTCPAddr("tcp", "["+ip.String()+"]:"+port) } return net.ResolveTCPAddr("tcp", ip.String()+":"+port) }
func initPeers(dir string) { nextDefrag = time.Now().Add(defragEvery) peerDB, _ = qdb.NewDB(dir + "peers") if peerDB.Count() == 0 { if !*testnet { initSeeds([]string{"seed.bitcoin.sipa.be", "dnsseed.bluematt.me", "dnsseed.bitcoin.dashjr.org", "bitseed.xf2.org"}, 8333) } else { initSeeds([]string{"testnet-seed.bitcoin.petertodd.org", "testnet-seed.bluematt.me"}, 18333) } println("peerDB initiated with ", peerDB.Count(), "seeds") } if *proxy != "" { oa, e := net.ResolveTCPAddr("tcp4", *proxy) if e != nil { if strings.HasPrefix(e.Error(), "missing port in address") { oa, e = net.ResolveTCPAddr("tcp4", fmt.Sprint(*proxy, ":", DefaultTcpPort)) } if e != nil { println(e.Error()) os.Exit(1) } } proxyPeer = new(onePeer) proxyPeer.Services = 1 copy(proxyPeer.Ip4[:], oa.IP[0:4]) proxyPeer.Port = uint16(oa.Port) } }
func main() { localAddr := ":3391" // 监听本机3391端口 remoteAddr := "192.168.7.109:7171" // 7171端口的rds服务应该是未加密的 cer, err := tls.LoadX509KeyPair("server.pem", "server.key") if err != nil { log.Println(err) return } config := &tls.Config{Certificates: []tls.Certificate{cer}} lAddr, err := net.ResolveTCPAddr("tcp", localAddr) if err != nil { panic(err) } rAddr, err := net.ResolveTCPAddr("tcp", remoteAddr) if err != nil { panic(err) } listener, err := net.ListenTCP("tcp", lAddr) if err != nil { panic(err) } defer listener.Close() for { conn, err := listener.Accept() if err != nil { log.Println(err) continue } go handleConnection(conn, config, rAddr) } }
func CreateClient(uid uint64, password string) { RECONNECTION: //tcpAddr, err := net.ResolveTCPAddr("tcp", "192.168.20.51:9100") tcpAddr, err := net.ResolveTCPAddr("tcp", "112.74.66.141:9100") //tcpAddr, err := net.ResolveTCPAddr("tcp", "112.74.66.141:9100") //tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:9100") if err != nil { fmt.Println(err) return } clientIP := fmt.Sprintf("127.%v.%v.%v:0", rand.Uint32()%255, rand.Uint32()%255, rand.Uint32()%255) locAddr, err := net.ResolveTCPAddr("tcp", clientIP) if err != nil { panic(err) } connClient, err := net.DialTCP("tcp", locAddr, tcpAddr) if err != nil { fmt.Println(err) return } client := &Client{ conn: connClient, uid: uid, } log.Println("connect start:", *client) err = client.recvPkg() if err != nil && err != io.EOF { log.Println(err, *client) return goto RECONNECTION } else if err != nil { panic(err) } log.Println("connect end:", *client) // 先登录 client.execArgs("10102", uid, password) client.recvPkg() cur_count++ go client.run() //select {} time.Sleep(3 * time.Minute) for { // 跑业务 //second := time.Duration(rand.Uint32()%150) + 30 time.Sleep(time.Second * 60) if client.sid == 0 { continue } uid := int(rand.Uint32())%cur_count + MIN_UID g_rwMutex.RLock() _, ok := g_client_map[uint64(uid)] g_rwMutex.RUnlock() if ok { client.execArgs("30101", uid) } } client.Close() }