C程序:獲取本機IP地址

// 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;
}

 

發佈了23 篇原創文章 · 獲贊 2 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章