winsock中的gethostname与gethostbyname

linux系统中,gethostname与gethostbyname的使用,网上有很多资料可以查到。在此阐述的是windows下如何使用这两个获取IP地址。

贴上实例程序:

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<winsock2.h>
#include<windows.h>
#pragma comment(lib,  "ws2_32.lib")
using  namespace std;

#define ERR_EXIT(m) \
    do\
    {\
        perror(m);\
        exit(EXIT_FAILURE);\
    } while( 0)

int getlocalip( char *ip)
{
     char host[ 100] ={ "sina.com.cn"};
     if(gethostname(host, sizeof(host))< 0)
         return - 1;
     struct hostent *hp;
     if((hp =gethostbyname(host))== NULL)
         return - 1;
    strcpy(ip,inet_ntoa(*( struct in_addr*)hp->h_addr));   //h_addr代表主机IP
     return  0;
}
int main()
{
        WSADATA wsd;

     if(WSAStartup(MAKEWORD( 2, 2),&wsd)!= 0)
    {
        cout<< "WSAStartup failed!"<<endl;
        ERR_EXIT( "WSAStartup");
    }

     char host[ 100] ={ 0};
     if(gethostname(host, sizeof(host)) ==SOCKET_ERROR)   //获取主机名
        ERR_EXIT( "gethostname");

     struct hostent *hp;
     if((hp = gethostbyname(host)) == NULL)   //通过主机名获取更多信息
        ERR_EXIT( "gethostbyname");

     int i = 0;
     while(hp->h_addr_list[i]!= NULL)
    {
        printf( "%s\n",inet_ntoa(*( struct in_addr*)hp->h_addr_list[i]));
        i++;
    }

     char ip[ 16] ={ 0};
    getlocalip(ip);
    printf( "localip =%s\n",ip);
     return  0;   
}

根据以上代码做分析:

1.gethostname以及gethostbyname的参数就不做说明了;

2.winsock中,socket通信是使用winsock2.h头文件。使用任何网络API都需要使用WSAStartup()加载动态库。实例代码中,如果不首先使用WSAStartup,程序会在gethostname处退出,并且显示no error;使用GetLastError()获得错误代码为10039;也就是未使用WSAStartup加载动态库的原因;

3.许多网络API 还需要ws2_32.lib库的支持。例如实例代码中的inet_ntoa等;或者会报错。错误显示:error LNK2019:无法解析的外部符号...


说的不对的地方,欢迎更正,及补充。




  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值