Wednesday, October 1, 2008

My First WinSock Application

Finally, I wrote my first WinSock application with Visual C++. It's just the simple one. This application is used to detect IP address and hostname of local host. Here is the code :

WORD Version;
WSADATA wsaData;
char name[255];
CString ip;
CWaitCursor wait;
PHOSTENT hostinfo;
Version = MAKEWORD(2,2);
in_addr m_in;

if (WSAStartup(Version,&wsaData)==0)
{
if (gethostname(name, sizeof(name))==0)
{
if ((hostinfo=gethostbyname(name))!=NULL)
{
memcpy (&m_in, hostinfo->h_addr_list, 4);
ip=inet_ntoa(m_in);
m_cIPAddress.SetWindowTextW(ip);
m_cName.SetWindowTextW((CString)name);
m_cIPAddress.EnableWindow(TRUE);
m_cName.EnableWindow(TRUE);
}
}
WSACleanup();
}

And the output looks like this:

No comments: