C程序:获取本机IP地址

来源:互联网 发布:mysql高可用架构方案 编辑:程序博客网 时间:2024/05/06 04:34

// louis 2004-7-27


#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
 int ret;
 char buf[1024];
 WORD wVersionRequested;
 WSADATA wsaData;
 int err;

 struct hostent *host;

 // socket initialize
 wVersionRequested = MAKEWORD( 2, 2 );
 err = WSAStartup( wVersionRequested, &wsaData );
 if ( err != 0 ) {
  return -1;
 }

 memset(buf, 0, 1024);

 // get hostname
 ret = gethostname(buf, 1024);
 if(ret != 0)
 {
  printf("return is %d/n", ret);
  ret = WSAGetLastError();
  printf("specific error is %d/n", ret);
  printf("gethostname error./n");
 }else
  printf("hostname is %s/n", buf);

 // get host ip address
 host = gethostbyname(buf);
 if(host == NULL)
 {
  perror("gethostbyname");
  return -1;
 }else
  //printf("ip address is %s/n", inet_ntoa(*(host->h_addr_list)));
  printf("ip address is %s/n", inet_ntoa(*(in_addr *)host->h_addr_list[0]));

 return 0;
}

 

原创粉丝点击