Do you need help on a specific subject? Use the contact form (Request a blog entry) on the right hand side.
Showing posts with label Xcode8. Show all posts
Showing posts with label Xcode8. Show all posts

2016-10-14

Port Spy

While working on Swiftfire I had the need to see which data actually arrives at a port and which data is actually sent.

Thus I wrote a little utility called Port Spy.



Port Spy is an in-between utility: it listens on one port and connections to a server on the other. All traffic received on the first port is send to the second port and vice versa. Aside from a little delay, there is no interference with the data itself.
This allows Port Spy to display the data in a view, and -if necessary- to write it to file.

Port Spy uses low level socket-io operations and is written completely in Swift.

Obviously Port Spy is primarily useful for developers, thus Port Spy includes its own source code. If you are in need of some example code for socket based IO in Swift, then you can purchase this utility and export the source code (a complete zipped Xcode project actually) from the File menu.

If you have thought about supporting this blog, then you can now do so while getting a nice utility in return!

Oh, a screenshot:



Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2016-09-26

A Q&D error display for the key window

During development it is convenient to have a simple error display routine that shows whatever text you throw into it in the frontmost (key) window.

There is an easy way to accomplish this, just add a global function (for example in the AppDelegate file):

func showErrorInKeyWindow(_ message: String) {
    
    if let window = NSApp.keyWindow {
        
        DispatchQueue.main.async {
            
            let alert = NSAlert()
            alert.messageText = "Error"
            alert.informativeText = message
            alert.addButton(withTitle: "Dismiss")
            alert.beginSheetModal(for: window, completionHandler: nil)
        }
    }
    else {
        log.atLevelError(id: -1, source: #file.source(#function, #line), message: "Could not send error message '\(message)' to key window")
    }

}

Of course you can replace the error logging with a simple "print" statement as long as you are working in Xcode. Otherwise you could use the SwifterLog logging project (free from github, see link at right side)

Now anywhere in your code where you need to flash an error, just call "showErrorInKeyWindow(message)"

(But beware for repeating error's ;-))

Note: Do not use this in shipping code. Yes, you could, but you really should have a something better in place.

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-10-30

Socket Programming in Swift: Part 1 - getaddrinfo

Updated on 2016-08-08 for Swift 3 in Xcode 8 beta 3 & use in playground.

The first thing to mention when blogging about socket programming is that you really, really should read Beej's Guide to Network Programming it's free, so you don't have an excuse...

In fact, I created this series while working through this guide. Thus much of the code in this series is more or less the Swift version of the code in that book. That said, I will not discuss the general nature of socket programming. I could not do a better job that Beej did anyway. This series will focus on the Swift side of things and some Cocoa aspects.

Still I do want to give some perspective first. So here is the sequence of calls to be made to implement the server side of things:

1) getaddrinfo(): To retrieve the information needed to create a socket descriptor.
2) socket(): To create a socket descriptor
3) setsockopt(): To set the options on the socket
4) bind(): To connect the socket descriptor to a local port
5) freeaddrinfo(): To deallocate used resources
6) listen(): To listen for connection requests
7) -- do some cocoa magic
8) accept(): To accept connection requests
9) recv(): To read the data that is received from the client
10) close()

The client side of things will follow in a later series of posts.

In this post: getaddrinfo

This is the code for Swift 3 Xcode 8, copy & paste into Playground:

// Defs for playground purposes

let servicePortNumber = "3333"
let applicationInDebugMode = true

/// Returns the (host, service) tuple for a given sockaddr

func sockaddrDescription(addr: UnsafePointer<sockaddr>) -> (String?, String?) {
    
    var host : String?
    var service : String?
    
    var hostBuffer = [CChar](repeating: 0, count: Int(NI_MAXHOST))
    var serviceBuffer = [CChar](repeating: 0, count: Int(NI_MAXSERV))
    
    if getnameinfo(
        addr,
        socklen_t(addr.pointee.sa_len),
        &hostBuffer,
        socklen_t(hostBuffer.count),
        &serviceBuffer,
        socklen_t(serviceBuffer.count),
        NI_NUMERICHOST | NI_NUMERICSERV)
        
        == 0 {
        
        host = String(cString: hostBuffer)
        service = String(cString: serviceBuffer)
    }
    return (host, service)
    
}


