ドットIPアドレスの数値変換(C版)
- Thu
- 22:29
- C/C++
ドット付きIPアドレス(127.0.0.1等)を数値に変換。
IPV4でのみ確認。IPV6の場合はどうなるかまだ調べてない。
in_addr構造体は(/usr/include/)netinet/in.hにて定義されている。
返される数値は、uint32_t型。
IPV4でのみ確認。IPV6の場合はどうなるかまだ調べてない。
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <string.h> //#include <sys socket.h> #include <arpa/inet.h> #include <netinet/in.h> using namespace std; const char* me; void usage () { cerr << "Usage: " << me << " IP" << endl; cerr << " IP: dot address format (e.g. 127.0.0.1)" << endl; cerr << endl; } int main (int argc,const char * argv[]) { struct in_addr addr; int success = 1; me = argv[0]; const char *ip = argv[1]; if (ip == NULL || strlen(ip) <= 0) { usage(); exit (1); } // non-zero on success success = inet_aton(ip, &addr); if (success) { cerr << "*** IP=[" << argv[1] << "] => "<< addr.s_addr << endl; } else { cerr << "inet_aton() failed (rc=" << success << "). IP=[" << ip << "]" << endl; usage(); exit (1); } exit (0); }
in_addr構造体は(/usr/include/)netinet/in.hにて定義されている。
返される数値は、uint32_t型。
/* Internet address. */ typedef uint32_t in_addr_t; struct in_addr { in_addr_t s_addr; };
シェルスクリプトのパラメータ(引数)の取得
- Thu
- 00:43
- シェルスクリプト
getopts を利用した、シェルスクリプトのパラメータ(引数)取得。
getopts の指定方法:
実行例:
getopts の指定方法:
文字: | valueあり |
文字 | valueなし。ヘルプ表示やデバッグのフラグなどに利用。 |
#!/bin/sh sub_show_usage () { echo "Usage: $0 [-d date] [-h]" echo " -d: date (yyyymmdd) " echo " -h: show usage " exit 1 } while getopts d:he: OPT do case $OPT in "d" ) DATE="$OPTARG" ;; "e" ) ENV="$OPTARG" ;; "h" ) sub_show_usage exit 1;; * ) sub_show_usage exit 1 ;; esac done echo "*** DATE=[$DATE] ENV=[$ENV]" exit 0
実行例:
$ ./tmp.sh -d 20100929 -h Usage: ./tmp.sh [-d date] [-h] -d: date (yyyymmdd) -h: show usage $ ./tmp.sh -d 20100929 *** DATE=[20100929] ENV=[] $ ./tmp.sh -d 20100929 -e test *** DATE=[20100929] ENV=[test]