iosswiftsocketsportasyncsocket

iOS Swift: How to check if port is open


In my application want to check port is open or not. Here refer this link

iOS SDK: How can I check if a port is open?

But dnt get any solution. And also refer these two github source,

https://github.com/swiftsocket/SwiftSocket

https://github.com/robbiehanson/CocoaAsyncSocket

But dnt any solution. Any one help how check port is open or not. Thanks Advance.


Solution

  • Please use the below method to port is open or not

    func isPortOpen(port: in_port_t) -> Bool {
    
        let socketFileDescriptor = socket(AF_INET, SOCK_STREAM, 0)
        if socketFileDescriptor == -1 {
            return false
        }
    
        var addr = sockaddr_in()
        let sizeOfSockkAddr = MemoryLayout<sockaddr_in>.size
        addr.sin_len = __uint8_t(sizeOfSockkAddr)
        addr.sin_family = sa_family_t(AF_INET)
        addr.sin_port = Int(OSHostByteOrder()) == OSLittleEndian ? _OSSwapInt16(port) : port
        addr.sin_addr = in_addr(s_addr: inet_addr("0.0.0.0"))
        addr.sin_zero = (0, 0, 0, 0, 0, 0, 0, 0)
        var bind_addr = sockaddr()
        memcpy(&bind_addr, &addr, Int(sizeOfSockkAddr))
    
        if Darwin.bind(socketFileDescriptor, &bind_addr, socklen_t(sizeOfSockkAddr)) == -1 {
            return false
        }
        if listen(socketFileDescriptor, SOMAXCONN ) == -1 {
            return false
        }
        return true
    }
    

    Use like:

    let port = UInt16(10000)
    print(isPortOpen(port:port))