sourdesi
sourdesi

Reputation: 380

How to find IP:Port of incoming client in TCP Connection

After receiving a connection from conn, err := listener.Accept(), I want to find the address of the client at the other end of the conn. I've tried doing this with conn.LocalAddr() and conn.RemoteAddr() (Documentation). .LocalAddr() just gives the address of the server's process. .RemoteAddr() gives the right IP for the client but a very different port number from what I know the client to be binded to. If it makes any difference, Im doing this with two separate processes running on the same machine. One is a client, one is a server. Any ideas as to how else I can find the correct IP:Port of the client? Am I to use either LocalAddr or RemoteAddr?

Upvotes: 2

Views: 11698

Answers (2)

freeformz
freeformz

Reputation: 896

On OSX, using go 1.4 the host / port combo reported by conn.RemoteAddr() is correct when compared against netstat output.

package main

import (
  "fmt"
  "net"
  "time"
)

func main() {
  ln, err := net.Listen("tcp", ":8080")
  if err != nil {
    panic(err)
  }
  for {
    conn, err := ln.Accept()
    if err != nil {
      panic(err)
    }
    fmt.Println(conn.RemoteAddr())
    time.Sleep(time.Minute)
    conn.Close()
  }
}

$ go run foo.go
127.0.0.1:63418

$ netstat -an | grep 8080
tcp4       0      0  127.0.0.1.8080         127.0.0.1.63418        ESTABLISHED
tcp4       0      0  127.0.0.1.63418        127.0.0.1.8080         ESTABLISHED

Upvotes: 7

Gregg Dotoli
Gregg Dotoli

Reputation: 1

netstat -a 1 -f in the windows shell. I'm a command line guy, this works, write it to a file via redirect. This will rerun every second, the f is to resolve DNS name.

Upvotes: -4

Related Questions