Created
August 8, 2024 09:49
-
-
Save cmsong-shina/f108b96ea4274906e1c0d9ed9a16c79c to your computer and use it in GitHub Desktop.
udp sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"net" | |
"os" | |
"time" | |
) | |
func main() { | |
// Check if at least 3 arguments are passed | |
if len(os.Args) < 4 { | |
fmt.Println("Usage: ./udp [--broadcast] <IP> <Port> <Message>") | |
return | |
} | |
// Determine if broadcasting is needed | |
broadcast := false | |
args := os.Args[1:] | |
if args[0] == "--broadcast" { | |
broadcast = true | |
args = args[1:] // Shift arguments if broadcast flag is present | |
} | |
// Extract IP, port, and message from command line arguments | |
ip := args[0] | |
port := args[1] | |
message := args[2] | |
// Resolve the UDP address | |
address := net.JoinHostPort(ip, port) | |
udpAddr, err := net.ResolveUDPAddr("udp", address) | |
if err != nil { | |
fmt.Println("Error resolving address:", err) | |
return | |
} | |
// Dial the UDP connection | |
conn, err := net.DialUDP("udp", nil, udpAddr) | |
if err != nil { | |
fmt.Println("Error dialing UDP connection:", err) | |
return | |
} | |
defer conn.Close() | |
// TODO: broadcast | |
_ = broadcast | |
// Send the message | |
_, err = conn.Write([]byte(message)) | |
if err != nil { | |
fmt.Println("Error sending message:", err) | |
return | |
} | |
fmt.Println("Message sent to", address) | |
// Set a 10-second timeout for the response | |
conn.SetReadDeadline(time.Now().Add(10 * time.Second)) | |
// Buffer to hold the response | |
buffer := make([]byte, 1024) | |
// Read the response | |
n, addr, err := conn.ReadFromUDP(buffer) | |
if err != nil { | |
fmt.Println("No response received within 10 seconds or an error occurred:", err) | |
return | |
} | |
fmt.Printf("Received response from %s: %s\n", addr, string(buffer[:n])) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment