added java example

This commit is contained in:
Joseph Henry
2017-05-04 13:06:39 -07:00
parent 64f2634960
commit 890e32e88b
29 changed files with 673 additions and 75 deletions

1
examples/README.md Normal file
View File

@@ -0,0 +1 @@
Language bindings

View File

@@ -0,0 +1,3 @@
Clojure Language Binding API for the ZeroTier SDK
======

3
examples/cpp/README.md Normal file
View File

@@ -0,0 +1,3 @@
C\C++ Language Binding API for the ZeroTier SDK
======

185
examples/cpp/simple.cpp Normal file
View File

@@ -0,0 +1,185 @@
// Comprehensive stress test for socket-like API
#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <arpa/inet.h>
#include <string.h>
#include <netinet/in.h>
#include <netdb.h>
#include "ZeroTierSDK.h"
int main()
{
char *nwid = (char *)"e5cd7a9e1c0fd272";
// Get ZeroTier core version
char ver[ZT_VER_STR_LEN];
zts_core_version(ver);
printf("zts_core_version = %s\n", ver);
// Get SDK version
zts_sdk_version(ver);
printf("zts_sdk_version = %s\n", ver);
// Spawns a couple threads to support ZeroTier core, userspace network stack, and generates ID in ./zt
zts_start("./zt");
// Print the device/app ID (this is also the ID you'd see in ZeroTier Central)
char id[ZT_ID_LEN + 1];
zts_get_device_id(id);
printf("id = %s\n", id);
// Get the home path of this ZeroTier instance, where we store identity keys, conf files, etc
char homePath[ZT_HOME_PATH_MAX_LEN+1];
zts_get_homepath(homePath, ZT_HOME_PATH_MAX_LEN);
printf("homePath = %s\n", homePath);
// Wait for ZeroTier service to start
while(!zts_service_running()) {
printf("wating for service to start\n");
sleep(1);
}
// Join a network
zts_join_network(nwid);
// Wait for ZeroTier service to issue an address to the device on the given network
while(!zts_has_address("e5cd7a9e1c0fd272")) {
printf("waiting for service to issue an address\n");
sleep(1);
}
// Begin Socket API calls
int err;
int sockfd;
int port = 7878;
struct sockaddr_in addr;
// socket()
if((sockfd = zts_socket(AF_INET, SOCK_STREAM, 0)) < 0)
printf("error creating ZeroTier socket");
else
printf("sockfd = %d\n", sockfd);
// connect() IPv6
if(false)
{
struct hostent *server = gethostbyname2("fde5:cd7a:9e1c:0fd2:7299:9367:5993:3b86",AF_INET6);
struct sockaddr_in6 serv_addr;
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin6_flowinfo = 0;
serv_addr.sin6_family = AF_INET6;
memmove((char *) &serv_addr.sin6_addr.s6_addr, (char *) server->h_addr, server->h_length);
serv_addr.sin6_port = htons( port );
if((err = zts_connect(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr))) < 0) {
printf("error connecting to remote host (%d)\n", err);
return -1;
}
}
// connect() IPv4
if(true)
{
addr.sin_addr.s_addr = inet_addr("10.9.9.20");
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
if((err = zts_connect(sockfd, (const struct sockaddr *)&addr, sizeof(addr))) < 0) {
printf("error connecting to remote host (%d)\n", err);
return -1;
}
zts_write(sockfd, "hello", 5);
sleep(3);
zts_close(sockfd);
}
// bind() ipv4
if(false)
{
//addr.sin_addr.s_addr = INADDR_ANY; // TODO: Requires significant socket multiplexer work
addr.sin_addr.s_addr = inet_addr("10.9.9.40");
addr.sin_family = AF_INET;
addr.sin_port = htons( port );
if((err = zts_bind(sockfd, (const struct sockaddr *)&addr, sizeof(addr))) < 0) {
printf("error binding to interface (%d)\n", err);
return -1;
}
zts_listen(sockfd, 1);
struct sockaddr_in client;
int c = sizeof(struct sockaddr_in);
int accept_fd = zts_accept(sockfd, (struct sockaddr *)&client, (socklen_t*)&c);
printf("reading from buffer\n");
char newbuf[32];
memset(newbuf, 0, 32);
read(accept_fd, newbuf, 20);
printf("newbuf = %s\n", newbuf);
}
// End Socket API calls
// Get the ipv4 address assigned for this network
char addr_str[ZT_MAX_IPADDR_LEN];
zts_get_ipv4_address(nwid, addr_str, ZT_MAX_IPADDR_LEN);
printf("ipv4 = %s\n", addr_str);
zts_get_ipv6_address(nwid, addr_str, ZT_MAX_IPADDR_LEN);
printf("ipv6 = %s\n", addr_str);
printf("peer_count = %lu\n", zts_get_peer_count());
while(1)
{
sleep(1);
}
// ---
/*
"Tap Multiplexer"
- socket() [BEFORE JOIN]: take requests for new sockets
- Create them, and store them in a temporary holding space until we find out where we should assign them
- connect():
- Search SocketTaps for tap with a relevant route
- None? -> ENETUNREACH
- Found?
- Assign previously-held socket to this tap
- Attempt connection
- bind():
- bind on all Interfaces?
Join Semantics
- Create : SocketTap
- Create : rpc.d/nwid unix domain socket (if intercept mode?)
- Create : Stack Interface
- Provide : IPs to Interface
/--- int0: 10. 9.0.0
stack ---- int1: 172.27.0.0
\--- int2: ?
*/
// zts_join("other_network"); // 10.9.0.0
// zts_join("whatever"); // 172.27.0.0
//zts_socket(AF, STREAM, 0);
//zts_connect("10.9.9.5");
// ---
// Stop service, delete tap interfaces, and network stack
zts_stop();
return 0;
}

