简单的Winsock例程

类别:VC语言 点击:0 评论:0 推荐:

      这个程序的功能用来获得本机的主机名(Hostname)和IP地址。

      程序如下:

       #include <stdio.h>
       #include <winsock.h>

       int doit(int rgc,char** rgv)
       {
           char ac[80];
           struct hostent* phe;
           struct in_addr addr;
           int i;
           if(gethostname(ac,sizeof(ac))==SOCKET_ERROR)
           {
             printf("Error %d when getting local hostname.\n",WSAGetLastError());
             return 1;
            }
         printf("The host name is:%s\n",ac);
         phe=gethostbyname(ac);
         if(phe==0)
         {
            printf("Error!Bad host lookup.\n");
            return 1;
         }
           for (i=0;phe->h_addr_list[i]!=0;++i)
         {
            memcpy(&addr,phe->h_addr_list[i],sizeof(struct in_addr));
            printf("Address %d is %s.\n",i,inet_ntoa(addr));
          }
          return 0;
      }
      int main(int argc,char* argv[])
      {
         WSADATA wsaData;
         int retval;
         if(WSAStartup(MAKEWORD(1,1),&wsaData)!=0)
         {
            return 255;
          }
         retval=doit(argc,argv);
         WSACleanup();
         return retval;
       }

本文地址:http://com.8s8s.com/it/it3304.htm