本文整理匯總了Golang中net.TCPAddr類的典型用法代碼示例。如果您正苦於以下問題:Golang TCPAddr類的具體用法?Golang TCPAddr怎麽用?Golang TCPAddr使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
在下文中一共展示了TCPAddr類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: GetOriginalDst
// GetOriginalDst returns original destination of Conn
func GetOriginalDst(c net.Conn) (string, error) {
tcp, ok := c.(*net.TCPConn)
if !ok {
return "", errors.New("socket is not tcp")
}
file, err := tcp.File()
if err != nil {
return "", err
}
defer file.Close()
sa, err := syscall.Getsockname(int(file.Fd()))
if err != nil {
return "", err
}
var addr net.TCPAddr
if v, ok := sa.(*syscall.SockaddrInet4); ok {
addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port}
} else if v, ok := sa.(*syscall.SockaddrInet6); ok {
addr = net.TCPAddr{IP: v.Addr[0:], Port: v.Port, Zone: zoneToString(int(v.ZoneId))}
} else {
return "", errors.New("socket is not ipv4")
}
return addr.String(), nil
}
示例2: makeNewNode
func makeNewNode(host string, port int) (*node, error) {
var (
resolvedAddress *net.TCPAddr
err error
)
if resolvedAddress, err = net.ResolveTCPAddr("tcp", net.JoinHostPort(host, strconv.Itoa(port))); err != nil {
return nil, err
}
newNode := new(node)
newNode.SetAddress(resolvedAddress)
if host == "" {
return nil, ErrNotYetImplemented
} else {
newNode.baseKey = hashString(resolvedAddress.String())
}
entries := M()
newNode.fingerTable = make([]*tableEntry, entries, entries)
for row := 0; row < entries; row++ {
newNode.SetTableEntry(row, nil)
}
newNode.dataStorage = make(map[string][]byte)
newNode.backupStorageOfPredecessorsData = make(map[string][]byte)
newNode.backupStorageOfSuccessorsData = make(map[string][]byte)
newNode.aliasStorage = make(map[string]string)
newNode.backupStorageOfPredecessorsAliases = make(map[string]string)
newNode.backupStorageOfSuccessorsAliases = make(map[string]string)
newNode.wgs = new(waitGroups)
return newNode, nil
}
示例3: MakeConn
func MakeConn(ip string) (*net.TCPConn, error) {
var addr net.TCPAddr
addr.IP = net.ParseIP(ip)
addr.Port = Port
c, err := net.DialTCP("tcp4", nil, &addr)
return c, err
}
示例4: ts6_main
func ts6_main(msg chan string, exit chan int) {
// No configuration, so this is fixed.
var addr net.TCPAddr
addr.IP = net.IPv4(127, 0, 0, 1)
addr.Port = 3725
// Start our listener.
l, err := net.ListenTCP("tcp4", &addr)
if err != nil {
fmt.Printf("No bind: %s\n", err)
exit <- 0
} else {
go listen(l)
// Again, no configuration.
addr.Port = 13725
c, err := net.DialTCP("tcp4", nil, &addr)
if err != nil {
fmt.Printf("No connection: %s\n", err)
} else {
go link(c, true)
}
}
// Handle messages.
for message := range msg {
if message == "exit" {
exit <- 0
}
}
}
示例5: sendAndReceiveState
// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte) ([]pushNodeState, []byte, error) {
// Attempt to connect
dialer := net.Dialer{Timeout: m.config.TCPTimeout}
dest := net.TCPAddr{IP: addr, Port: m.config.TCPPort}
conn, err := dialer.Dial("tcp", dest.String())
if err != nil {
return nil, nil, err
}
defer conn.Close()
m.logger.Printf("[INFO] Initiating push/pull sync with: %s", conn.RemoteAddr())
// Send our state
if err := m.sendLocalState(conn); err != nil {
return nil, nil, err
}
// Read remote state
remote, userState, err := m.readRemoteState(conn)
if err != nil {
err := fmt.Errorf("Reading remote state failed: %v", err)
return nil, nil, err
}
// Return the remote state
return remote, userState, nil
}
示例6: main
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s message", os.Args[0])
os.Exit(1)
}
message := os.Args[1]
serverIP := "127.0.0.1" //サーバ側のIP
serverPort := "55555" //サーバ側のポート番號
myIP := "127.0.0.1" //クライアント側のIP
myPort := 55556 //クライアント側のポート番號
tcpAddr, err := net.ResolveTCPAddr("tcp", serverIP+":"+serverPort)
checkError(err)
myAddr := new(net.TCPAddr)
myAddr.IP = net.ParseIP(myIP)
myAddr.Port = myPort
conn, err := net.DialTCP("tcp", myAddr, tcpAddr)
checkError(err)
defer conn.Close()
conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
conn.Write([]byte(message))
readBuf := make([]byte, 1024)
conn.SetReadDeadline(time.Now().Add(10 * time.Second))
readlen, err := conn.Read(readBuf)
checkError(err)
fmt.Println("server: " + string(readBuf[:readlen]))
}
示例7: sendAndReceiveState
// sendAndReceiveState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
// Attempt to connect
dialer := net.Dialer{Timeout: m.config.TCPTimeout}
dest := net.TCPAddr{IP: addr, Port: int(port)}
conn, err := dialer.Dial("tcp", dest.String())
if err != nil {
return nil, nil, err
}
defer conn.Close()
m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)
// Send our state
if err := m.sendLocalState(conn, join); err != nil {
return nil, nil, err
}
conn.SetDeadline(time.Now().Add(m.config.TCPTimeout))
msgType, bufConn, dec, err := m.readTCP(conn)
if err != nil {
return nil, nil, err
}
// Quit if not push/pull
if msgType != pushPullMsg {
err := fmt.Errorf("received invalid msgType (%d), expected pushPullMsg (%d) %s", msgType, pushPullMsg, LogConn(conn))
return nil, nil, err
}
// Read remote state
_, remoteNodes, userState, err := m.readRemoteState(bufConn, dec)
return remoteNodes, userState, err
}
示例8: detailedOutput
// detailedOutput is used to dump all known information about nodes in
// their raw format
func (c *MembersCommand) detailedOutput(members []agent.Member) []string {
result := make([]string, 0, len(members))
header := "Node|Address|Status|Tags"
result = append(result, header)
for _, member := range members {
// Get the tags sorted by key
tagKeys := make([]string, 0, len(member.Tags))
for key := range member.Tags {
tagKeys = append(tagKeys, key)
}
sort.Strings(tagKeys)
// Format the tags as tag1=v1,tag2=v2,...
var tagPairs []string
for _, key := range tagKeys {
tagPairs = append(tagPairs, fmt.Sprintf("%s=%s", key, member.Tags[key]))
}
tags := strings.Join(tagPairs, ",")
addr := net.TCPAddr{IP: member.Addr, Port: int(member.Port)}
line := fmt.Sprintf("%s|%s|%s|%s",
member.Name, addr.String(), member.Status, tags)
result = append(result, line)
}
return result
}
示例9: interfaceURLs
// Generate all publishable URLs for a given HTTP port.
func interfaceURLs(port int) (types.URLs, error) {
allAddrs, err := net.InterfaceAddrs()
if err != nil {
return []url.URL{}, err
}
var allURLs types.URLs
for _, a := range allAddrs {
ip, ok := a.(*net.IPNet)
if !ok || !ip.IP.IsGlobalUnicast() {
continue
}
tcp := net.TCPAddr{
IP: ip.IP,
Port: port,
}
u := url.URL{
Scheme: "http",
Host: tcp.String(),
}
allURLs = append(allURLs, u)
}
if len(allAddrs) == 0 {
return []url.URL{}, fmt.Errorf("no publishable addresses")
}
return allURLs, nil
}
示例10: replyAnnouncePeer
func (d *DHT) replyAnnouncePeer(addr net.UDPAddr, node *remoteNode, r responseType) {
ih := InfoHash(r.A.InfoHash)
if log.V(3) {
log.Infof("DHT: announce_peer. Host %v, nodeID: %x, infoHash: %x, peerPort %d, distance to me %x",
addr, r.A.Id, ih, r.A.Port, hashDistance(ih, InfoHash(d.nodeId)),
)
}
// node can be nil if, for example, the server just restarted and received an announce_peer
// from a node it doesn't yet know about.
if node != nil && d.checkToken(addr, r.A.Token) {
peerAddr := net.TCPAddr{IP: addr.IP, Port: r.A.Port}
d.peerStore.addContact(ih, nettools.DottedPortToBinary(peerAddr.String()))
// Allow searching this node immediately, since it's telling us
// it has an infohash. Enables faster upgrade of other nodes to
// "peer" of an infohash, if the announcement is valid.
node.lastResponseTime = time.Now().Add(-searchRetryPeriod)
if d.peerStore.hasLocalDownload(ih) {
d.PeersRequestResults <- map[InfoHash][]string{ih: []string{nettools.DottedPortToBinary(peerAddr.String())}}
}
}
// Always reply positively. jech says this is to avoid "back-tracking", not sure what that means.
reply := replyMessage{
T: r.T,
Y: "r",
R: map[string]interface{}{"id": d.nodeId},
}
sendMsg(d.conn, addr, reply)
}
示例11: removeDeadFinger
func (thisNode *node) removeDeadFinger(deadAddress *net.TCPAddr) {
// If a connected node disappears, remove it from the finger table.
var closestFinger *net.TCPAddr
for _, entry := range thisNode.fingerTable {
if entry.fingerAddress != nil && entry.fingerAddress.String() == deadAddress.String() {
entry.fingerAddress = nil
} else if entry.fingerAddress != nil && closestFinger == nil {
closestFinger = entry.fingerAddress
}
}
// If it's the predecessor, remove it.
if thisNode.predecessorAddress.String() == deadAddress.String() {
thisNode.predecessorAddress = nil
}
// If there was some other finger, replace it.
if closestFinger != nil {
thisNode.SetSuccessor(closestFinger)
} else if thisNode.predecessorAddress != nil {
// There was no other finger in the table, but maybe as a predecessor?
thisNode.SetSuccessor(thisNode.predecessorAddress)
} else {
// If not, become a singular node ring.
thisNode.MakeIntoRing()
}
}
示例12: ProxyRelay
func ProxyRelay(port string, relays map[string]Relay) error {
tcpAddr := net.TCPAddr{}
tcpAddr.IP = net.ParseIP("127.0.0.1")
tcpAddr.Port, _ = strconv.Atoi(port)
ln, err := net.ListenTCP("tcp", &tcpAddr)
if err != nil {
msg := fmt.Sprintf("Proxy listener error on port %s: %s",
port, err)
LogWriter.Err(msg)
return fmt.Errorf(msg)
}
msg := fmt.Sprintf("Started proxy listener on port: %s",
port)
LogWriter.Info(msg)
defer ln.Close()
for {
conn, err := ln.AcceptTCP()
if err != nil {
msg := fmt.Sprintf("Error accepting TCP connection on port %s: %s",
port, err)
LogWriter.Err(msg)
continue
}
conn.SetKeepAlive(true)
if err != nil {
msg := fmt.Sprintf("Error setting keep-alive on connection: %s",
err)
LogWriter.Err(msg)
}
go acceptClient(conn, relays)
}
return nil
}
示例13: DialTCP
func (p *httpProxyClient) DialTCP(network string, laddr, raddr *net.TCPAddr) (net.Conn, error) {
if laddr != nil || laddr.Port != 0 {
return nil, errors.New("代理協議不支持指定本地地址。")
}
return p.DialTCPSAddr(network, raddr.String())
}
示例14: sendAndReceiveState
// sendState is used to initiate a push/pull over TCP with a remote node
func (m *Memberlist) sendAndReceiveState(addr []byte, port uint16, join bool) ([]pushNodeState, []byte, error) {
// Attempt to connect
dialer := net.Dialer{Timeout: m.config.TCPTimeout}
dest := net.TCPAddr{IP: addr, Port: int(port)}
conn, err := dialer.Dial("tcp", dest.String())
if err != nil {
return nil, nil, err
}
defer conn.Close()
m.logger.Printf("[DEBUG] memberlist: Initiating push/pull sync with: %s", conn.RemoteAddr())
metrics.IncrCounter([]string{"memberlist", "tcp", "connect"}, 1)
// Send our state
if err := m.sendLocalState(conn, join); err != nil {
return nil, nil, err
}
// Read remote state
_, remote, userState, err := m.readRemoteState(conn)
if err != nil {
err := fmt.Errorf("Reading remote state failed: %v", err)
return nil, nil, err
}
// Return the remote state
return remote, userState, nil
}
示例15: CreateTCPSocket
func CreateTCPSocket(proto, addr string) (net.Listener, error) {
var err error
var laddr *net.TCPAddr
laddr, err = net.ResolveTCPAddr(proto, addr)
if err != nil {
return nil, err
}
family, ipv6only := favoriteTCPAddrFamily(proto, laddr, "listen")
var socketAddr syscall.Sockaddr
if socketAddr, err = ipToSockaddr(family, laddr.IP, laddr.Port, laddr.Zone); err != nil {
panic(err)
return nil, err
}
var s int
if s, err = sysSocket(family, syscall.SOCK_STREAM, 0); err != nil {
return nil, err
}
if err = setDefaultSockopts(s, family, syscall.SOCK_STREAM, ipv6only); err != nil {
closesocket(s)
return nil, err
}
if err = setDefaultListenerSockopts(s); err != nil {
closesocket(s)
return nil, err
}
if err = syscall.SetsockoptInt(s, syscall.SOL_SOCKET, SO_REUSEPORT, 1); err != nil {
closesocket(s)
panic(err)
return nil, err
}
if err = syscall.Bind(s, socketAddr); err != nil {
closesocket(s)
return nil, err
}
if err = syscall.Listen(s, maxListenerBacklog()); err != nil {
closesocket(s)
return nil, err
}
file := os.NewFile(uintptr(s), "listener-"+laddr.String())
defer file.Close()
var socketListener net.Listener
if socketListener, err = net.FileListener(file); err != nil {
return nil, err
}
return socketListener, nil
}