2020/05/26

[C] Simple daemon example with multiple connections


  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread.h>

#define PORT 1539
#define MAX_CLIENT 32

// connection information
struct connectInfo {
	int socket;
	int index;
};

// pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_t tid[MAX_CLIENT]={0};

// Each connection creates a pthread to handle communication.
void * sThread(void *arg)
{
	char message[64], retmsg[64];
	struct connectInfo *cInfo = (struct connectInfo *)arg;
	int nSocket = cInfo->socket;

	pthread_detach(pthread_self());
	int resume=1, i;
	struct timeval timeout;
	fd_set fds;
	
	FD_ZERO(&fds);
	FD_SET(nSocket, &fds);
	
	while (resume) {
		// reset timer
		timeout.tv_sec = 300;
		timeout.tv_usec = 0;
		
		// receive message with timeout control.
		i = select(nSocket+1, &fds, NULL, NULL, &timeout);
		if (0 == i) {
			printf("[%d] timeout\n", nSocket);
			resume = 0;
		} else if (-1 == i) {
			printf("[%d] got error\n", nSocket);
			resume = 0;
		} else {
			// The message still needs to be retrieved by recv.
			recv(nSocket , message , sizeof(message) , 0);
			printf("[%d] got message %s\n", nSocket, message);
			//pthread_mutex_lock(&lock);
			/*                         */
			//pthread_mutex_unlock(&lock);
			if (strncmp (message, "exit" , 4) == 0 ) {
				sprintf(retmsg, "bye");
				resume = 0;
			} else {
				sprintf(retmsg, "I got %s", message);
			}
			// Reply message to the other side.
			send(nSocket, retmsg, sizeof(retmsg), 0);
		}
	}
	// close connection
	close(nSocket);
	// release tid
	tid[cInfo->index] = 0;
	// exit pthread
	pthread_exit(NULL);
}

int main(int argc, char *argv[])
{
	int sSocket, nSocket, i;
	struct sockaddr_in s_in;
	struct sockaddr_storage s_storage;
	socklen_t addr_size;
	struct connectInfo cInfo[MAX_CLIENT];
	
	sSocket = socket(PF_INET, SOCK_STREAM, 0);
	
	// Set daemon to listen on port 1539 to any address 
	s_in.sin_family = AF_INET;
	s_in.sin_port = htons(PORT);
	s_in.sin_addr.s_addr = htonl(INADDR_ANY);
	memset(s_in.sin_zero, '\0', sizeof s_in.sin_zero);
	bind(sSocket, (struct sockaddr *) &s_in, sizeof(s_in));

	// start listen.
	if(listen(sSocket, MAX_CLIENT)==0) {
		printf("Listening\n");
	} else {
		printf("Listen Fail\n");
		exit(-1);
	}

	i = 0;
	while (1) {
		addr_size = sizeof(s_storage);
		nSocket = accept(sSocket, (struct sockaddr *) &s_storage, &addr_size);
		if (-1 == nSocket) {	//accept return error
			continue;
		}

		// when got a new connection, find an empty tid to create a new pthread.
		for (i=0; i<MAX_CLIENT; i++) {
			if (0 == tid[i]) {
				cInfo.socket = nSocket;
				cInfo.index = i;
				if( pthread_create(&tid[i], NULL, sThread, (void*) &cInfo[i]) != 0 ) {
					printf("Failed to create thread\n");
				} else {
					i = MAX_CLIENT+1;
				}
			}
		}
		
		if (MAX_CLIENT == i) {
			printf("No more free thread.\n");
			close(nSocket);
		}
	}
}

2020/01/08

[bash] Check if the IP address is used


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
#!/bin/bash
[ 1 -ne $# ] && {
        echo "Syntax: $0 ip_address"
        exit 0
}

ping -c1 -W1 $1 >/dev/null

ret=$(arp -n | grep "$1" | grep "(incomplete)")
[ -n "$ret" ] &&
{
        echo "$1 unused"
} || {
        echo "$1 used"
}

Line 2~5: Avoid no parameters.
Line 7: Use ping to learn arp.
Line 9~15: Check arp table and echo message.

