一、gethostname,gethostbyname的用法

这两个函数可以用来获取主机的信息。
gethostname:获取主机的名字
gethostbyname:通过名字获取其他的信息(比如ip)

1.gethostname:
man手册里面的解释(部分):
       #include <unistd.h>
       int gethostname(char *name, size_t len);
       int sethostname(const char *name, size_t len);
DESCRIPTION
       These  system calls are used to access or to change the hostname of the
       current processor.
RETURN VALUE
       On  success,  zero is returned.  On error, -1 is returned, and errno is
       set appropriately.

2.gethostbyname:
       #include <netdb.h>
       extern int h_errno;
       struct hostent *gethostbyname(const char *name);

可以看到获取的内容保存在一个指针里面。下面我们来看这个指针指向的内容:
       The hostent structure is defined in <netdb.h> as follows:
           struct hostent {
               char  *h_name;            /* official name of host */
               char **h_aliases;         /* alias list */
               int    h_addrtype;        /* host address type */
               int    h_length;          /* length of address */
               char **h_addr_list;       /* list of addresses */
           }
           #define h_addr h_addr_list[0] /* for backward compatibility */
       The members of the hostent structure are:
       h_name The official name of the host.
       h_aliases
              An array of alternative names for the host, terminated by a NULL
              pointer.
       h_addrtype
              The type of address; always AF_INET or AF_INET6 at present.
       h_length
              The length of the address in bytes.
       h_addr_list
              An array of pointers to network addresses for the host (in  net‐
              work byte order), terminated by a NULL pointer.
       h_addr The first address in h_addr_list for backward compatibility.
然后是返回值:
失败返回空。否则返回值指向我们需要的信息的那个结构体。
RETURN VALUE
       The  gethostbyname()  and  gethostbyaddr() functions return the hostent
       structure or a NULL pointer if an error occurs.  On error, the  h_errno
       variable  holds  an  error number.  When non-NULL, the return value may
       point at static data, see the notes below.

实例:

#include<stdio.h>
#include<unistd.h>
#include<netdb.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
int main()
{ printf("%s() +++ hello\n", __func__);
char host[] = {};
if(gethostname(host, sizeof(host)) < )
{
perror("gethostname");
return -;
} printf("host:%s\n", host);
struct hostent *myhost = NULL;
if(!(myhost = gethostbyname(host)))
{
perror("gethostbyname");
return -;
}
int i = ;
while(myhost && myhost->h_addr_list[i])
{
printf("ip%d:%s\n", i+, inet_ntoa(*(struct in_addr*)myhost->h_addr_list[i]));
i++;
}
return ;
}

运行:

xcy@xcy-virtual-machine:~/test/gethost$ ./a.out 
main() +++ hello
host:xcy-virtual-machine
ip1:127.0.1.1

二、关于getsockname和getpeername

1.getsockname:获取一个套接字的名字。获取本地的地址和端口信息。
#include <sys/socket.h>
int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
失败返回-1,成功返回0。addr是输入参数,addrlen是输入输出参数

2.getpeername:获取socket的对方的地址
#include <sys/socket.h>
int getpeername(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
失败返回-1,成功返回0。addr是输入参数,addrlen是输入输出参数

注意:
1)对于server来说:
bind以后就可以调用getsockname来获取本地地址和端口了,只不过这样没啥意义,因为就是自己绑定的。
只有在accept以后(就是有连接之后才)才能用getpeername获取client的ip和端口。(client的ip和port也可以在accept函数的第二个参数中带出)
2)对于client来说:
创建socket并不会分配ip和端口。用getsockname获取出来的数据全是0.
在连接(connect)之后才可以用getsockname获取自己的ip和端口。也可以用getpeername获取服务器的。

3.如何使用:伪代码
客户端代码:

......
if(connect(sockfd, (struct sockaddr*)&addr, sizeof(addr)) < )
{
perror("connect");
return -;
}
// 在连接以后才能获取
struct sockaddr_in addr2;
socklen_t len = sizeof(addr2); //
//if(getsockname(sockfd, (struct sockaddr*)&addr2, &len) < 0) // 这个是获取自己的ip和端口
if(getpeername(sockfd, (struct sockaddr*)&addr2, &len) < ) // 这个是获取连接方的
{
perror("getsockname");
return -;
}
printf("Get: port:%d, ip:%s\n", ntohs(addr2.sin_port), inet_ntoa(addr2.sin_addr));
......

服务端代码:

。。。// 前面有bind,listen等动作,这里只处理连接的
while()
{
int conn = accept(listenfd, (struct sockaddr*)&connaddr, &len);
if(conn < )
{
perror("accept");
return -;
}
// 这里的connaddr就跟下面getpeername获取的一样
char strip[] = {};
char *ip = inet_ntoa(connaddr.sin_addr);
strcpy(strip, ip);
printf("new client connect,ip:%s, port:%d\n", strip,ntohs(connaddr.sin_port));
struct sockaddr_in addr2;
socklen_t len = sizeof(addr2);
// if(getsockname(conn, (struct sockaddr*)&addr2, &len) < 0) // 这个是获取自己的ip和端口
if(getpeername(conn, (struct sockaddr*)&addr2, &len) < ) // 这个是获取连接方的。这样其实跟accept参数带出来的数据是一样的
{
perror("getsockname");
return -;
}
printf("get: port:%d, ip:%s\n", ntohs(addr2.sin_port), inet_ntoa(addr2.sin_addr));
deal_connect(conn); // 用来处理连接的函数
}
。。。。。。

