golang int to IP

WBOY
Release: 2023-05-10 09:38:06
Original
863 people have browsed it

In Golang, we often need to convert an integer type IP address to a string type IP address, or conversely, convert a string type IP address to an integer type IP address.

Golang provides convenient library functions to achieve this conversion. IP conversion from integer type to string type and from string type to integer type can be completed using the following functions and methods.

Convert an IP address of integer type to an IP address of string type:

func IntToIP(ip uint32) net.IP {
    return net.IPv4(byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip))
}
Copy after login

This function converts an unsigned integer IP address (uint32) to an IPv4 address and returns a net.IP type structure. We can convert the IP address to a string type by using the String() method.

Usage example:

ip := uint32(3232235876) // 对应IP地址为192.168.1.100
ipAddr := IntToIP(ip)
fmt.Println(ipAddr.String()) // output: "192.168.1.100"
Copy after login

Convert a string type IP address to an integer type IP address:

func IPToInt(ip net.IP) uint32 {
    return binary.BigEndian.Uint32(ip.To4())
}
Copy after login

This function accepts an IP address (net.IP type) As a parameter, and returns the corresponding unsigned integer type (uint32). Inside the function, we use the binary.BigEndian.Uint32() function to convert the IPv4 address to a 32-bit unsigned integer.

Usage example:

ipStr := "192.168.1.100"
ipAddr := net.ParseIP(ipStr)
ipInt := IPToInt(ipAddr)
fmt.Println(ipInt) // output: 3232235876
Copy after login

Summary:

In this article, we discussed converting integer type IP address to string type IP address in Golang and a method to convert an IP address of string type to an IP address of integer type. We used the net.IP type and binary.BigEndian.Uint32() function provided by Golang to achieve this conversion. This is a very common operation in network programming and system management. These functions and methods can make Golang development more convenient and efficient.

The above is the detailed content of golang int to IP. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template