Linux:getsockname、getpeername、gethostname、gethostbyname

/ Linux / 没有评论 / 1997浏览

getsockname:得到本地的地址和端口号

struct sockaddr_in localaddr;
	socklen_t addrlen = sizeof(localaddr);
	if(getsockname(sock, (struct sockaddr *)&localaddr, &addrlen) < 0)
	{
		ERR_EXIT("getsock");
	}
	printf("ip=%s port=%d\n",inet_ntoa(localaddr.sin_addr),ntohs(localaddr.sin_port));

getpeername:得到对等方的地址和端口号

gethostname:获取主机名。gethostbyname:通过主机名获取主机上的所有ip地址

/*
readline 实现,遇到\n 就算作是一条消息,可以解决粘包问题(遇到\r\n,在包尾,ftp协议就是这么做的)
*/

#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <stdio.h>

#include <netdb.h>
#define ERR_EXIT(m)do{perror(m);exit(EXIT_FAILURE);}while(0)

int getlocalip(char *ip)
{
	char host[100] ={0};
	if(gethostname(host,sizeof(host)) < 0)
	{
		return -1;
	}
	struct hostent *hp;

	if((hp = gethostbyname(host)) == NULL)
	{
		ERR_EXIT("gethostbyname");
	}
	strcpy(ip,inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]));

	return 0;
}

int main(void)
{
	char host[100] ={0};
	if(gethostname(host,sizeof(host)) < 0)
	{
		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;
}