关于 getsockname、getpeername和gethostname、gethostbyname的更多相关文章

  1. 获取主机信息,网络信息AIP,getsockname,getpeername,getservbyname,getservbyport,inet_ntop,inet_pton

    获取主机信息 1.ip地址转换,主机字节序 <---> 网络字节序 #include <arpa/inet.h> int inet_pton(int af, const cha ...

  2. 关于getsockname()/getpeername()函数第一次被调用得到0.0.0.0结果的说明

    最近阅读UNIX网络编程第四章时,书本末尾介绍了两个函数getsockname()和getpeername(),可以用于获取服务器端和客户端的IP地址与端口,原本很简单的两个函数,过一眼即明白函数的用 ...

  3. 套接字之 getsockname && getpeername

    getsockname-获取本地地址:比如,在绑定的时候设置端口号为0由系统自动选择端口绑定,或者使用了INADDR_ANY通配所有地址的情况下,后面需要用到具体的地址和端口,就可以用getsockn ...

  4. gethostname gethostbyname gethostbyaddr 获得主机相关信息

    网络编程里经常需要获得主机的相关信息,下面围绕相关的函数以及用到的结构来说明. 获得主机名:int gethostname( char FAR *name, //[out] Pointer to a ...

  5. getsockname()/getpeername()函数第一次被调用得到0.0.0.0结果

    int getsockname(int sockfd, struct sockaddr *addr, socklen_t *addrlen); getsockname() returns the cu ...

  6. 一个进程发起多个连接和gethostbyname等函数

    一.在前面讲过的最简单的回射客户/服务器程序中,一个客户端即一个进程,只会发起一个连接,只要稍微修改一下就可以让一个客户端发起多个连 接,然后只利用其中一个连接发送数据. 先来认识一个函数getsoc ...

  7. net programming guid

    Beej's Guide to Network Programming Using Internet Sockets Brian "Beej Jorgensen" Hallbeej ...

  8. socket编程头文件分析

    在socket网络编程中经常用到一些宏定义.结构和函数,这些经常包含在相关的头文件中,使用时直接include相关头文件即可.下面简单描述下相关的一些结构及头文件. 1. sockaddr  / bi ...

  9. UNP总结 Chapter 11 名字与地址转换

    本章讲述在名字和数值地址间进行转换的函数:gethostbyname和gethostbyaddr在主机名字与IP地址间进行转换,getservbyname和getservbyport在服务器名字和端口 ...

随机推荐

  1. 走进Spark生态圈:环境的安装与配置

    什么是Spark? Apache Spark 是一种大规模数据处理的快速通用引擎,使用基于内存的处理方式,较与MapReduce而言,解决了其shuffle多次IO操作带来的效率低问题,从而达到快速的 ...

  2. Python异步处理

    回调函数是实现异步操作的常用手法 1.callback版本的示例,其中framework调用logic,在完成某些操作或者接收到信号后,用callback返回异步结果 #!/usr/bin/env p ...

  3. 准备冲锋 golang入坑系列

    史前摘要: 本来想写读前必读,但连续几篇博文都写读前必读,感觉就没有了新意. 所以换成史前摘要,反正是一个意思. 此摘要的目的仍然是提醒点击而来的同学,本系列最新文章在这里.放到博客园的目的是为了方便 ...

  4. Java数据结构和算法(一)——简介

    本系列博客我们将学习数据结构和算法,为什么要学习数据结构和算法,这里我举个简单的例子. 编程好比是一辆汽车,而数据结构和算法是汽车内部的变速箱.一个开车的人不懂变速箱的原理也是能开车的,同理一个不懂数 ...

  5. 苹果快速的修复了Mac OS High Sierra 上出现了root的漏洞

    最近苹果因为Mac最新系统 Mac OS High Sierra 上出现了root的漏洞走上了风口浪尖,不过还好,在一封苹果给科技媒体'9to5 Mac'的回复中得知,苹果在接收到报告之后,立即展开修 ...

  6. PHP防止SQL注入和XSS攻击

    PHP防止SQL注入和XSS攻击PHP防范SQL注入是一个非常重要的安全手段.一个优秀的PHP程序员除了要能顺利的编写代码,还需要具备使程序处于安全环境下的能力.说到网站安全,就不得不提到SQL注入( ...

  7. 分布式监控系统Zabbix3.2给异常添加邮件报警

    在前一篇 分布式监控系统Zabbix3.2跳坑指南 中已安装好服务端和客户端,此处客户端是被监控的服务器,可能有上百台服务器.监控的目的一个是可以查看历史状态,可以对比零晨和工作区间数据的对比,以便后 ...

  8. warning: C4819: 该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失

    ------问题-------------------- Qt项目使用 VC++ 编译器出现此错误. warning: C4819: 该文件包含不能在当前代码页(936)中表示的字符.请将该文件保存为 ...

  9. js实现关键词高亮显示 正则匹配

    html 和ajax 部分就不写了,只需将需要匹配的文字传进去就可以了 比如匹配后台传回的字符串data.content中的关键词:直接调用: data.content = highLightKeyw ...

  10. leetcode算法题2: 合并两个二叉树。递归,如何切入并保持清醒?

    /* Given two binary trees and imagine that when you put one of them to cover the other, some nodes o ...