プロキシ切り替えるクロム拡張作った


学校のネットワークに繋いだら学校のプロキシに、家に戻ったらプロキシの自動検出に手動で切り替えてたのだけれども、
面倒くさかったから勉強も兼ねてクロム拡張を作った。

マニュフェストファイルはこんな感じ

{
  "manifest_version": 2,
  "name": "Proxy Changer",
  "version": "1.0",
  "description": "change http proxy",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "tabs",
    "proxy"
  ],
  "icons" : {
    "128": "icon.png"
  }
}

続いてhtml

<!DOCTYPE HTML>

<html lnag="ja">
  <head>
    <meta charset="utf-8">
    <title>proxy changer</title>
  </head>
  <body>
    <button id="scholl">scholl proxy</button>
    <button id="outer">outer proxy</button>

    <script src="background.js"></script>
  </body>

</html>

js

window.onload=function(){
  document.getElementById("scholl").addEventListener("click", changeShollProxy);
  document.getElementById("outer").addEventListener("click", changeOuterProxy);
}

var config = {
    mode: "fixed_servers",
    rules: {
      proxyForHttp: {
        scheme: "http",
        host: "xx.xx.xx.xx",
        port: xxxx
      },
      bypassList: ["127.0.0.1"]
    }
  };


function changeShollProxy(){
  chrome.proxy.settings.set(
    {value: config, scope: "regular"},
    function(){}
  );
}

function changeOuterProxy(){
  config.mode = "auto_detect";
  chrome.proxy.settings.set(
    {value: config, scope: "regular"},
    function(){}
  );

}

html適当なのは許して
本当は

<button id="scholl" onclick="chagneSchollProxy">scholl</button>

みたいにしたかったけど、クロム拡張では出来ないみたい(違ってたらごめんなさい)。

参考
いまさらまとめるChrome ExtensionでのJavaScript挿入 - console.lealog();

https://developer.chrome.com/extensions/proxy

バイト列の任意の位置から32ビット読み込んでint型として扱う

TCPUDPなどのネットワークプログラムを書いてると、受信したバイト列の任意の位置から32ビットを読み込んでint型として扱いたくなる時がある。

例えば、受信したバイト列に整数「123」が含まれているとする。

整数「123」はバイト列に直すと

00 00 00 7b

となる。実際には、バイト列には他のデータも含まれているので

00 00 00 64 00 00 00 7b 00 00 04 d2

みたいな感じになる(「00 00 00 7b」以外は適当)。

このバイト列から4バイト(00 00 00 7b)をうまく切り出してint型にキャストすると整数「123」を復元することができる。

c言語で書くとこんな感じ

#include <stdio.h>
typedef unsigend char UINT8;
typedef unsigned int UINT32;

UINT32 readUint32(UINT8 *bytes, int index){
  return (UINT32)((UINT32)(bytes[index] << 0) | ((UINT32)bytes[index + 1] << 8) | ((UINT32)bytes[index + 2] << 16) | ((UINT32)bytes[index + 3] << 24));
}

int main(void){
  UINT8 bytes[] ={0xd2m 0x04, 0x00, 0x00, 0x7b, 0x00, 0x00, 0x00, 0x64, 0x00, 0x00, 0x00};
  UINT32 temp;
  int *intVal;

  temp = readUint32(bytes, 4);
  intVal = (int *)&temp;

  printf("%d\n", *intVal);
  
  return 0;
}