John Smith
John Smith

Reputation: 591

Convert IP-Address to Binary (UInt32)

I have an IP address in a Stringformat, so "192.168.0.1".

I want to convert this string to a binary/bit version, so that I get a Uint32 out of it. In this case 16820416

I've found multiple tutorials online how to convert a bit version to a String like here:

let ipAddress = 16820416

public var ipAddressString: String {
    var bytes = [UInt32]()
    bytes.append(self.ipAddress & 0xFF)
    bytes.append((self.ipAddress >> 8) & 0xFF)
    bytes.append((self.ipAddress >> 16) & 0xFF)
    bytes.append((self.ipAddress >> 24) & 0xFF)

    return "\(bytes[0]).\(bytes[1]).\(bytes[2]).\(bytes[3])" //192.168.0.1
}

My Question: How can I do the exact opposite of this?

Upvotes: 0

Views: 3230

Answers (2)

Martin R
Martin R

Reputation: 539865

The inet_pton() function ...

... converts a presentation format address (that is, printable form as held in a character string) to network format (usually a struct in_addr or some other internal binary representation, in network byte order).

Example:

let addrString = "192.168.0.1"
var addr = in_addr()
if inet_pton(AF_INET, addrString, &addr) == 1 {
    let ipAddress = addr.s_addr

    print(ipAddress) // 16820416
    print(String(format:"%#08x", ipAddress)) // 0x100a8c0
} else {
    print("invalid address")
}

All socket address structures use "network byte order" (= big-endian). If you want the IP address in the host byte order (= little-endian) then use

    let ipAddress = UInt32(bigEndian: addr.s_addr)

    print(ipAddress) // 3232235521
    print(String(format:"%#08x", ipAddress)) // 0xc0a80001

Upvotes: 5

Duncan C
Duncan C

Reputation: 131426

Use components(separatedBy:) to divide the string into 4 parts. Then add each part in turn into a total, shifting the previous total by 8 bits each time:

let ipString = "192.168.1.12"
let values = ipString.components(separatedBy: ".").flatMap{Int($0)}

var result = 0
for aValue in values {
  result = result << 8 + aValue
}
print(String(format:"%X", result))

Or going "full functional:"

let ipString = "192.168.1.12"
let result = ipString.components(separatedBy: ".").flatMap{Int($0)}.reduce(0, 
{ x, y in
  x << 8 + y
})

Or making it as short and cryptic as possible:

let ipString = "192.168.1.12"
let result = ipString.components(separatedBy: ".").flatMap{Int($0)}.reduce(0) { $0 << 8 + $1 }

Upvotes: 1

Related Questions