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
+8.3k Golang : Terminate-stay-resident or daemonize your program?
+11.1k Golang : convert(cast) string to integer value
+18.3k Golang : Check if os.Stdin input data is piped or from terminal
+5.5k Golang : Calculate diameter, circumference, area, sphere surface and volume
+6.9k Golang : Check from web if Go application is running or not
+14.1k Golang : Get digits from integer before and after given position example
+31.2k Golang : How to check if a date is within certain range?
+13.3k Golang : Parsing or breaking down URL
+8.2k Golang : Detect number of active displays and the display's resolution
+8.2k Golang : Create unique title slugs example
+6.3k Golang : Word limiter example
+29.6k error: trying to remove "yum", which is protected