Golang : Get UDP client IP address and differentiate clients by port number
Problem :
Your UDP server program needs to find out the UDP client IP address before writing to client. However, you are not able to find out the client IP address from net.UDPConn.RemoteAddr()
For instance:
conn *net.UDPConn
clientIP := conn.RemoteAddr()
fmt.Println(clientIP) // <---- returns NIL
Solution :
Your UDP server must first receive data from the UDP client before the server is able to find out the client IP address. There are ReadFrom()
, ReadFromUDP()
and ReadMsgUDP()
functions that your server will probably use to read the UDP data from client. These functions will return the source Addr
( https://golang.org/pkg/net/#Addr) that you can use to extract client IP address.
For example :
buffer := make([]byte, 1024)
n, addr, err := conn.ReadFromUDP(buffer)
fmt.Println("UDP client : ", addr)
IF you have more than one client connection connecting from the same client machine and you need to distinguish them, use the port numbers to differentiate the client programs.
For example :
Client 1 program :
UDP client : 127.0.0.1:63937
Client 2 program :
UDP client : 127.0.0.1:52132
NOTE : See UDP client server example at https://socketloop.com/tutorials/golang-udp-client-server-read-write-example
References :
https://golang.org/pkg/net/#UDPConn.ReadFrom
See also : Golang : UDP client server read write example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+15.6k Golang : Read large file with bufio.Scanner cause token too long error
+10.9k Golang : How to pipe input data to executing child process?
+7.3k Golang : Rename part of filename
+14.9k nginx: [emerg] unknown directive "ssl"
+5.2k Golang : If else example and common mistake
+13.9k Android Studio : Use image as AlertDialog title with custom layout example
+9.6k Golang : Sort and reverse sort a slice of integers
+21k Golang : How to read float value from standard input ?
+10.2k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+19.2k Golang : Example for DSA(Digital Signature Algorithm) package functions
+13.7k Javascript : Prompt confirmation before exit
+33.3k Golang : All update packages with go get command