请问如何取得本机,例如(192.168.110.11)
解决方案 »
- 在VS2008关于MFC默认生成的对话框 最大化显示 和拖动显示不正常的问题!
- 窗口分割的问题
- 请问哥哥们用什么操作数据库?OLE DB,ODBC,ADO,哪个好用?
- 怎样得到一个CString类型的长度?谢谢!
- 高手请进:Dll中“回调”如何实现?
- 我要创建一个类CMsg,基类是CObject,可是在ClassWizard中的BaseClass选项中找不到CObject,所以建不成CMsg,为什么,怎么办??
- 关于安装的问题,在线!!!!!
- 请问如何把 IE 中 FLASH 讨厌的声音关掉?
- 高分重赏!!!谁知道怎么给CcmdTarget派生的类发送消息.
- 怎么在Windows下播放MP3?用SDK编程
- 急,关于类已经在注册表中注册的问题,如何删除,注册表高手请解答,在线等
- 数据转换问题
(航一发表于2001-8-15 20:38:22) [问题提出]
如何获得本机主机名和IP地址? [解决方法]
主机地址可以用API 获得int gethostname (char *name, int namelen ); [程序实现]
假设你有了名为My的对话框工程.有一个按钮并有响应的程序:如OnButton1();
BOOL CListCtrl1Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
AfxSocketInit(NULL);//支持Socket.若在向导是没选Support Socket,这就的加.还要加#include <afxsock.h>在StdAfx.h中. .......
// Add "About..." menu item to system menu. // IDM_ABOUTBOX must be in the system command range.
// TODO: Add extra initialization here return TRUE; // return TRUE unless you set the focus to a control
}
void CListCtrl1Dlg::OnButton1()
{
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);
}
}
WSACleanup( );
}
AfxMessageBox(name);//name里是本机名
AfxMessageBox(ip); //ip中是本机IP
}
WSADATA wsaData;
if (WSAStartup(wVersionRequested, &wsaData)) {
printf("WSAStartup failed %s\n", WSAGetLastError());
return -1;
}SOCKADDR_IN sockStruct; //SOCKET 结构
sockStruct.sin_family=AF_INET; //使用TCP/IP协议
sockStruct.sin_port = htons(8001);
sockStruct.sin_addr.S_un.S_addr = inet_addr("172.31.21.59");char strIP[100];
WSAAddressToString((LPSOCKADDR)&sockStruct, WSAEnumProtocols(),sizeof(sockStruct), strIP, 100);
//////////////////
// Get host name.
//
char hostname[256];
int res = gethostname(hostname, sizeof(hostname));
if (res != 0) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}
printf("hostname=%s\n", hostname);////////////////
// Get host info for hostname.
//
hostent* pHostent = gethostbyname(hostname);
if (pHostent==NULL) {
printf("Error: %u\n", WSAGetLastError());
return -1;
}//////////////////
// Parse the hostent information returned
//
hostent& he = *pHostent;
printf("name=%s\naliases=%s\naddrtype=%d\nlength=%d\n",
he.h_name, he.h_aliases, he.h_addrtype, he.h_length);sockaddr_in sa;
for (int nAdapter=0; he.h_addr_list[nAdapter]; nAdapter++) {
memcpy ( &sa.sin_addr.s_addr, he.h_addr_list[nAdapter],he.h_length);
// Output the machines IP Address.
printf("Address: %s\n", inet_ntoa(sa.sin_addr)); // display as string
}//////////////////
// Terminate windows sockets API
//
WSACleanup();