2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift:macのIP Addressを取得する

Last updated at Posted at 2019-11-04

SandBoxありの場合

import Network

func getIPAddress() {
    var address: String = ""
    var ifaddr: UnsafeMutablePointer<ifaddrs>?
    guard getifaddrs(&ifaddr) == 0 else { return }
    var ptr = ifaddr
    while ptr != nil {
        defer { ptr = ptr?.pointee.ifa_next }
        let interface = ptr?.pointee
        let addrFamily = interface?.ifa_addr.pointee.sa_family
        if addrFamily == UInt8(AF_INET) || addrFamily == UInt8(AF_INET6) {
            if String(cString: (interface?.ifa_name)!) == "en0" {
                var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST))
                let res = getnameinfo(interface?.ifa_addr,
                                      socklen_t((interface?.ifa_addr.pointee.sa_len)!),
                                      &hostname,
                                      socklen_t(hostname.count),
                                      nil,
                                      socklen_t(0),
                                      NI_NUMERICHOST)
                if res == 0 {
                    let str = String(cString: hostname)
                    if isIPAddress(str) {
                        address = str
                    }
                }
            }
        }
    }
    freeifaddrs(ifaddr)
    Swift.print(address)
}

func isIPAddress(_ address: String) -> Bool {
    let pattern = "^[\\d.]+$"
    return address.range(of: pattern, options: .regularExpression,
                         range: nil, locale: .current) != nil
}

SandBoxなしでいい場合

import Foundation

var ip: String {
    let process = Process()
    process.launchPath = "/usr/sbin/ipconfig"
    process.arguments = ["getifaddr", "en0"]
    
    let pipe = Pipe()
    process.standardOutput = pipe
    process.standardError = pipe
    process.launch()
    
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    return String(data: data, encoding: .utf8) ?? "No connection"
}

参照

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?