3
examples/go/README.md Normal file
View File

@@ -0,0 +1,3 @@
Go Language Binding API for the ZeroTier SDK
======

7
examples/java/README.md Normal file
View File

@@ -0,0 +1,7 @@
Java Examples
======
Uses API described in [api/java/README.md]
- Copy `ZeroTier.java` into `your_project/src/zerotier`
- Copy `Address.java` into `your_project/src/zerotier`
- Copy `libzt.jnilib` or `libzt.so` from `build/` into `your_project/lib`

View File

@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="/Users/Joseph/op/code/zerotier/ZeroTierSDK/examples/java/ZeroTierHelloWorld/lib"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ZeroTierHelloWorld</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
</natures>
</projectDescription>

View File

@@ -0,0 +1,11 @@
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.debug.lineNumber=generate
org.eclipse.jdt.core.compiler.debug.localVariable=generate
org.eclipse.jdt.core.compiler.debug.sourceFile=generate
org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
org.eclipse.jdt.core.compiler.source=1.8

View File

@@ -0,0 +1,2 @@
ZeroTierSDK Java API
======

View File

@@ -0,0 +1,2 @@
/MyClass$1.class
/zerotier/

Binary file not shown.

View File

@@ -0,0 +1,40 @@
// Hello World example for the ZeroTierSDK
import zerotier.*;
public class MyClass {
public native int loadsymbols();
public native void startOneService();
static {
System.loadLibrary("zt");
}
public static void main(String[] args) {
System.out.println("Welcome to the Machine");
final ZeroTier z = new ZeroTier();
new Thread(new Runnable() {
public void run() {
// Calls to JNI code
z.start("/Users/Joseph/op/code/zerotier/ZeroTierSDK/zt1");
}
}).start();
//while(!z.running()) { }
while(true)
{
try {
System.out.println("Welcome to the Machine");
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,84 @@
package zerotier;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
/*
The ZTAddress object is merely a convenience object for moving address information
across the JNI memory border.
*/
public class Address
{
// int -> byte array
static public byte[] toIPByteArray(long addr){
return new byte[]{(byte)addr,(byte)(addr>>>8),(byte)(addr>>>16),(byte)(addr>>>24)};
}
// byte array -> int
long toIPInt(String _addr) {
long result = 0;
for(String part: _addr.split(Pattern.quote("."))) {
result = result << 8;
result |= Integer.parseInt(part);
}
return result;
}
public int port;
public int Port() {
return port;
}
public long _rawAddr;
public String Address()
{
try {
return InetAddress.getByAddress(toIPByteArray(_rawAddr)).getHostAddress();
} catch (UnknownHostException e) {
// should never happen
return null;
}
}
public String toString() {
return Address() + ":" + Port();
}
public Address()
{
port = -1;
_rawAddr = -1;
}
public Address(String _addr, int _port)
{
_rawAddr = toIPInt(_addr);
port = _port;
}
public void ZTAddress(InetSocketAddress ins)
{
port = ins.getPort();
_rawAddr = toIPInt(ins.getAddress().getHostAddress());
}
public InetSocketAddress ToInetSocketAddress() throws IllegalArgumentException {
InetSocketAddress sock_addr = null;
try {
sock_addr = new InetSocketAddress(Address(), port);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return sock_addr;
}
public boolean isValid() {
return port != -1 && !Address().startsWith("-1.-1.-1.-1/-1");
}
}

View File

@@ -0,0 +1,205 @@
/*
* ZeroTier One - Network Virtualization Everywhere
* Copyright (C) 2011-2015 ZeroTier, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* --
*
* ZeroTier may be used and distributed under the terms of the GPLv3, which
* are available at: http://www.gnu.org/licenses/gpl-3.0.html
*
* If you would like to embed ZeroTier into a commercial application or
* redistribute it in a modified binary form, please contact ZeroTier Networks
* LLC. Start here: http://www.zerotier.com/
*/
package zerotier;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipError;
public class ZeroTier {
public static String Version()
{
return "1.2.2";
}
// Socket families
public static int AF_UNIX = 1;
public static int AF_INET = 2;
// Socket types
public static int SOCK_STREAM = 1;
public static int SOCK_DGRAM = 2;
// fcntl flags
public static int O_APPEND = 1024;
public static int O_NONBLOCK = 2048;
public static int O_ASYNC = 8192;
public static int O_DIRECT = 65536;
public static int O_NOATIME = 262144;
// fcntl cmds
public static int F_GETFL = 3;
public static int F_SETFL = 4;
// Loads JNI code
static { System.loadLibrary("zt"); }
// ZeroTier service controls
public native void ztjni_start(String homeDir);
public void start(String homeDir) {
ztjni_start(homeDir);
}
public native void ztjni_join(String nwid);
public void join(String nwid) {
ztjni_join(nwid);
}
public native void ztjni_leave(String nwid);
public void leave(String nwid) {
ztjni_leave(nwid);
}
public native ArrayList<String> ztjni_get_addresses(String nwid);
public ArrayList<String> get_addresses(String nwid) {
int err = -1;
ArrayList<String> addresses;
while (err < 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
addresses = ztjni_get_addresses(nwid);
if (addresses.size() > 0) {
return addresses;
}
}
return null;
}
public native boolean ztjni_running();
public boolean running() {
return ztjni_running();
}
public native int ztjni_socket(int family, int type, int protocol);
public int socket(int family, int type, int protocol) {
return ztjni_socket(family, type, protocol);
}
public native int ztjni_connect(int fd, String addr, int port);
public int connect(int sock, Address zaddr, String nwid) {
return connect(sock, zaddr.Address(), zaddr.Port(), nwid);
}
public int connect(int sock, String addr, int port, String nwid)
{
int err = -1;
ArrayList<String> addresses;
while (err < 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
addresses = ztjni_get_addresses(nwid);
if (addresses.size() > 0) {
if(!addresses.get(0).startsWith("-1.-1.-1.-1/-1")) {
err = ztjni_connect(sock, addr, port);
}
}
}
return err;
}
public native int ztjni_bind(int fd, String addr, int port);
public int bind(int sock, Address zaddr, String nwid) {
return bind(sock, zaddr.Address(), zaddr.Port(), nwid);
}
public int bind(int sock, String addr, int port, String nwid) {
int err = -1;
ArrayList<String> addresses;
while (err < 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
addresses = ztjni_get_addresses(nwid);
if (addresses.size() > 0) {
if(!addresses.get(0).startsWith("-1.-1.-1.-1/-1")) {
err = ztjni_bind(sock, addr, port);
}
}
}
return err;
}
public native int ztjni_accept4(int fd, String addr, int port);
public int accept4(int fd, String addr, int port) {
return ztjni_accept4(fd,addr,port);
}
public native int ztjni_accept(int fd, zerotier.Address addr);
public int accept(int fd, zerotier.Address addr) {
return ztjni_accept(fd, addr);
}
public native int ztjni_listen(int fd, int backlog);
public int listen(int fd, int backlog) {
return ztjni_listen(fd,backlog);
}
public native int ztjni_close(int fd);
public int close(int fd) {
return ztjni_close(fd);
}
public native int ztjni_read(int fd, byte[] buf, int len);
public int read(int fd, byte[] buf, int len) {
return ztjni_read(fd, buf, len);
}
public native int ztjni_write(int fd, byte[] buf, int len);
public int write(int fd, byte[] buf, int len) {
return ztjni_write(fd, buf, len);
}
public native int ztjni_sendto(int fd, byte[] buf, int len, int flags, zerotier.Address addr);
public int sendto(int fd, byte[] buf, int len, int flags, zerotier.Address addr){
return ztjni_sendto(fd,buf,len,flags,addr);
}
public native int ztjni_send(int fd, byte[] buf, int len, int flags);
public int send(int fd, byte[] buf, int len, int flags) {
return ztjni_send(fd, buf, len, flags);
}
public native int ztjni_recvfrom(int fd, byte[] buf, int len, int flags, zerotier.Address addr);
public int recvfrom(int fd, byte[] buf, int len, int flags, zerotier.Address addr){
return ztjni_recvfrom(fd,buf,len,flags,addr);
}
public native int ztjni_fcntl(int sock, int cmd, int flag);
public int fcntl(int sock, int cmd, int flag) {
return ztjni_fcntl(sock, F_SETFL, O_NONBLOCK);
}
}

View File

@@ -0,0 +1,3 @@
Python Language Binding API for the ZeroTier SDK
======

3
examples/swift/README.md Normal file
View File

@@ -0,0 +1,3 @@
Swift Language Binding API for the ZeroTier SDK
======