Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Convert IP address to dot syntax from unsigned integer in iOS
//
// UInt32+IPv4String.swift
// Cybertk
//
// Created by Quanlong He on 8/14/15.
// Copyright © 2015 Quanlong He. All rights reserved.
//
import Foundation
extension UInt32 {
public func IPv4String() -> String {
let ip = self
let byte1 = UInt8(ip & 0xff)
let byte2 = UInt8((ip>>8) & 0xff)
let byte3 = UInt8((ip>>16) & 0xff)
let byte4 = UInt8((ip>>24) & 0xff)
return "\(byte1).\(byte2).\(byte3).\(byte4)"
}
}
@IdoBn

This comment has been minimized.

Copy link

@IdoBn IdoBn commented May 28, 2020

The above is incorrect... It will result in a reverse ordered IP.
To fix this simply change the return value to be as follows:

return "\(byte4).\(byte3).\(byte2).\(byte1)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment