source: launchers/macosx/I2PLauncher/routermgmt/NetworkUtil.swift @ 7cb0c9b

Last change on this file since 7cb0c9b was 7cb0c9b, checked in by meeh <meeh@…>, 15 months ago

Mac OSX Launcher: Router management/healthcheck code updates.

  • Property mode set to 100644
File size: 1.7 KB
Line 
1//
2//  NetworkUtil.swift
3//  I2PLauncher
4//
5//  Created by Mikal Villa on 07/04/2019.
6//  Copyright © 2019 The I2P Project. All rights reserved.
7//
8
9import Foundation
10
11class NetworkUtil {
12  static func checkTcpPortForListen(host: String = "127.0.0.1", port: in_port_t = 7657) -> (Bool, descr: String){
13   
14    let socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0)
15    if socketFileDescriptor == -1 {
16      return (false, "SocketCreationFailed, \(descriptionOfLastError())")
17    }
18   
19    var addr = sockaddr_in()
20    let sizeOfSockkAddr = MemoryLayout<sockaddr_in>.size
21    addr.sin_len = __uint8_t(sizeOfSockkAddr)
22    addr.sin_family = sa_family_t(AF_INET)
23    addr.sin_port = Int(OSHostByteOrder()) == OSLittleEndian ? _OSSwapInt16(port) : port
24    addr.sin_addr = in_addr(s_addr: inet_addr(host))
25    addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
26    var bind_addr = sockaddr()
27    memcpy(&bind_addr, &addr, Int(sizeOfSockkAddr))
28   
29    if Darwin.bind(socketFileDescriptor, &bind_addr, socklen_t(sizeOfSockkAddr)) == -1 {
30      let details = descriptionOfLastError()
31      release(socket: socketFileDescriptor)
32      return (false, "\(port), BindFailed, \(details)")
33    }
34    if listen(socketFileDescriptor, SOMAXCONN ) == -1 {
35      let details = descriptionOfLastError()
36      release(socket: socketFileDescriptor)
37      return (false, "\(port), ListenFailed, \(details)")
38    }
39    release(socket: socketFileDescriptor)
40    return (true, "\(port) is free for use")
41  }
42 
43  static func release(socket: Int32) {
44    Darwin.shutdown(socket, SHUT_RDWR)
45    close(socket)
46  }
47  static func descriptionOfLastError() -> String {
48    return String(cString: UnsafePointer(strerror(errno)))
49  }
50}
Note: See TracBrowser for help on using the repository browser.