ドットIPアドレスの数値変換(C版)

ドット付きIPアドレス(127.0.0.1等)を数値に変換。
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;
  };


カテゴリ

Amazon

アクセスランキング

[ジャンルランキング]
コンピュータ
226位
アクセスランキングを見る>>

[サブジャンルランキング]
プログラミング
37位
アクセスランキングを見る>>

RSSリンクの表示

QRコード

QRコード

サイトマップ

Copyright © nopgm