#include <winsock2.h>
#pragma comment(lib,"ws2_32.lib")
CString getMyIp() {
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
CString ip;
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD(2,0);
if(WSAStartup(wVersionRequested, &wsaData) == 0) {
if(gethostname(name,sizeof(name)) == 0) {
if((hostinfo = gethostbyname(name)) != NULL) {
ip = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list);
}
}
}
return ip;
}
참고
자신의 IP가 여러개일때는 다음의 방법을 사용하도록 합니다.
---------------- CString getMyIp() {
WORD wVersionRequested;
WSADATA wsaData;
char name[255];
CString ip;
PHOSTENT hostinfo;
wVersionRequested = MAKEWORD(2,0); if(WSAStartup(wVersionRequested, &wsaData) == 0) {
if(gethostname(name,sizeof(name)) == 0) {
for(int i=0; pHostInfo->h_addr_list[i] != NULL ;i++) {// 반복해서 IP얻기
memcpy(&(addr.sin_addr), pHostInfo->h_addr_list[i], pHostInfo->h_length);
ip.Format("My address:%s\n", inet_ntoa(dest.sin_addr));
AfxMessageBox(ip);
}
}
} return ip;
} |