Added examples/apple

This commit is contained in:
Joseph Henry
2017-05-30 13:47:50 -07:00
parent 5ab563ce4c
commit c6f20df8da
40 changed files with 4806 additions and 3 deletions

View File

@@ -0,0 +1,46 @@
//
// AppDelegate.swift
// Example_iOS_App
//
// Created by Joseph Henry on 7/10/16.
// Copyright © 2016 ZeroTier Inc. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}

View File

@@ -0,0 +1,73 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "29x29",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "40x40",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "29x29",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "40x40",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "1x"
},
{
"idiom" : "ipad",
"size" : "76x76",
"scale" : "2x"
},
{
"idiom" : "ipad",
"size" : "83.5x83.5",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}

View File

@@ -0,0 +1,27 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15F34" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" launchScreen="YES" useTraitCollections="YES" initialViewController="01J-lp-oVM">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="EHf-IW-A2E">
<objects>
<viewController id="01J-lp-oVM" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="Llm-lL-Icb"/>
<viewControllerLayoutGuide type="bottom" id="xb3-aO-Qok"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="Ze5-6b-2t3">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
</view>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="iYj-Kq-Ea1" userLabel="First Responder" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="53" y="375"/>
</scene>
</scenes>
</document>

View File

@@ -0,0 +1,186 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="10117" systemVersion="15G1004" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" initialViewController="BYZ-38-t0r">
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="10085"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="Example_iOS_App" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="600" height="600"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="sM5-GM-4R8">
<rect key="frame" x="183" y="314" width="59" height="30"/>
<state key="normal" title="Connect"/>
<connections>
<action selector="UI_Connect:" destination="BYZ-38-t0r" eventType="touchUpInside" id="5bz-xp-hzT"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="9Qv-V2-VnT">
<rect key="frame" x="157" y="264" width="46" height="30"/>
<state key="normal" title="Button"/>
</button>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="dwn-d8-Ki3">
<rect key="frame" x="183" y="352" width="31" height="30"/>
<state key="normal" title="Bind"/>
<connections>
<action selector="UI_Bind:" destination="BYZ-38-t0r" eventType="touchUpInside" id="DJq-47-7gO"/>
</connections>
</button>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" text="ip address" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="6id-4C-E8W">
<rect key="frame" x="20" y="275" width="147" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" text="port" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="uiQ-EM-gfq">
<rect key="frame" x="175" y="276" width="97" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Protocol" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Fn2-mn-MjK">
<rect key="frame" x="20" y="149" width="64" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Remote Host" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="9rm-WW-ji2">
<rect key="frame" x="20" y="239" width="100" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Lnh-9e-LMk">
<rect key="frame" x="401" y="281" width="42" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="bqB-xS-7Oo">
<rect key="frame" x="423" y="115" width="97" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<segmentedControl opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="top" segmentControlStyle="plain" selectedSegmentIndex="0" translatesAutoresizingMaskIntoConstraints="NO" id="vwT-sy-CRY">
<rect key="frame" x="38" y="178" width="121" height="29"/>
<segments>
<segment title="TCP"/>
<segment title="UDP"/>
</segments>
<connections>
<action selector="protocolSelected:" destination="BYZ-38-t0r" eventType="valueChanged" id="PpI-tQ-h4C"/>
</connections>
</segmentedControl>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="ZeroTier iOS Example App" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="h4F-YA-Rsh">
<rect key="frame" x="20" y="59" width="200" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="dp1-qj-Mq8">
<rect key="frame" x="160" y="491" width="41" height="30"/>
<state key="normal" title="read()"/>
<connections>
<action selector="UI_RX:" destination="BYZ-38-t0r" eventType="touchUpInside" id="JJJ-KW-5rF"/>
<action selector="UI_TX:" destination="BYZ-38-t0r" eventType="touchUpInside" id="4h0-8L-CI3"/>
</connections>
</button>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="EBa-HV-MZ5">
<rect key="frame" x="20" y="453" width="132" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="ZjP-35-mln">
<rect key="frame" x="160" y="453" width="132" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="RX" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="z5X-D0-I5d">
<rect key="frame" x="165" y="424" width="22" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="TX" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Tho-Qu-UmE">
<rect key="frame" x="20" y="424" width="22" height="21"/>
<fontDescription key="fontDescription" type="system" pointSize="17"/>
<color key="textColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<nil key="highlightedColor"/>
</label>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="BfY-Te-yWV">
<rect key="frame" x="20" y="492" width="45" height="30"/>
<state key="normal" title="write()"/>
<connections>
<action selector="UI_TX:" destination="BYZ-38-t0r" eventType="touchUpInside" id="1ZJ-oI-a98"/>
</connections>
</button>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="IXS-rJ-KKM">
<rect key="frame" x="208" y="94" width="30" height="30"/>
<state key="normal" title="Join"/>
<connections>
<action selector="UI_JoinNetwork:" destination="BYZ-38-t0r" eventType="touchUpInside" id="kem-tf-1h1"/>
</connections>
</button>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="left" contentVerticalAlignment="center" text="nwid" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="TvY-qZ-Zjm">
<rect key="frame" x="20" y="94" width="167" height="30"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
<button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="fU2-IH-aMf">
<rect key="frame" x="208" y="122" width="40" height="30"/>
<state key="normal" title="Leave"/>
<connections>
<action selector="UI_LeaveNetwork:" destination="BYZ-38-t0r" eventType="touchUpInside" id="7Pg-IK-dMo"/>
</connections>
</button>
<label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" usesAttributedText="YES" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Q7W-t2-dqo">
<rect key="frame" x="20" y="28" width="320" height="28"/>
<attributedString key="attributedText">
<fragment content="-1.-1.-1.-1/-1">
<attributes>
<color key="NSColor" red="0.0" green="0.0" blue="0.0" alpha="1" colorSpace="calibratedRGB"/>
<font key="NSFont" size="24" name="HelveticaNeue"/>
</attributes>
</fragment>
</attributedString>
<nil key="highlightedColor"/>
</label>
</subviews>
<color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="calibratedWhite"/>
<variation key="default">
<mask key="subviews">
<exclude reference="9Qv-V2-VnT"/>
<exclude reference="Lnh-9e-LMk"/>
<exclude reference="bqB-xS-7Oo"/>
</mask>
</variation>
</view>
<connections>
<outlet property="btnBind" destination="dwn-d8-Ki3" id="FHu-Jd-wFh"/>
<outlet property="btnConnect" destination="sM5-GM-4R8" id="Qun-r4-1OF"/>
<outlet property="btnJoinNetwork" destination="IXS-rJ-KKM" id="C88-pL-2CT"/>
<outlet property="btnLeaveNetwork" destination="fU2-IH-aMf" id="YwN-GB-2tc"/>
<outlet property="btnRX" destination="dp1-qj-Mq8" id="vVr-s4-AX9"/>
<outlet property="btnTX" destination="BfY-Te-yWV" id="KTA-eE-Rhy"/>
<outlet property="lblAddress" destination="Q7W-t2-dqo" id="m0T-dL-QB1"/>
<outlet property="segmentProtocol" destination="vwT-sy-CRY" id="BcU-8W-7kX"/>
<outlet property="txtAddr" destination="6id-4C-E8W" id="q3w-zX-ZFf"/>
<outlet property="txtNWID" destination="TvY-qZ-Zjm" id="1Jc-3U-PIE"/>
<outlet property="txtPort" destination="uiQ-EM-gfq" id="CXT-Ed-idq"/>
<outlet property="txtRX" destination="ZjP-35-mln" id="tOT-GE-wq8"/>
<outlet property="txtTX" destination="EBa-HV-MZ5" id="WWI-4O-1iT"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="-12" y="326"/>
</scene>
</scenes>
</document>

View File

@@ -0,0 +1,47 @@
<?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>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
<key>UISupportedInterfaceOrientations~ipad</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>

View File

@@ -0,0 +1,295 @@
//
// ViewController.swift
// Example_iOS_App
//
// Created by Joseph Henry on 7/10/16.
// Copyright © 2016 ZeroTier Inc. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let zt = ZTSDK();
var serverPort:Int16 = 8080
var serverAddr:String = "10.9.9.100"
var selectedProtocol:Int32 = 0
var sock:Int32 = -1
var accepted_sock:Int32 = -1
@IBOutlet weak var txtAddr: UITextField!
@IBOutlet weak var txtPort: UITextField!
@IBOutlet weak var txtTX: UITextField!
@IBOutlet weak var txtRX: UITextField!
@IBOutlet weak var btnTX: UIButton!
@IBOutlet weak var btnConnect: UIButton!
@IBOutlet weak var btnBind: UIButton!
@IBOutlet weak var btnRX: UIButton!
@IBAction func UI_RX(sender: AnyObject) {
// Use ordinary read/write calls on ZeroTier socket
// TCP
if(selectedProtocol == SOCK_STREAM) {
var buffer = [UInt8](count: 100, repeatedValue: 0)
read(accepted_sock, &buffer, 100);
print(buffer)
}
// UDP
if(selectedProtocol == SOCK_DGRAM) {
var buffer = [UInt8](count: 100, repeatedValue: 0)
read(Int32(sock), &buffer, 100);
print(buffer)
}
}
@IBAction func UI_TX(sender: AnyObject) {
// Use ordinary read/write calls on ZeroTier socket
// TCP
if(selectedProtocol == SOCK_STREAM) {
write(Int32(sock), txtTX.description, txtTX.description.characters.count);
}
// UDP
if(selectedProtocol == SOCK_DGRAM) {
sendto(Int32(sock), txtTX.description, txtTX.description.characters.count, 0, UnsafePointer<sockaddr>([udp_addr]), UInt32(udp_addr.sin_len))
}
}
@IBOutlet weak var txtNWID: UITextField!
@IBOutlet weak var btnJoinNetwork: UIButton!
@IBAction func UI_JoinNetwork(sender: AnyObject) {
zt.join_network(txtNWID.text!)
}
@IBOutlet weak var btnLeaveNetwork: UIButton!
@IBAction func UI_LeaveNetwork(sender: AnyObject) {
zt.leave_network(txtNWID.text!)
}
@IBOutlet weak var segmentProtocol: UISegmentedControl!
@IBAction func protocolSelected(sender: AnyObject) {
switch sender.selectedSegmentIndex
{
case 0:
selectedProtocol = SOCK_STREAM
case 1:
selectedProtocol = SOCK_DGRAM
default:
break;
}
}
// CONNECT
var connect_thread : NSThread!
func attempt_connect()
{
// TCP
if(selectedProtocol == SOCK_STREAM)
{
sock = zt.socket(AF_INET, SOCK_STREAM, 0)
let ztaddr: ZTAddress = ZTAddress(AF_INET, serverAddr, serverPort)
let connect_err = zt.connect(sock, ztaddr)
print("connect_err = \(connect_err),\(errno)")
if connect_err < 0 {
let err = errno
print("Error connecting IPv4 socket \(err)")
return
}
}
// UDP
if(selectedProtocol == SOCK_DGRAM)
{
}
}
// Connect to remote host on ZeroTier virtual network
@IBAction func UI_Connect(sender: AnyObject) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.connect_thread = NSThread(target:self, selector:#selector(ViewController.attempt_connect), object:nil)
self.connect_thread.start()
});
}
// BIND
var bind_thread : NSThread!
func attempt_bind()
{
var err:Int32
// TCP
if(selectedProtocol == SOCK_STREAM)
{
sock = zt_socket(AF_INET, SOCK_STREAM, 0)
let ztaddr: ZTAddress = ZTAddress(AF_INET, serverAddr, serverPort)
let bind_err = zt.bind(sock, ztaddr)
print("bind_err = \(bind_err),\(errno)")
if bind_err < 0 {
let err = errno
print("Error binding IPv4 socket \(err)")
return
}
// Put socket into listening state
zt_listen(Int32(sock), 1);
while(accepted_sock < 0) {
accepted_sock = zt.accept(sock, ztaddr)
}
print("accepted connection")
}
// UDP
if(selectedProtocol == SOCK_DGRAM)
{
let ztaddr: ZTAddress = ZTAddress(AF_INET, serverAddr, serverPort)
sock = zt_socket(AF_INET, SOCK_DGRAM, 0)
err = zt.bind(sock, ztaddr)
print("bind_err = ", err)
err = zt.listen(sock, 0)
print("listen_err = ", err)
}
}
@IBOutlet weak var txtAddress: UITextField!
// Bind a ZeroTier socket
@IBAction func UI_Bind(sender: AnyObject) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.bind_thread = NSThread(target:self, selector:#selector(ViewController.attempt_bind), object:nil)
self.bind_thread.start()
});
}
@IBOutlet weak var lblAddress: UILabel!
var udp_addr:sockaddr_in!
// Watch for incoming data
var rx_thread : NSThread!
func update_rx() {
while(true)
{
sleep(1)
dispatch_async(dispatch_get_main_queue()) {
var str_buf = [Int8](count: 16, repeatedValue: 0)
self.zt.get_ipv4_address(self.txtNWID.text!, &str_buf)
self.lblAddress.text = String.fromCString(str_buf)
print("addr = ", String.fromCString(str_buf))
}
// TCP
if(selectedProtocol == SOCK_STREAM)
{
let len = 32
var buffer = [UInt8](count: len, repeatedValue: 0)
let n = read(accepted_sock, &buffer, len);
if(n > 0)
{
if let str = String(data: NSData(bytes: &buffer, length: len), encoding: NSUTF8StringEncoding) {
dispatch_async(dispatch_get_main_queue()) {
self.txtRX.text = str
}
} else {
print("not a valid UTF-8 sequence")
}
}
}
// UDP
/*
if(selectedProtocol == SOCK_DGRAM)
{
let len = 32
var buffer = [UInt8](count: len, repeatedValue: 0)
//udp_addr = sockaddr_in(sin_len: UInt8(sizeof(sockaddr_in)),
// sin_family: UInt8(AF_INET),
// sin_port: UInt16(0).bigEndian,
// sin_addr: in_addr(s_addr: 0),
// sin_zero: (0,0,0,0,0,0,0,0))
//var addrlen:socklen_t = 0;
//var legIntPtr = withUnsafeMutablePointer(&addrlen, { $0 })
//let n = recvfrom(sock, &buffer, len, 0, UnsafeMutablePointer<sockaddr>([udp_addr]), legIntPtr)
var socketAddress = sockaddr_storage()
var socketAddressLength = socklen_t(sizeof(sockaddr_storage.self))
let bytesRead = withUnsafeMutablePointers(&socketAddress, &socketAddressLength) {
recvfrom(sock, UnsafeMutablePointer<Void>(buffer), len, 0, UnsafeMutablePointer($0), UnsafeMutablePointer($1))
//recvfrom(<#T##Int32#>, <#T##UnsafeMutablePointer<Void>#>, <#T##Int#>, <#T##Int32#>, <#T##UnsafeMutablePointer<sockaddr>#>, <#T##UnsafeMutablePointer<socklen_t>#>)
}
if(bytesRead > 0)
{
print("socketAddressLength = ", socketAddressLength);
let bytesWritten = withUnsafePointer(&socketAddress) {
print("TXing...\n");
sendto(sock, UnsafePointer(buffer), bytesRead, 0, UnsafePointer<sockaddr>($0), socketAddressLength)
}
print("bytesWritten = ", bytesWritten);
//let bytesWritten = withUnsafePointer(&socketAddress.sin) {
// sendto(sock, buffer, len, 0, UnsafePointer($0), socklen_t(socketAddress.sin.sin_len))
//}
if let str = String(data: NSData(bytes: &buffer, length: len), encoding: NSUTF8StringEncoding) {
dispatch_async(dispatch_get_main_queue()) {
self.txtRX.text = str
}
} else {
print("not a valid UTF-8 sequence")
}
}
}
*/
}
}
override func viewDidLoad() {
super.viewDidLoad()
txtNWID.text = "8056c2e21c000001"
txtTX.text = "welcome to the machine"
txtAddr.text = "0.0.0.0"
serverAddr = "0.0.0.0"
txtPort.text = "8080"
serverPort = 8080
selectedProtocol = SOCK_STREAM
print("Starting ZeroTier...\n");
zt.start_service(nil);
print("Joining network...\n");
zt.join_network(txtNWID.text!);
print("Complete\n");
// UI RX update
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), {
self.rx_thread = NSThread(target:self, selector:#selector(ViewController.update_rx), object:nil)
self.rx_thread.start()
});
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}