1、getsockname
用于获取自己的ip和端口
使用举例:
struct sockaddr_in localaddr;
socklen_t len = sizeof(localaddr);
memset(&localaddr,0,sizeof(localaddr));
//获取自己的ip和端口
if(getsockname(sk_fd,(struct sockaddr*)&localaddr,&len) == -1)
handle_error("getsockname");
printf("localaddr ip = %s\tport = %d\n",inet_ntoa(localaddr.sin_addr),ntohs(localaddr.sin_port));
2、getpeername
根据已连接的套接字,获取对等方地址信息
使用举例
//获取对等方地址信息
struct sockaddr_in peeraddr;
socklen_t leng = sizeof(peeraddr);
memset(&peeraddr,0,sizeof(peeraddr));
if(getpeername(sk_fd,(struct sockaddr*)&peeraddr,&leng) == -1)
handle_error("getpeername");
printf("peeraddr ip = %s\tport = %d\n",inet_ntoa(peeraddr.sin_addr),ntohs(peeraddr.sin_port));
3、gethostname
获取当前主机名,该名字常用于给其他函数做参数
使用举例
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define handle_error(msg) \
do{perror(msg);exit(EXIT_FAILURE);}while(0)
int main()
{
char hostname[64] = {0};
if(gethostname(hostname,sizeof(hostname)) == -1)
handle_error("gethostname");
printf("hostname = %s\n", hostname);
return 0;
}
4、gethostbyname
通过主机名,获取主机的ip地址
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define handle_error(msg) \
do{perror(msg);exit(EXIT_FAILURE);}while(0)
int main()
{
struct hostent *host = gethostbyname("www.baidu.com");
if(host == NULL)
handle_error("gethostbyname");
printf("h_name = %s\n", host->h_name);
int i = 0;
while(host->h_aliases[i] != NULL)
{
printf("h_aliases = %s\n", host->h_aliases[i]);
++i;
}
if(host->h_addrtype == AF_INET)
printf("h_addrtype = AF_INET\n");
else if(host->h_addrtype == AF_INET6)
printf("h_addrtype = AF_INET6\n");
printf("h_length = %d\n", host->h_length);
i = 0;
while(host->h_addr_list[i] != NULL)
{
printf("ip = %s\n",inet_ntoa(*(struct in_addr *)host->h_addr_list[i]));
++i;
}
return 0;
}