自マシンのネットワークデバイス名に対応するIPアドレスを取得します。ネットワークデバイス名は、"ipconfig /all"で表示される、Description属性の値です。
環境
WindowsXP SP2
VisualC++ 2008 ExpressEdition
プロジェクトの「追加の依存ファイル」に"Ws2_32.lib"と"iphlpapi.lib"を追記します。
1
2
3
4
5
| -
|
|
|
!
| int main(){
const char* r = GetMyIpAddr("Intel(R) PRO/100 VE Network Connection");
printf("%s\n", r);
return 0;
}
|
参考サイト
「札幌ソフト開発工場」の情報を参考にさせていただきました。
http://homepage2.nifty.com/spw/tips/
ソースコード
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
|
-
|
|
|
|
|
|
-
|
|
|
-
-
|
|
|
|
!
!
!
|
|
!
-
|
|
|
|
|
|
|
|
-
|
-
|
-
|
!
|
-
|
|
!
!
!
|
|
!
| #include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <errno.h>
const char* GetMyIpAddr(const char* device_name);
long GetIndexOfIF(const char* device_name);
const char* GetMyIpAddr(const char* device_name) {
char* ipAddr = NULL;
DWORD dSize=0;
GetIfTable( NULL , &dSize, FALSE );
PMIB_IPADDRTABLE pIpAddrTable = (PMIB_IPADDRTABLE)new char[dSize];
if( GetIpAddrTable( (PMIB_IPADDRTABLE)pIpAddrTable,&dSize,FALSE) == NO_ERROR ){
long index = GetIndexOfIF(device_name);
for( int i = 0 ; i < (int)pIpAddrTable->dwNumEntries ; i++ ){
if( index == pIpAddrTable->table[i].dwIndex ) {
in_addr ina;
ina.S_un.S_addr = pIpAddrTable->table[i].dwAddr;
ipAddr = inet_ntoa( ina );
break;
}
}
}
delete [] pIpAddrTable;
return ipAddr;
}
long GetIndexOfIF(const char* device_name) {
DWORD dSize=0;
DWORD dwIndex=0;
GetIfTable( NULL , &dSize, FALSE );
PMIB_IFTABLE pIfTable = (PMIB_IFTABLE)new char[dSize] ;
if( GetIfTable( (PMIB_IFTABLE)pIfTable,&dSize,FALSE) == NO_ERROR ){
for(int i=0;i< (int)pIfTable->dwNumEntries;i++ ){
if( sizeof(pIfTable->table[i].bDescr) < strlen(device_name) ) {
continue;
}
if( !strncmp((const char*)pIfTable->table[i].bDescr, device_name, strlen(device_name)) ) {
dwIndex = pIfTable->table[i].dwIndex;
break;
}
}
}
delete [] pIfTable;
return (long)dwIndex;
}
|