views:

431

answers:

6

Hi,

I would like to send an email from an application that contains the current ip address of the machine.

I have the email code in place and it works. I just need to add the ipaddress to the body of the email (ie I am not doing anything programmatically with the IP address).

I was hoping there was a really simple way like running ipconfig via the system command and grabbing the resultant text.

I would rather not have to open a socket.

Thanks,

A: 

I believe you may need to look into winsock2.h

PSU_Kardi
+1  A: 

Use either gethostbyname (deprecated) or the newer getaddrinfo. The MSDN links contain examples as well.

dirkgently
A: 

Try this.

Stu
+1  A: 

EDIT: Well, it helps if i read that you are using VC++ and not c#.....

So you can ignore my response, or maybe use it as a guide...

here ya go:

using System;
using System.Net;


namespace testProgram
{
    class Program
    {
        static void Main()
        {
            String strHostName = string.Empty;
            // Getting Ip address of local machine...
            // First get the host name of local machine.
            strHostName = Dns.GetHostName();
            Console.WriteLine("Local Machine's Host Name: " + strHostName);


            // Then using host name, get the IP address list..
            IPHostEntry ipEntry = Dns.GetHostEntry(strHostName);
            IPAddress[] addr = ipEntry.AddressList;

            for (int i = 0; i < addr.Length; i++)
            {
                Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
            }
            Console.ReadLine();

        }
    }

}

this will give you all the information you need and then some, you can parse out what you need and don't need.

Jason Heine
+1  A: 

This code will loop all adapters and check for the first which is up.

#include <afxtempl.h>
#include <afxsock.h>
#include <iphlpapi.h>

u_long GetFirstIpAddressUp(SOCKET s)
{
#define MAX_ADAPTERS    30
#pragma comment(lib, "Iphlpapi.lib")
    IP_ADAPTER_ADDRESSES AdapterAddresses[MAX_ADAPTERS];           
    PIP_ADAPTER_ADDRESSES pAdapterAddresses = AdapterAddresses;                                              
    DWORD dwBufLen = sizeof(AdapterAddresses);
    if (GetAdaptersAddresses(AF_INET, 0, NULL, AdapterAddresses,&dwBufLen) == ERROR_SUCCESS)
    {
        do {
         if ((pAdapterAddresses->OperStatus == IfOperStatusUp))
            {
                sockaddr_in* pAdr = (sockaddr_in*)pAdapterAddresses->FirstUnicastAddress->Address.lpSockaddr;
                return pAdr->sin_addr.S_un.S_addr;
            }
        pAdapterAddresses = pAdapterAddresses->Next;
        } while(pAdapterAddresses);
    }
    return INADDR_ANY;  // No adapters are up
}
A: 

Certainly getaddrinfo works in your case, but I thought I'd mention that if you every want to more than just read the ip you can use the windows IP Helper api to do most of what the ipconfig utility does.

Jim In Texas