2019/08/30

Use netstat to find out specific port listened by which process.


 First look at the syntax of netstate.
BusyBox v1.25.1 (2019-08-07 15:22:35 CST) multi-call binary.
Usage: netstat [-ral] [-tuwx] [-enWp]
Display networking information
-r Routing table
-a All sockets
-l Listening sockets
Else: connected sockets
-t TCP sockets
-u UDP sockets
-w Raw sockets
-x Unix sockets
Else: all socket types
-e Other/more information
-n Don't resolve names
-W Wide display
-p Show PID/program name for sockets

I want to know which port softethervpn listens to.
Execute command: netstat -alnp | grep vpnserver
root@AtopTechnologies:~# netstat -alnp | grep vpnserver
udp        0      0 0.0.0.0:33147           0.0.0.0:*                           4007/vpnserver
udp        0      0 192.168.5.143:1194      0.0.0.0:*                           4007/vpnserver
udp        0      0 127.0.0.1:1194          0.0.0.0:*                           4007/vpnserver
udp        0      0 192.168.1.1:1194        0.0.0.0:*                           4007/vpnserver
udp        0      0 0.0.0.0:63972           0.0.0.0:*                           4007/vpnserver
udp        0      0 ::1:1194                :::*                                4007/vpnserver
udp        0      0 fe80::8ee7:48ff:fe00:1:1194 :::*                                4007/vpnserver
udp        0      0 fe80::8ee7:48ff:fe00:0:1194 :::*                                4007/vpnserver
It is listen UDP port 1194, same as openVPN.

2019/02/12

OpenWRT 在 shell 使用 ubus 取得 wan, lan 的 ip address 和 mask

OpenWRT 的 uci get 是用來取得設定內容,假如 wan 是動態取得 ip address,就無法透過 uci get 來取得 wan 的 ip address。所以需要透過 ubus 跟 jsonfilter 來取得這些動態的資訊。

先參考官方的 ubus 說明

列出現有的 object 來參考
root@OpenWrt:~# ubus list
log
network
network.device
network.interface
network.interface.VLAN101
network.interface.lan
network.interface.loopback
network.interface.wan
network.interface.wan6
network.wireless
service
session
system
uci

看看 wan 的狀態
root@OpenWrt:~# ubus call network.interface.wan status
{
	"up": true,
	"pending": false,
	"available": true,
	"autostart": true,
	"dynamic": false,
	"uptime": 5493,
	"l3_device": "eth0",
	"proto": "dhcp",
	"device": "eth0",
	"updated": [
		"addresses",
		"routes",
		"data"
	],
	"metric": 0,
	"delegation": true,
	"ipv4-address": [
		{
			"address": "192.168.5.218",
			"mask": 24
		}
	],
	"ipv6-address": [
		
	],
	"ipv6-prefix": [
		
	],
	"ipv6-prefix-assignment": [
		
	],
	"route": [
		{
			"target": "192.168.5.254",
			"mask": 32,
			"nexthop": "0.0.0.0",
			"source": "192.168.5.218\/32"
		},
		{
			"target": "0.0.0.0",
			"mask": 0,
			"nexthop": "192.168.5.254",
			"source": "192.168.5.218\/32"
		}
	],
	"dns-server": [
		"8.8.8.8",
		"168.95.1.1"
	],
	"dns-search": [
		"WIFI"
	],
	"inactive": {
		"ipv4-address": [
			
		],
		"ipv6-address": [
			
		],
		"route": [
			
		],
		"dns-server": [
			
		],
		"dns-search": [
			
		]
	},
	"data": {
		"leasetime": 86400
	}
}
輸出是 json 的結構,從上面的內容看到 wan 是透過 dhcp 取得 192.168.5.218/24

