本文摘自:http://blog.163.com/lyzaily@126/blog/static/42438837200910173105834/
将域名地址转换成IP地址有一个好处,就是我们的服务器的域名一般不会变化,但是与之对应的IP地址会因为各种原因常常需要更改,比如:服务器搬迁。如果我们将IP硬编码进去代码中,则随着IP的变化要不停的取该源码,这是无法容忍的。所有我们要将域名硬编码进源代码,并通过一些方法将域名转换成服务器的IP。
给出我写的代码片段:
if ( LOBYTE( wsaData.wVersion ) != 1 ||
HIBYTE( wsaData.wVersion ) != 1 ) {
WSACleanup( );
return bRet;
}
s_socketStatus.m_hsocket = socket(AF_INET,SOCK_STREAM,0);
if( INVALID_SOCKET == s_socketStatus.m_hsocket )
{
WSACleanup( );
return bRet;
}
//get remote sever address
memset(host_name,0,sizeof(host_name));
wcstombs(host_name,REMOTE_HOST_NAME,sizeof(host_name));
remoteHost = gethostbyname(host_name);
memmove(&inAddr,remoteHost->h_addr_list[0],4);
IPtr = inet_ntoa(inAddr);
memset(IPBuff,0,sizeof(IPBuff));
memcpy(IPBuff,IPtr,strlen(IPtr));
//-------------------------
// Set the socket I/O mode: In this case FIONBIO
// enables or disables the blocking mode for the
// socket based on the numerical value of iMode.
// If iMode = 0, blocking is enabled;
// If iMode != 0, non-blocking mode is enabled.
iMode = 1;
ioctlsocket(s_socketStatus.m_hsocket,FIONBIO,(u_long FAR*) &iMode);
s_socketStatus.m_isConnected = TRUE;
sockClient = s_socketStatus.m_hsocket;
addrSrv.sin_addr.S_un.S_addr=inet_addr(IPBuff);
addrSrv.sin_family=AF_INET;
addrSrv.sin_port=htons(6000);
connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));
return TRUE;
}
这里涉及到几个重要的socket函数:
(1)、
通过域名获得对应的IP:
struct hostent FAR* gethostbyname(
const char FAR* name //服务器的域名字符串
);
(2)、
将gethostbyname获得的IP转换成以点分的IP字符串:
char FAR* inet_ntoa(
struct in_addr in //gethostbyname()返回的内容
);
(3)、
将点分的IP字符串转换成合适的IP值:
unsigned long inet_addr( const char FAR* cp);
具体详情请自己查阅MSDN,msdn是个好东西!