现在的位置: 首页 > 综合 > 正文

linux应用编程:socket 常用API总结

2012年10月09日 ⁄ 综合 ⁄ 共 5941字 ⁄ 字号 评论关闭

1:代码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include<sys/ioctl.h>
#include<sys/socket.h>
#include<net/if.h>
//extern int h_errno;
char interfaceIpAddr[50];
int get_interface_ipAddr(char *ethName)
{
        int inet_sock;
        struct ifreq ifr;
        inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
        strcpy(ifr.ifr_name, ethName);
        if (ioctl(inet_sock, SIOCGIFADDR, &ifr) < 0)
        {
					perror("bind");
					exit(EXIT_FAILURE);
		    }
        sprintf(interfaceIpAddr,"%s", inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr));
}

void getInterfaceInfo(char* ethinterface)
{
		int i,sock_fd;
		struct ifreq ifreq;
		char mac[32];
		char ipbuf[16];
		int rcvbuf_size,sndbuf_size,type=0;
		socklen_t size;
    if((sock_fd=socket(AF_INET,SOCK_STREAM,0))<0)
    {
        perror("error");
        exit(EXIT_FAILURE);
    }
	size=sizeof(sndbuf_size);
	getsockopt(sock_fd,SOL_SOCKET,SO_SNDBUF,&sndbuf_size,&size);
	printf("sndbuf_size=%d size=%d\n",sndbuf_size,size);
	size=sizeof(rcvbuf_size);
	getsockopt(sock_fd,SOL_SOCKET,SO_RCVBUF,&rcvbuf_size,&size);
	printf("rcvbuf_size=%d size=%d\n",rcvbuf_size,size);
	size=sizeof(type);
	getsockopt(sock_fd,SOL_SOCKET,SO_TYPE,&type,&size);
	printf("socket type=%d\n",type);
    strcpy(ifreq.ifr_name,ethinterface);
    if(ioctl(sock_fd,SIOCGIFHWADDR,&ifreq)<0)
    {
        perror("error:");
        exit(EXIT_FAILURE);
    }
    for (i=0; i<6; i++)
    {
        sprintf(mac+3*i, "%02x:", (unsigned char)ifreq.ifr_hwaddr.sa_data[i]);
    }
    mac[17]='\0';
    printf("MAC:%s\n", mac);
    if(ioctl(sock_fd,SIOCGIFADDR,&ifreq)<0)
    {
        perror("error:");
        exit(EXIT_FAILURE);
    }
    printf("IP :%s\n",inet_ntoa(((struct sockaddr_in*)&ifreq.ifr_addr)->sin_addr));
    return 0;
}
void getHostByIpAdrr(char* ipaddr)
{
	u_int addr;
	struct hostent *hp;
	char **p;
	struct ifreq ifreq;
	if (ipaddr == NULL)
	{
		printf("usage:  IP-address\n");
		exit(EXIT_FAILURE);
	}
	if ((int) (addr = inet_addr(ipaddr)) == -1)
	{
		printf("IP-address must be of the form a.b.c.d\n");
		exit (EXIT_FAILURE);
	}
	hp=gethostbyaddr((char *) &addr, sizeof (addr), AF_INET);
	if (hp == NULL)
	{
		printf("host information for %s no found \n", ipaddr);
		exit (EXIT_FAILURE);
	}
	for (p = hp->h_addr_list; *p!=0;p++)
	{
		struct in_addr in;
		char **q;
		memcpy(&in.s_addr, *p, sizeof(in.s_addr));
		printf("%s\t%s",inet_ntoa(in), hp->h_name);
		for (q=hp->h_aliases;*q != 0; q++)
			printf("%s\t", *q);
		printf("\n");
	}
}
void ipaddrConvert()
{
	in_addr_t netAddr;
	struct in_addr net_addr,ret;
	char buf[128];
	memset(buf,'\0',128);
	netAddr=inet_addr("192.168.68.128");
	net_addr.s_addr=netAddr;

	printf("inet_addr(192.168.68.128)=0x%x\n",inet_addr("192.168.68.128"));
	printf("inet_network(192.168.68.128)=0x%x\n",inet_network("192.168.68.128"));

	printf("inet_ntoa(net)%s\n",inet_ntoa(net_addr));
	inet_aton("192.168.68.128",&ret);
	printf("test inet_aton,then inet_ntoa(ret)%s\n",inet_ntoa(ret));

	inet_pton(AF_INET,"192.168.68.128",&ret);
	inet_ntop(AF_INET,&ret,buf,128);
	printf("buf=%s\n",buf);
}
void getHostByName(char *hostname)
{
	char   *ptr,**pptr;
	char    str[INET_ADDRSTRLEN];
	struct hostent *hptr;

	{
		ptr = hostname;
		if ( (hptr = gethostbyname (ptr) ) == NULL)
		{
			printf("gethostbyname error for host: %s: %s",ptr, hstrerror (h_errno) );
			exit(EXIT_FAILURE);
		}
		printf ("official hostname: %s\n", hptr->h_name);
		for (pptr=hptr->h_aliases; *pptr!= NULL; pptr++)
		{
			printf ("\talias: %s\n", *pptr);
		}
		switch (hptr->h_addrtype)
		{
			case AF_INET:
				pptr = hptr->h_addr_list;
				for ( ; *pptr != NULL; pptr++)
					printf ("\taddress: %s\n",inet_ntop (hptr->h_addrtype, *pptr, str, sizeof (str)));
				break;

			default:
				printf("unknown address type");
				break;
		}
	}
}
void showInterfaceIpInfo(char *ethName)
{
	/*初始化网络,获取当前网络设备的信息*/
		int i;
		int sock;
		struct sockaddr_in sin;
		struct ifreq ifr;
		unsigned char	g_eth_name[16];
		unsigned char	g_macaddr[6];
		unsigned int	g_subnetmask;
		unsigned int	g_ipaddr;
		unsigned int	g_broadcast_ipaddr;
		sock = socket(AF_INET, SOCK_DGRAM, 0);
		if (sock == -1) {
			perror("socket");
		}

		strcpy(g_eth_name,ethName);
	    strcpy(ifr.ifr_name, g_eth_name);
		printf("eth name:\t%s\n", g_eth_name);


		// 获取并打印网卡地址
		if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
			perror("ioctl");
		}
		memcpy(g_macaddr, ifr.ifr_hwaddr.sa_data, 6);

		printf("local mac:\t");
		for(i=0;i<5;i++) {
			printf("%.2x:", g_macaddr[i]);
		}
		printf("%.2x\n",g_macaddr[i]);

		// 获取并打印IP地址
		if (ioctl(sock, SIOCGIFADDR, &ifr) < 0) {
			perror("ioctl");
		}
		memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
		g_ipaddr = sin.sin_addr.s_addr;
		printf("local %s:\t%s\n",g_eth_name, inet_ntoa(sin.sin_addr));

		// 获取并打印广播地址
		if (ioctl(sock, SIOCGIFBRDADDR, &ifr) < 0) {
			perror("ioctl");
		}
		memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
		g_broadcast_ipaddr = sin.sin_addr.s_addr;
		printf("broadcast:\t%s\n", inet_ntoa(sin.sin_addr));

		// 获取并打印子网掩码
		if (ioctl(sock, SIOCGIFNETMASK, &ifr) < 0) {
			perror("ioctl");
		}
		memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
		g_subnetmask = sin.sin_addr.s_addr;
		printf("subnetmask:\t%s\n", inet_ntoa(sin.sin_addr));

		close(sock);
}
usageError(const char *progName, const char *msg)
{
    if (msg != NULL)
    {
        fprintf(stderr, "%s", msg);
    }
    fprintf(stderr, "Usage: %s [options] parameter\n", progName);
    fprintf(stderr, "Usage: %s [n:i:p:fh] parameter\n", progName);
    fprintf(stderr, "Usage: %s  -n [hostName];				to execute:getHostByName()\n", progName);
    fprintf(stderr, "Usage: %s  -i [ipaddr];  				to execute:getHostByIpAdrr()\n", progName);
    fprintf(stderr, "Usage: %s  -p [interface;eth0/eth1];	to execute:getInterfaceInfo()\n", progName);
    fprintf(stderr, "Usage: %s  -f [addr convert function];	to execute:ipaddrConvert()\n", progName);
    fprintf(stderr, "Usage: %s  -h ;to execute:help\n", progName);

    exit(EXIT_FAILURE);
}
int main(int argc, char **argv)
{
	int opt;
	if(argc==1)
	{
		usageError(argv[0], NULL);
	}

#if 0
	printf("\n\n****************************************************************************************************\n");
	system("cat /etc/hosts");
	printf("****************************************************************************************************\n\n");
#endif
	while ((opt = getopt(argc, argv, "n:i:p:fh")) != -1) {
		switch (opt) {
		case 'n':
			if(optarg!=NULL)
			{
				printf("optopt:%c   :%s\n",optopt,optarg);
				getHostByName(optarg);
			}
			else
			{
				usageError(argv[0], NULL);
			}
			break;
		case 'i':
			if(optarg!=NULL)
			{
				printf("optopt:%c   :%s\n",optopt,optarg);
				getHostByIpAdrr(optarg);
			}
			else
			{
				usageError(argv[0], NULL);
			}
			break;
		case 'p':
			if(optarg!=NULL)
			{
				printf("optopt:%c   :%s\n",optopt,optarg);
				getInterfaceInfo(optarg);
				showInterfaceIpInfo(optarg);
			}
			else
			{
				usageError(argv[0], NULL);
			}
			break;
		case 'f':
				ipaddrConvert();
			break;
		default:

			usageError(argv[0], NULL);
		}
	}

	exit(0);
}

2:执行结果



抱歉!评论已关闭.