LoginSignup
1
3

More than 5 years have passed since last update.

【開発メモ~C/C++のプログラムで自身のローカルIPとホスト名取得~】

Last updated at Posted at 2018-10-22

開発環境:
・Windows64bit
・VisualStudio2015
・c/c++

①ソケットなのでとりあえずインクルードやら

main.cpp
#include <winsock2.h>
#pragma comment(lib, "wsock32.lib")

②格納する変数を作成する

main.cpp
// ホストネーム格納領域
char lpszHostName[50];
// IPアドレス
wchar_t lpszIP[19];
PHOSTENT phostent;
IN_ADDR in;

phostent ・・・ ホストネーム
in  ・・・ インターネットのホストアドレス

③ホストのデータをゲット

main.cpp
gethostname(lpszHostName, 50); // 格納する変数と名前の長さを指定(自由)

④phostent構造体にいれる

main.cpp
phostent = gethostbyname(lpszHostName)

⑤inにアドレスを4byte分コピーします

main.cpp
memcpy(&in, phostent->h_addr, 4);

⑥inをinet_ntoaで10進数へ変換し、lpszIPに 書式化が終わった文字列を格納して表示する。

main.cpp
wsprintf(lpszIP,(wchar_t*)inet_ntoa(in));

☆思ったこと
専門的なことが増えてきたので、グーグル先生を活用したのですがまだネットワーク知識が不十分なので勉強が必要だと改めて感じました。

参考

http://www.geocities.jp/playtown1056/program/ws_2.htm

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3