19. How do I find the current IP address(es) of my machine?
You can use GetComputerName (or gethostname) and gethostbyname (see
WINSOCK2.H) for this. Remember that a computer can have more than one IP address
- it can
have multiple adapters, or be supporting extra addresses for RAS purposes.
Bear in mind that this code uses Winsock functionality, so a successful call
to WSAStartup is a pre-requisite.
HOSTENT* phe ;
char szCpuName [128] ;
DWORD dwSize = sizeof(szCpuName);
int iaddr, ifield;
UINT uField;
CString csIpAddr;
CString csAddrField;
if (GetComputerName (szCpuName, &dwSize) == 0)
{
wsprintf (szCpuName, "Can't get computer name, error %d",
GetLastError ());
AfxMessageBox (szCpuName);
}
else
{
phe = gethostbyname (szCpuName);
if (phe != NULL)
{
for (iaddr=0; phe->h_addr_list[iaddr] != NULL; iaddr++)
{
csIpAddr = "";
for
(ifield=0; ifield < phe->h_length; ifield++)
{
if (ifield > 0)
csIpAddr += ".";
uField =
((BYTE*)phe->h_addr_list[iaddr])[ifield];
csAddrField.Format("%u",
uField);
csIpAddr +=
csAddrField;
}
// Do what you want with the address
here. I add it to a listbox.
m_ctrlListbox.AddString (csIpAddr);
}
}
}