#include "winsock2.h"
#include "iostream.h"
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"wsock32.lib")
int main(void)
{
char HostName[40];
memset(HostName,0,41);
if(gethostname(HostName,40)!=SOCKET_ERROR)
cout<<HostName<<endl;
else
cout<<"not fount!"<<endl;
hostent *host;
host=gethostbyname("LFY");//LFY为本机名
cout<<host->h_name<<endl;
return 0;
}
#include "iostream.h"
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"wsock32.lib")
int main(void)
{
char HostName[40];
memset(HostName,0,41);
if(gethostname(HostName,40)!=SOCKET_ERROR)
cout<<HostName<<endl;
else
cout<<"not fount!"<<endl;
hostent *host;
host=gethostbyname("LFY");//LFY为本机名
cout<<host->h_name<<endl;
return 0;
}
先使用WSAStartup()这个函数来初始化
#pragma comment(lib,"ws2_32.lib")
#pragma comment(lib,"wsock32.lib") CString m_strIPAddress;
WSADATA wsaData;
int iRet = WSAStartup(MAKEWORD(0x02, 0x02), &wsaData);
if (iRet != 0)
{
TRACE("初始化winsock动态库出错!");
m_strIPAddress = "";
return;
} struct in_addr localaddr;
struct hostent *hp=NULL;
char hostname[50];
gethostname(hostname,49);//主机名 hp=gethostbyname(hostname);//主机信息
memcpy(&localaddr,hp->h_addr,hp->h_length);//地址 m_strIPAddress = inet_ntoa(localaddr);//变成char *
WSACleanup();
WORD wVersionRequested = MAKEWORD(2,0);
if(WSAStartup(wVersionRequested,&wsaData) != 0)
{
return;
}
char hostname[256] = "";
int rest = gethostname(hostname,sizeof(hostname));
if(rest != 0)
{
return;
}
hostent* pHostent = gethostbyname(hostname);
if(pHostent != NULL)
{
hostent &he = *pHostent;
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);
}
SetDlgItemText(IDC_STATIC_IP,inet_ntoa(sa.sin_addr));
}
WSACleanup();