// General purpose status variable, used to detect error returns from socket functions

var status: Int32 = 0


// ==================================================================
// Retrieve the information necessary to create the socket descriptor
// ==================================================================

// Protocol configuration, used to retrieve the data needed to create the socket descriptor

var hints = addrinfo(
    ai_flags: AI_PASSIVE,       // Assign the address of the local host to the socket structures
    ai_family: AF_UNSPEC,       // Either IPv4 or IPv6
    ai_socktype: SOCK_STREAM,   // TCP
    ai_protocol: 0,
    ai_addrlen: 0,
    ai_canonname: nil,
    ai_addr: nil,
    ai_next: nil)


// For the information needed to create a socket (result from the getaddrinfo)

var servinfo: UnsafeMutablePointer<addrinfo>? = nil


// Get the info we need to create our socket descriptor

status = getaddrinfo(
    nil,                        // Any interface
    servicePortNumber,          // The port on which will be listenend
    &hints,                     // Protocol configuration as per above
    &servinfo)                  // The created information


// Cop out if there is an error

if status != 0 {
    var strError: String
    if status == EAI_SYSTEM {
        strError = String(validatingUTF8: strerror(errno)) ?? "Unknown error code"
    } else {
        strError = String(validatingUTF8: gai_strerror(status)) ?? "Unknown error code"
    }
    print(strError)

} else {

   // Print a list of the found IP addresses

   if applicationInDebugMode {
       var info = servinfo
       while info != nil {
           let (clientIp, service) = sockaddrDescription(addr: info!.pointee.ai_addr)
           let message = "HostIp: " + (clientIp ?? "?") + " at port: " + (service ?? "?")
           print(message)
           info = info!.pointee.ai_next
       }
   }   
}

There are a few noteworthy things:
a) I would like to keep the code agnostic with respect to IPv4 or IPv6, thus the use of AF_UNSPEC in the hints structure.
b) Notice that the definition of servinfo only defines a pointer, not the actual structure. It only allocates memory for the pointer, not the structure it points at.
c) The getaddrinfo call is given a pointer to servinfo i.e. a pointer to a pointer. getaddrinfo itself will allocate memory for the structure that servinfo will point at. However after the call to getaddrinfo we "own" the memory that was allocated. And thus must dispose of it later when we no longer need it. (See step 5) (Note: This has nothing to do with ARC, we really need to dispose of the memory ourself otherwise it will create a "memory leak")
d) The servicePortNumber is the port we want the server to listen on for connection requests. A HTTP server would normally listen on port 80.
e) The call to gai_strerror will produce a readable error message, still it is always useful to also have the original error code if we want to google for possible reasons.
f) The call to  uses our (free) SwifterLog error logging mechanism. See the link on the left hand side.
g) The addrinfo structure is recursive, hence when the global variable applicationInDebugMode indicates that the application is in debug mode, it will log a list of all addresses the server is using. These can be IPv4 and IPv6 addresses on multiple network interfaces (multiple ethernet connections, wifi connection, etc)

Socket Programming in Swift: part 2 - socket and setsockopt

Check out my Port Spy app in the App Store. A utility that helps you debug your socket based application and includes its own source code. So you can see first hand how to implement socket based io in Swift. And you will be helping this blog!

Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-08-04

Opening a file in the browser from an OSX-Application

After the holidays lets start off with something simple: opening a file from your application in a browser. For iOS this can simply be done through the sharedApplication.openURL, but this call is not available under OS-X.

In OS-X it has to be done through the NSWorkspace. Otherwise it is almost identical to the method used for iOS:

