linux應用編程:socket 常用API總結

來源:互聯網
上載者:User
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 charg_eth_name[16];unsigned charg_macaddr[6];unsigned intg_subnetmask;unsigned intg_ipaddr;unsigned intg_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 0printf("\n\n****************************************************************************************************\n");system("cat /etc/hosts");printf("****************************************************************************************************\n\n");#endifwhile ((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:執行結果



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.