How to get the ip address under Windows

故事扮演 提交于 2019-12-11 16:55:53

问题


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".


回答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).




回答2:


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>



来源:https://stackoverflow.com/questions/5114305/how-to-get-the-ip-address-under-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!