NSWorkspace.shared().openFile(fileLogPath, withApplication: "Safari")

Note that this is not the same as in iOS. Here we have to specify explicitly in which application the file has to be openend. Where in iOS we can simply request to open a URL. It is possible to skip the "withApplication:" parameter in OS-X as well, but then the default app will be used for the extension of the file. Which can be irksome if for example the file in question is an XML file that we want to show in the browser, but would open in an XML editor (like XCode). Also keep in mind tat the user might want a different default browser than Safari, hence it would make sense to keep the "withApplication:" parameter configurable.

If we only want to open an URL in a browser, the syntax can in fact be a little easier:

        let url = URL(string: "http://www.balancingrock.nl")!
        NSWorkspace.shared().open(helpUrl)


Happy coding...

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.

2015-03-27

Using the Info.plist

Every application on OS-X has a Info.plist file. When writing a utility like SwifterLog I find it nicer if the log levels can be set in a plist rather than in code.

But then it is necessary to access the Info.plist's properties during initialisation. Luckily Apple has made this easy. I use the following code to achieve this:

   init() {
        
        // Try to read the settings from the app's Info.plist
        
        if  let infoPlist = Bundle.main.infoDictionary,
            let config = infoPlist["SwifterLog"] as? Dictionary<String, AnyObject> {
            
                if let als = config["aslThreshold"] as? NSNumber {
                    if als.intValue >= Level.debug.rawValue &&
                       als.intValue <= Level.none.rawValue {
                        aslThreshold = Level(rawValue: als.intValue)!
                    } else {
                        // "Info.plist value for aslThreshold in SwifterLog out of bounds"
                    }

                }
                ....
        }

The corresponding entries in the plist file look as follows:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
...
<key>SwifterLog</key>
<dict>
<key>aslThreshold</key>
<integer>8</integer>
<key>logfileThreshold</key>
<integer>8</integer>
<key>stdoutThreshold</key>
<integer>0</integer>
<key>logfileMaxSizeInBytes</key>
<integer>1000000</integer>
<key>logfileMaxNumberOfFiles</key>
<integer>20</integer>
<key>logfileDirectoryPath</key>
<string></string>
</dict>
</dict>

</plist>

As you can see, I have added a dictionary item "SwifterLog" to the Info.plist file, and in that dictionary the configuration items for SwifterLog.

Consequently, in the source code I first need to gain access to the Info.plist, then the SwifterLog dictionary and then to the configuration items.
Swift allows us to encapsulate this nicely by using the conditional assignment. Notice that this also ensures that when the Info.plist does not contain a SwifterLog dictionary the default values in the code will be used. So the programmer has the choice of using the Info.plist, setting the configuration values in code, or simply using the default values.

Since errors are easily made, it is recommended to check the values in the Info.plist file before assigning them to the configuration parameters. This can save hours of bug-hunting!

Btw: Please note that I have manually changed the above code to be more compact for display purposes on screen. It is no longer identical to the swifterLog code. But you can check that out yourself by downloading SwifterLog...

Using the Info.plist is a nice enough feature, but when you code-sign your application it is no longer possible to change the Info.plist after distribution. While the end-user can edit the Info.plist file, GateKeeper won't start the application if the Info.plist is modified. If you need the capability for the end-user to modify plist values, you are out of luck. Unless you distribute the application without code-signing. I.e not through the App-store. Which of course can only be done for OS-X applications, not iOS applications.

Happy coding

Did this help?, then please help out a small independent.
If you decide that you want to make a small donation, you can do so by clicking this
link: a cup of coffee ($2) or use the popup on the right hand side for different amounts.
Payments will be processed by PayPal, receiver will be sales at balancingrock dot nl
Bitcoins will be gladly accepted at: 1GacSREBxPy1yskLMc9de2nofNv2SNdwqH

We don't get the world we wish for... we get the world we pay for.