请问如何取得本机IP,例如(192.168.110.11)
请问如何取得本机,例如(192.168.110.11) 问题点数:20、回复次数:6Top
1 楼laiyiling(陌生人[MVP])回复于 2005-06-03 13:04:21 得分 0
如何获得本机主机名和IP地址?
(航一发表于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
}
Top
2 楼younggle(洋溢)回复于 2005-06-03 13:19:29 得分 15
来晚了,不过laiyiling(陌生人·V2.0〓Happiness) 说的对了。Top
3 楼aiyue2010(亚伦)回复于 2005-06-03 13:19:47 得分 5
WORD wVersionRequested = MAKEWORD(2, 2);
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();
Top
4 楼wei1945()回复于 2005-06-03 13:23:24 得分 0
多谢!!!!Top
5 楼wei1945()回复于 2005-06-03 13:30:03 得分 0
不好意思,一着急分数给错了,对不起各位大虾;P
能改吗Top
6 楼wei1945()回复于 2005-06-03 13:30:26 得分 0
不好意思,一着急分数给错了,对不起各位大虾;P
能改吗Top




