This article describes how to correctly specify the local IP address when using the net.DialTCP function of the Go language. When trying to specify a local IP address, you may encounter a "dial tcp [IP address]:[port number]: An invalid argument was supplied" error. This article will explain the cause of this problem and provide the correct solution.
Use net.DialTCP to specify the local IP address
When using the net.DialTCP function, the first parameter is the network type (eg "tcp"), the second parameter is the local address (laddr), and the third parameter is the remote address (raddr). In the problem description, I tried to use the net.DialTCP function to specify the local IP address, but encountered the "An invalid argument was supplied" error.
package main import ( "fmt" "net" ) func main() { var localaddr net.TCPAddr var remoteaddr net.TCPAddr localaddr.IP = net.ParseIP("192.168.1.104") localaddr.Port = 6000 remoteaddr.IP = net.ParseIP("192.168.1.104") remoteaddr.Port = 5000 if localaddr.IP == nil || remoteaddr.IP == nil { fmt.Println("error") } if _, err := net.DialTCP("tcp", &localaddr, &remoteaddr); err != nil { fmt.Println(err) } fmt.Println("End") }
The above code snippet will report errors in some cases because Go's net package handles local addresses differently than some other implementations.
solution
When connecting to the local host, the net package allows the use of port numbers to simplify the specification of addresses. The following two ways of writing are equivalent:
- :5000
-
:5000
Therefore, when the destination address is a local address, the port number can be used directly instead of the full IP address and port number. However, it should be noted that in the net.DialTCP function, the laddr parameter still requires a net.TCPAddr structure.
Here is the corrected code example:
package main import ( "fmt" "net" ) func main() { remoteaddr, err := net.ResolveTCPAddr("tcp", "192.168.1.104:5000") if err != nil { fmt.Println("ResolveTCPAddr error:", err) return } // If you need to specify the local address and port, you can create a TCPAddr structure localaddr, err := net.ResolveTCPAddr("tcp", "192.168.1.104:6000") if err != nil { fmt.Println("ResolveTCPAddr error:", err) return } conn, err := net.DialTCP("tcp", localaddr, remoteaddr) if err != nil { fmt.Println("DialTCP error:", err) return } defer conn.Close() fmt.Println("Connected to:", conn.RemoteAddr()) }
In this revised example, we use the net.ResolveTCPAddr function to parse the address string and convert it into a net.TCPAddr structure. If you need to specify a local address, use the same method to resolve it.
Things to note
- Make sure that the local IP address specified is a valid IP address on the machine.
- If you do not need to specify a local IP address, you can set the laddr parameter to nil and let the system automatically select it.
- In practical applications, errors need to be handled according to specific circumstances, such as network connection errors, address resolution errors, etc.
Summarize
This article describes how to correctly specify the local IP address when using the net.DialTCP function of the Go language. You can avoid "An invalid argument was supplied" errors by using the net.ResolveTCPAddr function to resolve the address string. At the same time, attention should also be paid to handling possible errors to ensure the robustness of the program.
The above is the detailed content of Specify local IP address using net.DialTCP in Go. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Goprovidessimpleandefficientfilehandlingusingtheosandbufiopackages.Toreadasmallfileentirely,useos.ReadFile,whichloadsthecontentintomemorysafelyandautomaticallymanagesfileoperations.Forlargefilesorincrementalprocessing,bufio.Scannerallowsline-by-liner

struct{} is a fieldless structure in Go, which occupies zero bytes and is often used in scenarios where data is not required. It is used as a signal in the channel, such as goroutine synchronization; 2. Used as a collection of value types of maps to achieve key existence checks in efficient memory; 3. Definable stateless method receivers, suitable for dependency injection or organization functions. This type is widely used to express control flow and clear intentions.

GracefulshutdownsinGoapplicationsareessentialforreliability,achievedbyinterceptingOSsignalslikeSIGINTandSIGTERMusingtheos/signalpackagetoinitiateshutdownprocedures,thenstoppingHTTPserversgracefullywithhttp.Server’sShutdown()methodtoallowactiverequest

Use the encoding/json package of the standard library to read the JSON configuration file; 2. Use the gopkg.in/yaml.v3 library to read the YAML format configuration; 3. Use the os.Getenv or godotenv library to overwrite the file configuration; 4. Use the Viper library to support advanced functions such as multi-format configuration, environment variables, automatic reloading; it is necessary to define the structure to ensure type safety, properly handle file and parsing errors, correctly use the structure tag mapping fields, avoid hard-coded paths, and recommend using environment variables or safe configuration storage in the production environment. It can start with simple JSON and migrate to Viper when the requirements are complex.

CGOenablesGotocallCcode,allowingintegrationwithClibrarieslikeOpenSSL,accesstolow-levelsystemAPIs,andperformanceoptimization;itrequiresimporting"C"withCheadersincomments,usesC.function()syntax,anddemandscarefulmemorymanagement.However,CGOinc

This article aims to resolve the "undefined" error encountered in Go when trying to use strconv.Itoa64 for integer-to-string conversion. We will explain why Itoa64 does not exist and give details on the correct alternative to strconv.FormatInt in the strconv package. Through instance code, readers will learn how to efficiently and accurately convert integer types into string representations in specified partitions, avoid common programming traps and improve code robustness and readability.

Install the sqlcCLI tool, it is recommended to use curl scripts or Homebrew; 2. Create a project structure, including db/schema.sql (table structure), db/query.sql (annotated query) and sqlc.yaml configuration files; 3. Define database tables in schema.sql; 4. Write SQL queries with --name:annotation and :exec/:one/:many directives in query.sqlc.yaml; 5. Configure sqlc.yaml to specify package paths, query files, schema files, database engines and generation options; 6. Run sqlcgenerate to generate type-safe Go code, including models, query methods and interfaces

Implements JSON serialization and deserialization of customizable Go structures for MarshalJSON and UnmarshalJSON, suitable for handling non-standard formats or compatible with old data. 2. Control the output structure through MarshalJSON, such as converting field formats; 3. Parsing special format data through UnmarshalJSON, such as custom dates; 4. Pay attention to avoid infinite loops caused by recursive calls, and use type alias to bypass custom methods.
