0

all i already had a "socketfd", and i was wondering how to use it to retrieve the local ip address. under linux, i can do something like this(not exactly correct):

struct ifreq ifr;
ifr.ifr_addr.sa_family = AF_INET;
ioctl(socketfd, SIOCGIFADDR, &ifr);
char *address = inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr);

but, on Windows, how can i achieve the same goal? (not using MFC) many thanks.

edit: maybe my host has multiple ip addresses, and i want the one "connected" with "socketfd".

Heisenburgor
  • 107
  • 1
  • 6

2 Answers2

1
WORD wVersionRequested;
      WSADATA wsaData;
      char name[255];
      CString ip;
      PHOSTENT hostinfo;
      wVersionRequested = MAKEWORD( 2, 0 );

      if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
      {

            if( gethostname ( name, sizeof(name)) == 0)
            {
                  if((hostinfo = gethostbyname(name)) != NULL)
                  {
                        ip = inet_ntoa (*(struct in_addr *)*hostinfo->h_addr_list);
                  }
            }

            WSACleanup( );
      } 

with #include <winsock2.h>

Sergey Vedernikov
  • 7,609
  • 2
  • 25
  • 27
  • my host has several ip addresses , and i want the one "connected" with "socketfd",so... – Heisenburgor Feb 25 '11 at 06:38
  • I tried this code and getting the following errors ... `error: unknown type name 'CString'` Full error and code here... https://pastebin.com/shcZG73E –  Mar 11 '18 at 01:50
1

If the socket is connected, then getsockname() on it will fill a struct sockaddr with the local name for the socket. This works on both OSes (and anything with BSD sockets).

caf
  • 233,326
  • 40
  • 323
  • 462