Getting IP Address of Machine in VC++
August 14, 2010 2 Comments
Getting IP Address of machine in VC++
Introduction:
Here we can see how to get the multiple ip address available in machine and display it in Multi line text box in MFC.
How To start:
here am used MFC dialog based application you can change it accordingly.
note: make sure to select Socket support in Application Wizard
How to make Multi line text Box in MFC:
To make a Editbox as multi line text box follow this procedure .
- Select the edit box and select the properties
- Select Multiline checked
- Select want return checked
- Create member variable as Value type using Class Wizard. to insert a new line in edit box we should use “\r\n“.
- for example if the member variable is m_Text we can use as follows
m_Text="\r\n Hi \r\n This \r\n Multiline \r\n Sample";
Code To Get the IP Address:
The following code gets and displays the IP Address of the machine in the edit box.
void CDispalyIPAddressDlg::OnGetIP() { UpdateData(TRUE); char HostName[128]; //Get host name and Check is there was any error if (gethostname(HostName, sizeof(HostName)) == SOCKET_ERROR) { AfxMessageBox("Error in Getting Host Info"); CDialog::OnCancel(); } //Get the ip address of the machine using gethostbyname function struct hostent *IpList = gethostbyname(HostName); m_List+="Host Name is:"; m_List+=HostName; m_List+="\r\n"; if (IpList == 0) { AfxMessageBox("Yow! Bad host lookup."); CDialog::OnCancel(); } m_List+="\r\n\r\nIP Address Available are:\r\n"; m_List+="----------------------------------------------------------\r\n"; //Enumerate list of Ip Address available in the machine for (int i = 0; IpList->h_addr_list[i] != 0; ++i) { struct in_addr addr; memcpy(&addr, IpList->h_addr_list[i], sizeof(struct in_addr)); CString str=inet_ntoa(addr); m_List=m_List+ str; m_List+="\r\n" ; } m_List+="-----------------------------------------------------------\r\n"; UpdateData(FALSE); }
Final Output
Final looks like in the following screen shot.