接下來要透過 jsonfilter (官網) 來抽出我們想要的內容。不確定原因,但是直接執行沒看到說明,所以進去原始碼看看語法:
print_usage(char *app)
{
	printf(
	"== Usage ==\n\n"
	"  # %s [-a] [-i  | -s \"json...\"] {-t  | -e }\n"
	"  -q		Quiet, no errors are printed\n"
	"  -h, --help	Print this help\n"
	"  -a		Implicitely treat input as array, useful for JSON logs\n"
	"  -i path	Specify a JSON file to parse\n"
	"  -s \"json\"	Specify a JSON string to parse\n"
	"  -l limit	Specify max number of results to show\n"
	"  -F separator	Specify a field separator when using export\n"
	"  -t 	Print the type of values matched by pattern\n"
	"  -e 	Print the values matched by pattern\n"
	"  -e VAR=	Serialize matched value for shell \"eval\"\n\n"
	"== Patterns ==\n\n"
	"  Patterns are JsonPath: http://goessner.net/articles/JsonPath/\n"
	"  This tool implements $, @, [], * and the union operator ','\n"
	"  plus the usual expressions and literals.\n"
	"  It does not support the recursive child search operator '..' or\n"
	"  the '?()' and '()' filter expressions as those would require a\n"
	"  complete JavaScript engine to support them.\n\n"
	"== Examples ==\n\n"
	"  Display the first IPv4 address on lan:\n"
	"  # ifstatus lan | %s -e '@[\"ipv4-address\"][0].address'\n\n"
	"  Extract the release string from the board information:\n"
	"  # ubus call system board | %s -e '@.release.description'\n\n"
	"  Find all interfaces which are up:\n"
	"  # ubus call network.interface dump | \\\n"
	"  	%s -e '@.interface[@.up=true].interface'\n\n"
	"  Export br-lan traffic counters for shell eval:\n"
	"  # devstatus br-lan | %s -e 'RX=@.statistics.rx_bytes' \\\n"
	"	-e 'TX=@.statistics.tx_bytes'\n",
		app, app, app, app, app);
}

我們要用的是 -e 這個操作,以 ip address 為例,要取的值是 ipv4-address 底下的 address
root@OpenWrt:~# ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].address'
192.168.5.218
很順利的取得了 wan 的 ip 是 192.168.5.218

寫個 shell script 來測試
root@OpenWrt:/# cat /tmp/test.sh 
LAN_IP=`ubus call network.interface.lan status | jsonfilter -e '@["ipv4-address"][0].address'`
LAN_MASK=`ubus call network.interface.lan status | jsonfilter -e '@["ipv4-address"][0].mask'`
LAN_DEV=`ubus call network.interface.lan status | jsonfilter -e '@["device"]'`
WAN_IP=`ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].address'`
WAN_MASK=`ubus call network.interface.wan status | jsonfilter -e '@["ipv4-address"][0].mask'`
WAN_DEV=`ubus call network.interface.wan status | jsonfilter -e '@["device"]'`
echo "LAN_IP=$LAN_IP"
echo "LAN_MASK=$LAN_MASK"
echo "LAN_DEV=$LAN_DEV"
echo "WAN_IP=$WAN_IP"
echo "WAN_MASK=$WAN_MASK"
echo "WAN_DEV=$WAN_DEV"
root@OpenWrt:/# /tmp/test.sh 
LAN_IP=192.168.1.1
LAN_MASK=24
LAN_DEV=br-lan
WAN_IP=192.168.5.218
WAN_MASK=24
WAN_DEV=eth0


2019/02/01

Leetcode 869. Reordered Power of 2

869. Reordered Power of 2
Starting with a positive integer N, we reorder the digits in any order (including the original order) such that the leading digit is not zero.
Return true if and only if we can do this in a way such that the resulting number is a power of 2.
 Example 1:
Input: 1
Output: true
Example 2:
Input: 10
Output: false
Example 3:
Input: 16
Output: true
Example 4:
Input: 24
Output: false
Example 5:
Input: 46
Output: true
Note:
  1. 1 <= N <= 10^9

題意就是檢查輸入的數字能不能重組成2的次方倍,例如 46 可以重組成 64,是 2 的次方倍,所以要傳回 true。採用的方法就是計算個別數字出現的次數,跟 2 的次方倍相比,次數相同就表示可以重組成功。因為題目有限縮 N 的範圍,所以可以利用這一點來加快執行速度,程式碼如下:



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
bool check(int* d, int T) {
 int t[10] = {0};
 int m;
 
 while (T) {
  m = T % 10;
  ++t[m];
  T /= 10;
 }

 for (m=0; m<10; m++) {
  if (d[m] != t[m]) {
   return false;
  }
 }
 return true;
}

bool reorderedPowerOf2(int N) {
 int i, n, m, s, z, d[10]={0};
 
 if (N < 128) {
  if (64 == N) {
   return true;
  }
  if (46 == N) {
   return true;
  }
  if (32 == N) {
   return true;
  }
  if (23 == N) {
   return true;
  }
  if (16 == N) {
   return true;
  }
  if (61 == N) {
   return true;
  }
  if (8 == N) {
   return true;
  }
  if (4 == N) {
   return true;
  }
  if (2 == N) {
   return true;
  }
  if (1 == N) {
   return true;
  }
 }
 
 n = N;
 i = 0;
 s = 0;
 while (n) {
  m = n % 10;
  s += m;
  ++d[m];
  n /= 10;
 }

    if (N >= 100000000) {
  if ((41 == s) && check(d, 536870912)) {
   return true;
  }
  if ((43 == s) && check(d, 268435456)) {
   return true;
  }
  if ((35 == s) && check(d, 134217728)) {
   return true;
  }
 } else if (N >= 10000000) {
  if ((40 == s) && check(d, 67108864)) {
   return true;
  }
  if ((29 == s) && check(d, 33554432)) {
   return true;
  }
  if ((37 == s) && check(d, 16777216)) {
   return true;
  }
 } else if (N >= 1000000) {
  if ((41 == s) && check(d, 8388608)) {
   return true;
  }
  if ((25 == s) && check(d, 4194304)) {
   return true;
  }
  if ((26 == s) && check(d, 2097152)) {
   return true;
  }
  if ((31 == s) && check(d, 1048576)) {
   return true;
  }
 } else if (N >= 100000) {
  if ((29 == s) && check(d, 524288)) {
   return true;
  }
  if ((19 == s) && check(d, 262144)) {
   return true;
  }
  if ((14 == s) && check(d, 131072)) {
   return true;
  }
 } else if (N >= 10000) {
  if ((25 == s) && check(d, 65536)) {
   return true;
  }
  if ((26 == s) && check(d, 32768)) {
   return true;
  }
  if ((22 == s) && check(d, 16384)) {
   return true;
  }
 } else if (N >= 1000) { 
  if ((20 == s) && check(d, 8192)) {
   return true;
  }
  if ((19 == s) && check(d, 4096)) {
   return true;
  }
  if ((14 == s) && check(d, 2048)) {
   return true;
  }
  if ((7 == s) && check(d, 1024)) {
   return true;
  }
 } else if (N >= 100) {
  if ((8 == s) && check(d, 512)) {
   return true;
  }
  if ((13 == s) && check(d, 256)) {
   return true;
  }
  if ((11 == s) && check(d, 128)) {
   return true;
  }
 }
 
 return false;
}

另一個解法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
bool check(int* d, int T) {
 int t[10] = {0};
 int m;

 while (T) {
  ++t[T % 10];
  T /= 10;
 }
 
 for (m=0; m<10; m++) {
  if (d[m] != t[m]) {
   return false;
  }
 }
 return true;
}

bool reorderedPowerOf2(int N) {
 int c, i, n, T;
 int d[10] = {0};
 int r[32] = {0,1,1,1,1,2,2,2,3,3,3,4,4,4,4,5,5,5,6,6,6,7,7,7,7,8,8,8,9,9,9,10};

 if (1==N || 2==N || 4==N || 8==N) {
  return true;
 }

 n = N;
 c = 0;
 while (n) {
  ++d[n % 10];
  n /= 10;
  ++c;
 }

 T=16;
 for (i=5;i<32;i++) {
  if (r[i] > c) {
   break;
  } else if (r[i] == c && check(d, T)) {
   return true;
  }
  T<<=1;
 }

 return false;
}