linux c 網路編程:用網域名稱擷取IP地址或者用IP擷取網域名稱 網路位址轉譯成整型 主機字元順序與網路位元組順序的轉換

來源:互聯網
上載者:User

標籤:網路   c   

用網域名稱擷取IP地址或者用IP擷取網域名稱

#include<stdio.h>#include<sys/socket.h>#include<netdb.h>int main(int argc,char **aggv){        struct hostent *host;        char hostname[]="www.163.com";        char hostname2[]="www.baidu.com";        struct in_addr in;        struct sockaddr_in addr_in;        int h_errno;        char addr[]="202.108.249.216";        if((host=gethostbyname(hostname))!=NULL)                {                        memcpy(&addr_in.sin_addr.s_addr,host->h_addr,4);                        in.s_addr=addr_in.sin_addr.s_addr;                        printf("Domain name : %s \n",hostname);                        printf("IP length is: %d \n",host->h_length);                        printf("Type : %d \n",host->h_addrtype);                        printf("IP : %s \n",inet_ntoa(in));                }        if(((host=gethostbyaddr(addr,sizeof(addr),AF_INET)))!=(struct hostnet *)NULL)        {                memcpy(&addr_in.sin_addr.s_addr,host->h_addr,4);                        in.s_addr=addr_in.sin_addr.s_addr;                        printf("\n---------------------\n");                        printf("Domain name : %s \n",hostname);                        printf("IP length is: %d \n",host->h_length);                        printf("Type : %d \n",host->h_addrtype);                        printf("IP : %s \n",inet_ntoa(in));        }        return 0;}




#include<stdio.h>#include<netdb.h>#include<arpa/inet.h>int main(){        int i ;        for(i=0;i<6;i++)        printf("%d  %s \n",i,hstrerror(i));//捕獲錯誤編號        char cp[]="192.168.0.84";        printf("%ld\n",inet_addr(cp));
//將網路位址轉譯成整型
struct in_addr ip; ip.s_addr=16885952; printf("%s\n",inet_ntoa(ip));
//將整型轉換成網路地址
long local; int port; local=123456; port=1024; printf("net: %d\n",htonl(local));//主機字元順序與網路位元組順序的轉換 printf("net: %d\n",htonl(port)); printf("local: %d\n",ntohl(htonl(local))); printf("local: %d\n",ntohl(htonl(port))); return 0;}





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.