Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can i get clients ip address on UDP server in golang?

Tags:

ip-address

go

udp

I run a udp server successfully on go

func main() {
    service := "0.0.0.0:27014"
    udpAddr, err := net.ResolveUDPAddr("udp4", service)
    checkError(err)
    conn, err := net.ListenUDP("udp", udpAddr)
    checkError(err)
    for {
        handleClient(conn)
    }
}

But i Wanted to know how can i find out who(remote ip address, Client ip address) send request to my server

like image 309
Amir Mahmoudi Avatar asked Jun 15 '14 16:06

Amir Mahmoudi


People also ask

How does UDP find IP?

When IP delivers a UDP datagram, the host checks the port number and delivers the data to the corresponding application. In this way, UDP provides simple multiplexing over IP to allow a host to send and receive data on multiple distinct ports.

Is there client and server in UDP?

In UDP, the client does not form a connection with the server like in TCP and instead just sends a datagram. Similarly, the server need not accept a connection and just waits for datagrams to arrive. Datagrams upon arrival contain the address of the sender which the server uses to send data to the correct client.

Does Golang support TCP and UDP protocol?

UDP vs TCP in golang: client implementation If we use interfaces, implementing a client should be the same on both the TCP and the UDP versions. Let's see how. net. Dial() returns the Conn interface, which in turn supports Read and Write methods.

Can UDP client communicate with TCP server?

No, you can't have a TCP server communicating with UDP clients.


1 Answers

In connected mode, you can use the LocalAddr() and RemoteAddr() methods of the connection object.

In disconnected (i.e. classical) mode, you get the address information with the datagram itself using one of the following methods:

func (c *UDPConn) ReadFrom(b []byte) (int, Addr, error)
ReadFrom implements the PacketConn ReadFrom method.

func (c *UDPConn) ReadFromUDP(b []byte) (n int, addr *UDPAddr, err error)
ReadFromUDP reads a UDP packet from c, copying the payload into b. It returns the number of bytes copied into b and the return address that was on the packet.

func (c *UDPConn) ReadMsgUDP(b, oob []byte) (n, oobn, flags int, addr *UDPAddr, err error)
ReadMsgUDP reads a packet from c, copying the payload into b and the associated out-of-band data into oob. It returns the number of bytes copied into b, the number of bytes copied into oob, the flags that were set on the packet and the source address of the packet.

The address information is part of the return values in the signature of these methods.

like image 154
Didier Spezia Avatar answered Oct 05 '22 23:10

Didier Spezia